diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7c5ef13f898..6181265988a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -34,9 +34,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-core-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-core-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-core-x7- + ${{ runner.os }}-npm-core-x8- - name: install npm dependencies run: npm install @@ -47,57 +47,6 @@ jobs: - name: test:typings run: npm run test:typings - storage-pouchdb: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - name: Set node version - uses: actions/setup-node@v3 - with: - node-version-file: '.nvmrc' - - - name: Reuse npm cache folder - uses: actions/cache@v2 - env: - cache-name: cache-node-modules - with: - path: | - ~/.npm - ./node_modules - key: ${{ runner.os }}-npm-storage-pouchdb-x7-${{ hashFiles('**/package.json') }} - restore-keys: | - ${{ runner.os }}-npm-storage-pouchdb-x7- - - - name: install npm dependencies - run: npm install - - - name: build - run: npm run build - - - name: npm run test:node:pouchdb - run: npm run test:node:pouchdb - - - name: npm run test:fast:pouchdb - run: npm run test:fast:pouchdb - - - name: node example - working-directory: ./examples/node - run: | - npm install - npm run test - - - name: npm run test:browser:pouchdb - uses: GabrielBB/xvfb-action@v1 - with: - run: npm run test:browser:pouchdb - - - name: performance test - uses: GabrielBB/xvfb-action@v1 - with: - run: npm run test:performance:pouchdb:browser - - - run: npm run test:performance:pouchdb:node - # run the node tests for the LokiJS RxStorage storage-lokijs: runs-on: ubuntu-20.04 @@ -116,9 +65,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-loki-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-loki-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-loki-x7- + ${{ runner.os }}-npm-loki-x8- - name: install npm dependencies run: npm install @@ -160,9 +109,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-memory-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-memory-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-memory-x7- + ${{ runner.os }}-npm-memory-x8- - name: install npm dependencies run: npm install @@ -191,6 +140,12 @@ jobs: - run: npm run test:performance:memory:node + - name: node example + working-directory: ./examples/node + run: | + npm install + npm run test + storage-remote: runs-on: ubuntu-20.04 @@ -209,9 +164,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-remote-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-remote-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-remote-x7- + ${{ runner.os }}-npm-remote-x8- - name: install npm dependencies run: npm install @@ -226,9 +181,7 @@ jobs: with: run: npm run test:browser:remote - # run the node tests for the LokiJS RxStorage in a different - # task to run in parallel. - node-dexie-worker: + storage-worker-dexie: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -245,9 +198,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-loki-worker-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-loki-worker-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-loki-worker-x7- + ${{ runner.os }}-npm-loki-worker-x8- - name: install npm dependencies run: npm install @@ -285,9 +238,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-storage-dexie-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-storage-dexie-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-storage-dexie-x7- + ${{ runner.os }}-npm-storage-dexie-x8- - name: install npm dependencies run: npm install @@ -331,9 +284,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-storage-foundationdb-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-storage-foundationdb-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-storage-foundationdb-x7- + ${{ runner.os }}-npm-storage-foundationdb-x8- - name: install FoundationDB client and server working-directory: ./scripts @@ -351,8 +304,8 @@ jobs: - run: npm run test:fast:foundationdb - run: npm run test:performance:foundationdb - angular: - runs-on: ubuntu-20.04 + example-angular: + runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v2 #- name: install dependencies @@ -372,9 +325,9 @@ jobs: ./node_modules ./examples/angular/node_modules # invalidate cache when any package.json changes - key: ${{ runner.os }}-npm-angular-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-angular-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-angular-x7- + ${{ runner.os }}-npm-angular-x8- - name: prepare RxDB core run: | @@ -392,9 +345,9 @@ jobs: - name: angular test # uses: DevExpress/testcafe-action@latest - uses: GabrielBB/xvfb-action@v1 + uses: GabrielBB/xvfb-action@v1.6 with: - working-directory: ./examples/angular #optional + working-directory: ./examples/angular run: npm run test:build - name: angular test ssr @@ -418,9 +371,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-test-builds-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-test-builds-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-test-builds-x7- + ${{ runner.os }}-npm-test-builds-x8- - name: prepare RxDB core run: | @@ -451,9 +404,9 @@ jobs: path: | ~/.npm ./node_modules - key: ${{ runner.os }}-npm-test-code-style-x7-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-test-code-style-x8-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-test-code-style-x7- + ${{ runner.os }}-npm-test-code-style-x8- - name: prepare RxDB core run: | @@ -492,7 +445,7 @@ jobs: ignore_words_file: config/codespellignore.txt path: test - electron: + example-electron: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -520,7 +473,7 @@ jobs: working-directory: ./examples/electron run: npm run test - react: + example-react: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -548,7 +501,7 @@ jobs: working-directory: ./examples/react run: npm run test:build - react-native-expo: + example-react-native-expo: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -574,7 +527,7 @@ jobs: yarn test:bundle - supabase: + example-supabase: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -592,9 +545,9 @@ jobs: ./node_modules ./examples/supabase/node_modules # invalidate cache when any package-lock.json changes - key: ${{ runner.os }}-npm-supabase-x1-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-supabase-x2-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-supabase-x1 + ${{ runner.os }}-npm-supabase-x2 - name: Cache Docker layers uses: actions/cache@v2 with: @@ -631,7 +584,7 @@ jobs: working-directory: ./examples/supabase run: npm run test:dexie - vue: + example-vue: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -660,7 +613,7 @@ jobs: working-directory: ./examples/vue run: npm run test - svelte: + example-svelte: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -715,7 +668,7 @@ jobs: working-directory: ./examples/vite-vanilla-ts run: npm run test - graphql: + example-graphql: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -738,11 +691,6 @@ jobs: - name: build working-directory: ./examples/graphql run: npm run build - - name: test test:pouchdb - uses: GabrielBB/xvfb-action@v1.6 - with: - working-directory: ./examples/graphql - run: npm run test:pouchdb - name: test test:lokijs uses: GabrielBB/xvfb-action@v1.6 with: @@ -754,45 +702,7 @@ jobs: working-directory: ./examples/graphql run: npm run test:dexie - - test-couchdb-integration: - # The type of runner that the job will run on - runs-on: ubuntu-20.04 - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - - uses: actions/checkout@v2 - - uses: docker/setup-buildx-action@v1 - - - name: install linux - run: sudo apt-get update && sudo apt-get install -y chromium-browser - - # https://github.com/docker/build-push-action/blob/master/docs/advanced/cache.md#github-cache - - name: Cache Docker layers - uses: actions/cache@v2 - with: - path: /tmp/.buildx-cache - key: ${{ runner.os }}-buildx-${{ github.sha }} - restore-keys: | - ${{ runner.os }}-buildx - - - name: start couchdb container - run: docker run -d -p 5984:5984 --rm --name rxdb-couchdb couchdb:2.1.1 - - - name: Set node version - uses: actions/setup-node@v3 - with: - node-version-file: '.nvmrc' - - - name: prepare RxDB core - run: | - npm install - npm run build - - - name: npm run test:couchdb - run: npm run test:couchdb - - test-flutter: + example-flutter: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 @@ -814,9 +724,9 @@ jobs: ~/.npm ./node_modules ./examples/flutter/javascript/node_modules - key: ${{ runner.os }}-npm-flutter-x8-${{ hashFiles('**/package.json') }} + key: ${{ runner.os }}-npm-flutter-x9-${{ hashFiles('**/package.json') }} restore-keys: | - ${{ runner.os }}-npm-flutter-x8- + ${{ runner.os }}-npm-flutter-x9- - name: prepare RxDB core run: | npm install --legacy-peer-deps @@ -859,23 +769,6 @@ jobs: npm install npm test - test-multiple-times-pouchdb: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - name: Set node version - uses: actions/setup-node@v3 - with: - node-version-file: '.nvmrc' - - name: prepare RxDB core - run: | - npm install - npm run build - # in the past we had tests that failed randomly - # to prevent this we run the tests in fast-mode 10 times - - name: unit tests 10 times - run: for i in `seq 10`; do npm run test:fast:pouchdb; done - test-multiple-times-lokijs: runs-on: ubuntu-20.04 steps: @@ -900,28 +793,26 @@ jobs: # But this is a bad metric so I destroy it by obfuscating the actual download count. # This should never increase the total time of the CI. If this task takes longer then all other tasks, # decrease the download calls. - download: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v2 - - name: Set node version - uses: actions/setup-node@v3 - with: - node-version-file: '.nvmrc' - - name: download X times - run: | - npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit - npm cache clean --force - rm -rf node_modules - npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit - npm cache clean --force - rm -rf node_modules - npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit - npm cache clean --force - rm -rf node_modules - npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit - npm cache clean --force - rm -rf node_modules - npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit - - + # download: + # runs-on: ubuntu-20.04 + # steps: + # - uses: actions/checkout@v2 + # - name: Set node version + # uses: actions/setup-node@v3 + # with: + # node-version-file: '.nvmrc' + # - name: download X times + # run: | + # npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit + # npm cache clean --force + # rm -rf node_modules + # npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit + # npm cache clean --force + # rm -rf node_modules + # npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit + # npm cache clean --force + # rm -rf node_modules + # npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit + # npm cache clean --force + # rm -rf node_modules + # npm i rxdb --no-optional --skip-installed --ignore-scripts --no-audit diff --git a/.nvmrc b/.nvmrc index 1b575ab8beb..e44a38e0803 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v18.4.0 +v18.12.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 13e4dba6094..064125cf642 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ # RxDB Changelog +- CHANGE Do not use hash for revisions but use database instance token instead. +- Remove the deprecated PouchDB RxStorage. +- CHANGE (memory RxStorage) do not clean up database state on closing of the storage, only on `remove()`. +- REMOVE old `replication-couchdb` plugin. Rename `replication-couchdb-new` to `replication-couchdb`. +- FIX CouchDB replication: Use correct default fetch method. +- CHANGE use plain json errors inside of RxError parameters to make debugging easier. +- CHANGE crunch multiple incremental (aka 'atomic') operations into a single database write. Also batch writes to multiple documents into a single write. +- CHANGE Make RxDocuments immutable +- ADD `RxDocument.getLatest()` +- REMOVE deprecated `babel-plugin-transform-async-to-promises` plugin. +- CHANGE `RxCollection.findByIds()` now returns a `RxQuery`. +- REMOVED `RxCollection.findByIds$`, use `RxCollection.findByIds().$` instead. +- FIX schema hashing should respect the sort order [#4005](https://github.com/pubkey/rxdb/pull/4005) +- CHANGE Prefix storage plugins with `storage-` like `rxdb/plugins/storage-dexie`. +- RENAME `atomicUpdate()` to `incrementalModify()` +- RENAME `atomicPatch()` to `incrementalPatch()` +- RENAME `atomicUpsert()` to `incrementalUpsert()` +- ADD `RxDocument().incrementalUpdate()` +- ADD `RxDocument.incrementalRemove()` +- ADD non-incremental `RxDocument` methods `patch()` and `modify()` +- ADD typings to the query selector +- CHANGE start replication via pure functions instead of RxCollection methods. diff --git a/README.md b/README.md index 276b3525639..d59d65d70b0 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ import { * In other JavaScript runtimes, we can use different storages: * @link https://rxdb.info/rx-storage.html */ -import { getRxStorageDexie } from 'rxdb/plugins/dexie'; +import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie'; // create a database const db = await createRxDatabase({ @@ -259,7 +259,7 @@ As you may detect, the query can take very long time to run, because you have th When a user now logs off, the whole query will re-run over the database which takes again very long. ```js -await anyUser.atomicPatch({loggedIn: false}); +await anyUser.incrementalPatch({loggedIn: false}); ``` But not with the EventReduce. diff --git a/babel.config.js b/babel.config.js index 5d46ce3bc4c..4061521970e 100644 --- a/babel.config.js +++ b/babel.config.js @@ -30,23 +30,8 @@ const plugins = [ '@babel/transform-block-scoping', '@babel/plugin-transform-member-expression-literals', '@babel/transform-property-literals', - - /** - * Transpile async/await to promises instead of generators. - * This has shown to be 10% smaller build size and also be a bit faster. - * - */ - ['babel-plugin-transform-async-to-promises', { - /** - * TODO use externalHelpers instead of inlineHelpers, - * but we have to wait for this bug to be fixed: - * @link https://github.com/rpetrich/babel-plugin-transform-async-to-promises/issues/62 - * @link https://github.com/rpetrich/babel-plugin-transform-async-to-promises/issues/78 - */ - externalHelpers: false, - inlineHelpers: true - }], - + '@babel/transform-async-to-generator', + '@babel/transform-regenerator', ['@babel/transform-runtime', { 'regenerator': true }], diff --git a/config/bundle-size.js b/config/bundle-size.js index 66875ba2ca5..bbbc8a6b057 100644 --- a/config/bundle-size.js +++ b/config/bundle-size.js @@ -2,17 +2,13 @@ import { createRxDatabase } from '../'; import { - getRxStoragePouch, - addPouchPlugin -} from '../plugins/pouchdb'; + getRxStorageMemory, +} from '../plugins/storage-memory'; function run() { - addPouchPlugin(require('pouchdb-adapter-idb')); createRxDatabase({ - // the name of the database name: 'heroesdb', - // use pouchdb with the indexeddb-adapter as storage engine. - storage: getRxStoragePouch('idb') + storage: getRxStorageMemory() }).then(db => { return db.destroy(); }); diff --git a/dist/es/browserify.index.js b/dist/es/browserify.index.js index 72f6179e25e..2ebb4ecd1dd 100644 --- a/dist/es/browserify.index.js +++ b/dist/es/browserify.index.js @@ -6,8 +6,5 @@ import '@babel/polyfill'; import * as RxDB from './index.js'; -import * as RxDbPouchPlugin from './plugins/pouchdb/index.js'; -RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb')); -RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http')); window['RxDB'] = RxDB; //# sourceMappingURL=browserify.index.js.map \ No newline at end of file diff --git a/dist/es/browserify.index.js.map b/dist/es/browserify.index.js.map index b7393449d3a..0414da18114 100644 --- a/dist/es/browserify.index.js.map +++ b/dist/es/browserify.index.js.map @@ -1 +1 @@ -{"version":3,"file":"browserify.index.js","names":["RxDB","RxDbPouchPlugin","addPouchPlugin","require","window"],"sources":["../../src/browserify.index.ts"],"sourcesContent":["/**\n * this is the index for a browserify-build\n * which produces a single file that can be embedded into the html\n * and used via window.RxDB\n */\n\nimport '@babel/polyfill';\nimport * as RxDB from './index.js';\nimport * as RxDbPouchPlugin from './plugins/pouchdb/index.js';\n\nRxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb'));\nRxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http'));\n\n(window as any)['RxDB'] = RxDB;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,OAAO,iBAAiB;AACxB,OAAO,KAAKA,IAAI,MAAM,YAAY;AAClC,OAAO,KAAKC,eAAe,MAAM,4BAA4B;AAE7DA,eAAe,CAACC,cAAc,CAACC,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAC9DF,eAAe,CAACC,cAAc,CAACC,OAAO,CAAC,sBAAsB,CAAC,CAAC;AAE9DC,MAAM,CAAS,MAAM,CAAC,GAAGJ,IAAI"} \ No newline at end of file +{"version":3,"file":"browserify.index.js","names":["RxDB","window"],"sources":["../../src/browserify.index.ts"],"sourcesContent":["/**\n * this is the index for a browserify-build\n * which produces a single file that can be embedded into the html\n * and used via window.RxDB\n */\n\nimport '@babel/polyfill';\nimport * as RxDB from './index.js';\n\n(window as any)['RxDB'] = RxDB;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,OAAO,iBAAiB;AACxB,OAAO,KAAKA,IAAI,MAAM,YAAY;AAEjCC,MAAM,CAAS,MAAM,CAAC,GAAGD,IAAI"} \ No newline at end of file diff --git a/dist/es/custom-index.js b/dist/es/custom-index.js index 0ca3ea14d72..f460271f141 100644 --- a/dist/es/custom-index.js +++ b/dist/es/custom-index.js @@ -5,7 +5,7 @@ */ import { getSchemaByObjectPath } from './rx-schema-helper'; -import { ensureNotFalsy, objectPathMonad } from './util'; +import { ensureNotFalsy, objectPathMonad } from './plugins/utils'; import { INDEX_MAX, INDEX_MIN } from './query-planner'; /** diff --git a/dist/es/custom-index.js.map b/dist/es/custom-index.js.map index 87e80912e6f..e4e5612cb35 100644 --- a/dist/es/custom-index.js.map +++ b/dist/es/custom-index.js.map @@ -1 +1 @@ -{"version":3,"file":"custom-index.js","names":["getSchemaByObjectPath","ensureNotFalsy","objectPathMonad","INDEX_MAX","INDEX_MIN","getIndexableStringMonad","schema","index","fieldNameProperties","map","fieldName","schemaPart","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","ret","docData","str","forEach","props","fieldValue","padEnd","maxLength","boolToStr","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","length","multipleOfParts","split","decimals","roundedMinimum","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './util';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n\n\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n let fieldValue = props.getValueFn(docData);\n\n if (type === 'string') {\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n const parsedLengths = ensureNotFalsy(props.parsedLengths);\n if (!fieldValue) {\n fieldValue = 0;\n }\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n });\n return str;\n };\n return ret;\n}\n\ndeclare type ParsedLengths = {\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,qBAAqB,QAAQ,oBAAoB;AAM1D,SACIC,cAAc,EACdC,eAAe,QAEZ,QAAQ;AACf,SAASC,SAAS,EAAEC,SAAS,QAAQ,iBAAiB;;AAGtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuB,CACnCC,MAA+C,EAC/CC,KAAe,EAC+B;EAE9C;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAAC,UAAAC,SAAS,EAAI;IACzB,IAAMC,UAAU,GAAGX,qBAAqB,CACpCM,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIC,KAAK,CAAC,iBAAiB,GAAGF,SAAS,CAAC;IAClD;IACA,IAAMG,IAAI,GAAGF,UAAU,CAACE,IAAI;IAC5B,IAAIC,aAAwC;IAC5C,IAAID,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,SAAS,EAAE;MACzCC,aAAa,GAAGC,4BAA4B,CACxCJ,UAAU,CACb;IACL;IAEA,OAAO;MACHD,SAAS,EAATA,SAAS;MACTC,UAAU,EAAVA,UAAU;MACVG,aAAa,EAAbA,aAAa;MACbE,cAAc,EAAEN,SAAS,CAACO,QAAQ,CAAC,GAAG,CAAC;MACvCC,UAAU,EAAEhB,eAAe,CAACQ,SAAS;IACzC,CAAC;EACL,CAAC,CAAC;EAGF,IAAMS,GAAG,GAAG,SAANA,GAAG,CAAaC,OAAkC,EA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,MAAM,IAAIvC,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOQ,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"custom-index.js","names":["getSchemaByObjectPath","ensureNotFalsy","objectPathMonad","INDEX_MAX","INDEX_MIN","getIndexableStringMonad","schema","index","fieldNameProperties","map","fieldName","schemaPart","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","ret","docData","str","forEach","props","fieldValue","padEnd","maxLength","boolToStr","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","length","multipleOfParts","split","decimals","roundedMinimum","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n\n\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n let fieldValue = props.getValueFn(docData);\n\n if (type === 'string') {\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n const parsedLengths = ensureNotFalsy(props.parsedLengths);\n if (!fieldValue) {\n fieldValue = 0;\n }\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n });\n return str;\n };\n return ret;\n}\n\ndeclare type ParsedLengths = {\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,qBAAqB,QAAQ,oBAAoB;AAM1D,SACIC,cAAc,EACdC,eAAe,QAEZ,iBAAiB;AACxB,SAASC,SAAS,EAAEC,SAAS,QAAQ,iBAAiB;;AAGtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuB,CACnCC,MAA+C,EAC/CC,KAAe,EAC+B;EAE9C;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAAC,UAAAC,SAAS,EAAI;IACzB,IAAMC,UAAU,GAAGX,qBAAqB,CACpCM,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIC,KAAK,CAAC,iBAAiB,GAAGF,SAAS,CAAC;IAClD;IACA,IAAMG,IAAI,GAAGF,UAAU,CAACE,IAAI;IAC5B,IAAIC,aAAwC;IAC5C,IAAID,IAAI,KAAK,QAAQ,IAAIA,IAAI,KAAK,SAAS,EAAE;MACzCC,aAAa,GAAGC,4BAA4B,CACxCJ,UAAU,CACb;IACL;IAEA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UACvC,IAAMiD,QAAQ,GAAGI,YAAY,GAAG,GAAG,GAAG,GAAG;UACzCnC,GAAG,IAAI+B,QAAQ,CAACC,MAAM,CAACvC,aAAa,CAACsB,WAAW,GAAGtB,aAAa,CAAC2B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHpB,GAAG,IAAIO,oBAAoB,CACvBd,aAAa,EACbqC,KAAK,CACR;QACL;QACA;MACJ;QACI,MAAM,IAAIvC,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOQ,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/doc-cache.js b/dist/es/doc-cache.js index c1ecdaff732..42942538e25 100644 --- a/dist/es/doc-cache.js +++ b/dist/es/doc-cache.js @@ -1,18 +1,122 @@ -export var DocCache = /*#__PURE__*/function () { - function DocCache() { - this._map = new Map(); - this._map = new Map(); +import { getFromMapOrFill, getFromMapOrThrow, parseRevision } from './plugins/utils'; +import { overwritable } from './overwritable'; +import { getDocumentDataOfRxChangeEvent } from './rx-change-event'; +/** + * The DocumentCache stores RxDocument objects + * by their primary key and revision. + * This is useful on client side applications where + * it is not known how much memory can be used, so + * we de-duplicate RxDocument states to save memory. + * To not fill up the memory with old document states, the DocumentCache + * only contains weak references to the RxDocuments themself. + * @link https://caniuse.com/?search=weakref + */ +export var DocumentCache = /*#__PURE__*/function () { + /** + * Some JavaScript runtimes like QuickJS, + * so not have a FinalizationRegistry or WeakRef. + * Therefore we need a workaround which might waste a lot of memory, + * but at least works. + */ + + function DocumentCache(primaryPath, changes$, + /** + * A method that can create a RxDocument by the given document data. + */ + documentCreator) { + var _this = this; + this.cacheItemByDocId = new Map(); + this.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (docMeta) { + var docId = docMeta.docId; + var cacheItem = _this.cacheItemByDocId.get(docId); + if (cacheItem) { + cacheItem.documentByRevisionHeight["delete"](docMeta.revisionHeight); + if (cacheItem.documentByRevisionHeight.size === 0) { + /** + * No state of the document is cached anymore, + * so we can clean up. + */ + _this.cacheItemByDocId["delete"](docId); + } + } + }) : undefined; + this.primaryPath = primaryPath; + this.changes$ = changes$; + this.documentCreator = documentCreator; + changes$.subscribe(function (changeEvent) { + var docId = changeEvent.documentId; + var cacheItem = _this.cacheItemByDocId.get(docId); + if (cacheItem) { + var documentData = getDocumentDataOfRxChangeEvent(changeEvent); + cacheItem.latestDoc = documentData; + } + }); } - var _proto = DocCache.prototype; - _proto.get = function get(id) { - return this._map.get(id); - }; - _proto.set = function set(id, obj) { - return this._map.set(id, obj); + + /** + * Get the RxDocument from the cache + * and create a new one if not exits before. + */ + var _proto = DocumentCache.prototype; + _proto.getCachedRxDocument = function getCachedRxDocument(docData) { + var docId = docData[this.primaryPath]; + var revisionHeight = parseRevision(docData._rev).height; + var cacheItem = getFromMapOrFill(this.cacheItemByDocId, docId, function () { + return getNewCacheItem(docData); + }); + var cachedRxDocumentWeakRef = cacheItem.documentByRevisionHeight.get(revisionHeight); + var cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined; + if (!cachedRxDocument) { + docData = overwritable.deepFreezeWhenDevMode(docData); + cachedRxDocument = this.documentCreator(docData); + cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument)); + if (this.registry) { + this.registry.register(cachedRxDocument, { + docId: docId, + revisionHeight: revisionHeight + }); + } + } + return cachedRxDocument; + } + + /** + * Throws if not exists + */; + _proto.getLatestDocumentData = function getLatestDocumentData(docId) { + var cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId); + return cacheItem.latestDoc; }; - _proto["delete"] = function _delete(id) { - return this._map["delete"](id); + _proto.getLatestDocumentDataIfExists = function getLatestDocumentDataIfExists(docId) { + var cacheItem = this.cacheItemByDocId.get(docId); + if (cacheItem) { + return cacheItem.latestDoc; + } }; - return DocCache; + return DocumentCache; }(); +function getNewCacheItem(docData) { + return { + documentByRevisionHeight: new Map(), + latestDoc: docData + }; +} + +/** + * Fallback for JavaScript runtimes that do not support WeakRef. + * The fallback will keep the items in cache forever, + * but at least works. + */ +var HAS_WEAK_REF = typeof WeakRef === 'function'; +function createWeakRefWithFallback(obj) { + if (HAS_WEAK_REF) { + return new WeakRef(obj); + } else { + return { + deref: function deref() { + return obj; + } + }; + } +} //# sourceMappingURL=doc-cache.js.map \ No newline at end of file diff --git a/dist/es/doc-cache.js.map b/dist/es/doc-cache.js.map index ee50847b7ab..e9707b77379 100644 --- a/dist/es/doc-cache.js.map +++ b/dist/es/doc-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"doc-cache.js","names":["DocCache","_map","Map","get","id","set","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["export class DocCache {\n private _map: Map = new Map();\n constructor() {\n this._map = new Map();\n }\n\n get(id: string): T | undefined {\n return this._map.get(id);\n }\n set(id: string, obj: T) {\n return this._map.set(id, obj);\n }\n delete(id: string) {\n return this._map.delete(id);\n }\n}\n"],"mappings":"AAAA,WAAaA,QAAQ;EAEjB,oBAAc;IAAA,KADNC,IAAI,GAAmB,IAAIC,GAAG,EAAE;IAEpC,IAAI,CAACD,IAAI,GAAG,IAAIC,GAAG,EAAE;EACzB;EAAC;EAAA,OAEDC,GAAG,GAAH,aAAIC,EAAU,EAAiB;IAC3B,OAAO,IAAI,CAACH,IAAI,CAACE,GAAG,CAACC,EAAE,CAAC;EAC5B,CAAC;EAAA,OACDC,GAAG,GAAH,aAAID,EAAU,EAAEE,GAAM,EAAE;IACpB,OAAO,IAAI,CAACL,IAAI,CAACI,GAAG,CAACD,EAAE,EAAEE,GAAG,CAAC;EACjC,CAAC;EAAA,mBACD,iBAAOF,EAAU,EAAE;IACf,OAAO,IAAI,CAACH,IAAI,UAAO,CAACG,EAAE,CAAC;EAC/B,CAAC;EAAA;AAAA"} \ No newline at end of file +{"version":3,"file":"doc-cache.js","names":["getFromMapOrFill","getFromMapOrThrow","parseRevision","overwritable","getDocumentDataOfRxChangeEvent","DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","documentByRevisionHeight","revisionHeight","size","undefined","subscribe","changeEvent","documentId","documentData","latestDoc","getCachedRxDocument","docData","_rev","height","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","deepFreezeWhenDevMode","set","createWeakRefWithFallback","register","getLatestDocumentData","getLatestDocumentDataIfExists","HAS_WEAK_REF","WeakRef","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n getFromMapOrFill,\n getFromMapOrThrow,\n parseRevision\n} from './plugins/utils';\nimport {\n overwritable\n} from './overwritable';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\nimport { Observable } from 'rxjs';\n\ndeclare type CacheItem = {\n /**\n * Store the different document states of time\n * based on their revision height.\n * We store WeakRefs so that we can later clean up\n * document states that are no longer needed.\n */\n documentByRevisionHeight: Map>>;\n\n /**\n * Store the latest known document state.\n * As long as any state of the document is in the cache,\n * we observe the changestream and update the latestDoc accordingly.\n * This makes it easier to optimize performance on other parts\n * because for each known document we can always get the current state\n * in the storage.\n * Also it makes it possible to call RxDocument.latest() in a non-async way\n * to retrieve the latest document state or to observe$ some property.\n *\n * To not prevent the whole cacheItem from being garbage collected,\n * we store only the document data here, but not the RxDocument.\n */\n latestDoc: RxDocumentData;\n};\n\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\ndeclare type FinalizationRegistryValue = {\n docId: string;\n revisionHeight: number;\n};\n\n/**\n * The DocumentCache stores RxDocument objects\n * by their primary key and revision.\n * This is useful on client side applications where\n * it is not known how much memory can be used, so\n * we de-duplicate RxDocument states to save memory.\n * To not fill up the memory with old document states, the DocumentCache\n * only contains weak references to the RxDocuments themself.\n * @link https://caniuse.com/?search=weakref\n */\nexport class DocumentCache {\n public cacheItemByDocId = new Map>();\n\n /**\n * Some JavaScript runtimes like QuickJS,\n * so not have a FinalizationRegistry or WeakRef.\n * Therefore we need a workaround which might waste a lot of memory,\n * but at least works.\n */\n private registry?: FinalizationRegistry = typeof FinalizationRegistry === 'function' ?\n new FinalizationRegistry(docMeta => {\n const docId = docMeta.docId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n cacheItem.documentByRevisionHeight.delete(docMeta.revisionHeight);\n if (cacheItem.documentByRevisionHeight.size === 0) {\n /**\n * No state of the document is cached anymore,\n * so we can clean up.\n */\n this.cacheItemByDocId.delete(docId);\n }\n }\n }) :\n undefined;\n\n constructor(\n public readonly primaryPath: string,\n public readonly changes$: Observable>,\n /**\n * A method that can create a RxDocument by the given document data.\n */\n public documentCreator: (docData: RxDocumentData) => RxDocument\n ) {\n changes$.subscribe(changeEvent => {\n const docId = changeEvent.documentId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n const documentData = getDocumentDataOfRxChangeEvent(changeEvent);\n cacheItem.latestDoc = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n */\n public getCachedRxDocument(docData: RxDocumentData): RxDocument {\n const docId: string = (docData as any)[this.primaryPath];\n const revisionHeight = parseRevision(docData._rev).height;\n const cacheItem = getFromMapOrFill>(\n this.cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const cachedRxDocumentWeakRef: WeakRef> | undefined = cacheItem.documentByRevisionHeight.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = overwritable.deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = this.documentCreator(docData) as RxDocument;\n cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n\n if (this.registry) {\n this.registry.register(cachedRxDocument, {\n docId,\n revisionHeight\n });\n }\n }\n return cachedRxDocument;\n }\n\n /**\n * Throws if not exists\n */\n public getLatestDocumentData(docId: string): RxDocumentData {\n const cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId);\n return cacheItem.latestDoc;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.latestDoc;\n }\n }\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n documentByRevisionHeight: new Map(),\n latestDoc: docData\n };\n}\n\n\n/**\n * Fallback for JavaScript runtimes that do not support WeakRef.\n * The fallback will keep the items in cache forever,\n * but at least works.\n */\nconst HAS_WEAK_REF = typeof WeakRef === 'function';\nfunction createWeakRefWithFallback(obj: T): WeakRef {\n if (HAS_WEAK_REF) {\n return new WeakRef(obj) as any;\n } else {\n return {\n deref() {\n return obj;\n }\n } as any;\n }\n}\n"],"mappings":"AAKA,SACIA,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACV,iBAAiB;AACxB,SACIC,YAAY,QACT,gBAAgB;AACvB,SAASC,8BAA8B,QAAQ,mBAAmB;AAqClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI,uBACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA;IAAA,KAhCKC,gBAAgB,GAAG,IAAIC,GAAG,EAA4C;IAAA,KAQrEC,QAAQ,GAAqD,OAAOC,oBAAoB,KAAK,UAAU,GAC3G,IAAIA,oBAAoB,CAA4B,UAAAC,OAAO,EAAI;MAC3D,IAAMC,KAAK,GAAGD,OAAO,CAACC,KAAK;MAC3B,IAAMC,SAAS,GAAG,KAAI,CAACN,gBAAgB,CAACO,GAAG,CAACF,KAAK,CAAC;MAClD,IAAIC,SAAS,EAAE;QACXA,SAAS,CAACE,wBAAwB,UAAO,CAACJ,OAAO,CAACK,cAA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/dist/es/event-reduce.js index 3ed846086b9..89d33b5c544 100644 --- a/dist/es/event-reduce.js +++ b/dist/es/event-reduce.js @@ -1,6 +1,6 @@ import { calculateActionName, runAction } from 'event-reduce-js'; import { rxChangeEventToEventReduceChangeEvent } from './rx-change-event'; -import { arrayFilterNotEmpty, clone, ensureNotFalsy } from './util'; +import { arrayFilterNotEmpty, clone, ensureNotFalsy } from './plugins/utils'; import { normalizeMangoQuery } from './rx-query-helper'; export function getSortFieldsOfQuery(primaryKey, query) { if (!query.sort || query.sort.length === 0) { diff --git a/dist/es/event-reduce.js.map b/dist/es/event-reduce.js.map index 5c345e93687..1faa37d6873 100644 --- a/dist/es/event-reduce.js.map +++ b/dist/es/event-reduce.js.map @@ -1 +1 @@ -{"version":3,"file":"event-reduce.js","names":["calculateActionName","runAction","rxChangeEventToEventReduceChangeEvent","arrayFilterNotEmpty","clone","ensureNotFalsy","normalizeMangoQuery","getSortFieldsOfQuery","primaryKey","query","sort","length","map","part","Object","keys","RXQUERY_QUERY_PARAMS_CACHE","WeakMap","getQueryParams","rxQuery","has","collection","preparedQuery","getPreparedQuery","normalizedMangoQuery","storageInstance","schema","mangoQuery","primaryPath","sortComparator","database","storage","statics","getSortComparator","jsonSchema","useSortComparator","docA","docB","sortComparatorData","queryMatcher","getQueryMatcher","useQueryMatcher","doc","queryMatcherData","ret","skip","limit","sortFields","set","get","calculateNewResults","rxChangeEvents","eventReduce","runFullQueryAgain","queryParams","previousResults","_result","docsData","slice","previousResultsMap","docsDataMap","changed","eventReduceEvents","cE","filter","foundNonOptimizeable","find","eventReduceEvent","stateResolveFunctionInput","changeEvent","keyDocumentMap","actionName","newResults"],"sources":["../../src/event-reduce.ts"],"sourcesContent":["import {\n ActionName,\n calculateActionName,\n runAction,\n QueryParams,\n QueryMatcher,\n DeterministicSortComparator,\n StateResolveFunctionInput,\n ChangeEvent\n} from 'event-reduce-js';\nimport type {\n RxQuery,\n MangoQuery,\n RxChangeEvent,\n PreparedQuery,\n StringKeys,\n RxDocumentData\n} from './types';\nimport { rxChangeEventToEventReduceChangeEvent } from './rx-change-event';\nimport { arrayFilterNotEmpty, clone, ensureNotFalsy } from './util';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nexport type EventReduceResultNeg = {\n runFullQueryAgain: true;\n};\nexport type EventReduceResultPos = {\n runFullQueryAgain: false;\n changed: boolean;\n newResults: RxDocumentType[];\n};\nexport type EventReduceResult = EventReduceResultNeg | EventReduceResultPos;\n\n\nexport function getSortFieldsOfQuery(\n primaryKey: StringKeys>,\n query: MangoQuery\n): (string | StringKeys)[] {\n if (!query.sort || query.sort.length === 0) {\n return [primaryKey];\n } else {\n return query.sort.map(part => Object.keys(part)[0]);\n }\n}\n\n\n\nexport const RXQUERY_QUERY_PARAMS_CACHE: WeakMap> = new WeakMap();\nexport function getQueryParams(\n rxQuery: RxQuery\n): QueryParams {\n if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) {\n const collection = rxQuery.collection;\n const preparedQuery: PreparedQuery = rxQuery.getPreparedQuery();\n const normalizedMangoQuery = normalizeMangoQuery(\n collection.storageInstance.schema,\n clone(rxQuery.mangoQuery)\n );\n const primaryKey = collection.schema.primaryPath;\n\n /**\n * Create a custom sort comparator\n * that uses the hooks to ensure\n * we send for example compressed documents to be sorted by compressed queries.\n */\n const sortComparator = collection.database.storage.statics.getSortComparator(\n collection.schema.jsonSchema,\n preparedQuery\n );\n\n const useSortComparator: DeterministicSortComparator = (docA: RxDocType, docB: RxDocType) => {\n const sortComparatorData = {\n docA,\n docB,\n rxQuery\n };\n return sortComparator(sortComparatorData.docA, sortComparatorData.docB);\n };\n\n /**\n * Create a custom query matcher\n * that uses the hooks to ensure\n * we send for example compressed documents to match compressed queries.\n */\n const queryMatcher = collection.database.storage.statics.getQueryMatcher(\n collection.schema.jsonSchema,\n preparedQuery\n );\n const useQueryMatcher: QueryMatcher> = (doc: RxDocumentData) => {\n const queryMatcherData = {\n doc,\n rxQuery\n };\n return queryMatcher(queryMatcherData.doc);\n };\n\n const ret: QueryParams = {\n primaryKey: rxQuery.collection.schema.primaryPath as any,\n skip: normalizedMangoQuery.skip,\n limit: normalizedMangoQuery.limit,\n sortFields: getSortFieldsOfQuery(primaryKey, normalizedMangoQuery) as string[],\n sortComparator: useSortComparator,\n queryMatcher: useQueryMatcher\n };\n RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret);\n return ret;\n } else {\n return RXQUERY_QUERY_PARAMS_CACHE.get(rxQuery) as QueryParams;\n }\n}\n\n\nexport function calculateNewResults(\n rxQuery: RxQuery,\n rxChangeEvents: RxChangeEvent[]\n): EventReduceResult {\n if (!rxQuery.collection.database.eventReduce) {\n return {\n runFullQueryAgain: true\n };\n }\n const queryParams = getQueryParams(rxQuery);\n const previousResults: RxDocumentType[] = ensureNotFalsy(rxQuery._result).docsData.slice(0);\n const previousResultsMap: Map = ensureNotFalsy(rxQuery._result).docsDataMap;\n let changed: boolean = false;\n\n const eventReduceEvents: ChangeEvent[] = rxChangeEvents\n .map(cE => rxChangeEventToEventReduceChangeEvent(cE))\n .filter(arrayFilterNotEmpty);\n const foundNonOptimizeable = eventReduceEvents.find(eventReduceEvent => {\n const stateResolveFunctionInput: StateResolveFunctionInput = {\n queryParams,\n changeEvent: eventReduceEvent,\n previousResults,\n keyDocumentMap: previousResultsMap\n };\n\n const actionName: ActionName = calculateActionName(stateResolveFunctionInput);\n if (actionName === 'runFullQueryAgain') {\n return true;\n } else if (actionName !== 'doNothing') {\n changed = true;\n runAction(\n actionName,\n queryParams,\n eventReduceEvent,\n previousResults,\n previousResultsMap\n );\n return false;\n }\n });\n if (foundNonOptimizeable) {\n return {\n runFullQueryAgain: true,\n };\n } else {\n return {\n runFullQueryAgain: false,\n changed,\n newResults: previousResults\n };\n }\n}\n"],"mappings":"AAAA,SAEIA,mBAAmB,EACnBC,SAAS,QAMN,iBAAiB;AASxB,SAASC,qCAAqC,QAAQ,mBAAmB;AACzE,SAASC,mBAAmB,EAAEC,KAAK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qC,OAAO,CAAC,CAACC,QAAQ,CAACC,KAAK,CAAC,CAAC,CAAC;EAC3F,IAAMC,kBAA+C,GAAGtD,cAAc,CAACc,OAAO,CAACqC,OAAO,CAAC,CAACI,WAAW;EACnG,IAAIC,OAAgB,GAAG,KAAK;EAE5B,IAAMC,iBAAgD,GAAGX,cAAc,CAClEvC,GAAG,CAAC,UAAAmD,EAAE;IAAA,OAAI7D,qCAAqC,CAAC6D,EAAE,CAAC;EAAA,EAAC,CACpDC,MAAM,CAAC7D,mBAAmB,CAAC;EAChC,IAAM8D,oBAAoB,GAAGH,iBAAiB,CAACI,IAAI,CAAC,UAAAC,gBAAgB,EAAI;IACpE,IAAMC,yBAAoE,GAAG;MACzEd,WAAW,EAAXA,WAAW;MACXe,WAAW,EAAEF,gBAAgB;MAC7BZ,eAAe,EAAfA,eAAe;MACfe,cAAc,EAAEX;IACpB,CAAC;IAED,IAAMY,UAAsB,GAAGvE,mBAAmB,CAACoE,yBAAyB,CAAC;IAC7E,IAAIG,UAAU,KAAK,mBAAmB,EAAE;MACpC,OAAO,IAAI;IACf,CAAC,MAAM,IAAIA,UAAU,KAAK,WAAW,EAAE;MACnCV,OAAO,GAAG,IAAI;MACd5D,SAAS,CACLsE,UAAU,EACVjB,WAAW,EACXa,gBAAgB,EAChBZ,eAAe,EACfI,kBAAkB,CACrB;MACD,OAAO,KAAK;IAChB;EACJ,CAAC,CAAC;EACF,IAAIM,oBAAoB,EAAE;IACtB,OAAO;MACHZ,iBAAiB,EAAE;IACvB,CAAC;EACL,CAAC,MAAM;IACH,OAAO;MACHA,iBAAiB,EAAE,KAAK;MACxBQ,OAAO,EAAPA,OAAO;MACPW,UAAU,EAAEjB;IAChB,CAAC;EACL;AACJ"} \ No newline at end of file +{"version":3,"file":"event-reduce.js","names":["calculateActionName","runAction","rxChangeEventToEventReduceChangeEvent","arrayFilterNotEmpty","clone","ensureNotFalsy","normalizeMangoQuery","getSortFieldsOfQuery","primaryKey","query","sort","length","map","part","Object","keys","RXQUERY_QUERY_PARAMS_CACHE","WeakMap","getQueryParams","rxQuery","has","collection","preparedQuery","getPreparedQuery","normalizedMangoQuery","storageInstance","schema","mangoQuery","primaryPath","sortComparator","database","storage","statics","getSortComparator","jsonSchema","useSortComparator","docA","docB","sortComparatorData","queryMatcher","getQueryMatcher","useQueryMatcher","doc","queryMatcherData","ret","skip","limit","sortFields","set","get","calculateNewResults","rxChangeEvents","eventReduce","runFullQueryAgain","queryParams","previousResults","_result","docsData","slice","previousResultsMap","docsDataMap","changed","eventReduceEvents","cE","filter","foundNonOptimizeable","find","eventReduceEvent","stateResolveFunctionInput","changeEvent","keyDocumentMap","actionName","newResults"],"sources":["../../src/event-reduce.ts"],"sourcesContent":["import {\n ActionName,\n calculateActionName,\n runAction,\n QueryParams,\n QueryMatcher,\n DeterministicSortComparator,\n StateResolveFunctionInput,\n ChangeEvent\n} from 'event-reduce-js';\nimport type {\n RxQuery,\n MangoQuery,\n RxChangeEvent,\n PreparedQuery,\n StringKeys,\n RxDocumentData\n} from './types';\nimport { rxChangeEventToEventReduceChangeEvent } from './rx-change-event';\nimport { arrayFilterNotEmpty, clone, ensureNotFalsy } from './plugins/utils';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nexport type EventReduceResultNeg = {\n runFullQueryAgain: true;\n};\nexport type EventReduceResultPos = {\n runFullQueryAgain: false;\n changed: boolean;\n newResults: RxDocumentType[];\n};\nexport type EventReduceResult = EventReduceResultNeg | EventReduceResultPos;\n\n\nexport function getSortFieldsOfQuery(\n primaryKey: StringKeys>,\n query: MangoQuery\n): (string | StringKeys)[] {\n if (!query.sort || query.sort.length === 0) {\n return [primaryKey];\n } else {\n return query.sort.map(part => Object.keys(part)[0]);\n }\n}\n\n\n\nexport const RXQUERY_QUERY_PARAMS_CACHE: WeakMap> = new WeakMap();\nexport function getQueryParams(\n rxQuery: RxQuery\n): QueryParams {\n if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) {\n const collection = rxQuery.collection;\n const preparedQuery: PreparedQuery = rxQuery.getPreparedQuery();\n const normalizedMangoQuery = normalizeMangoQuery(\n collection.storageInstance.schema,\n clone(rxQuery.mangoQuery)\n );\n const primaryKey = collection.schema.primaryPath;\n\n /**\n * Create a custom sort comparator\n * that uses the hooks to ensure\n * we send for example compressed documents to be sorted by compressed queries.\n */\n const sortComparator = collection.database.storage.statics.getSortComparator(\n collection.schema.jsonSchema,\n preparedQuery\n );\n\n const useSortComparator: DeterministicSortComparator = (docA: RxDocType, docB: RxDocType) => {\n const sortComparatorData = {\n docA,\n docB,\n rxQuery\n };\n return sortComparator(sortComparatorData.docA, sortComparatorData.docB);\n };\n\n /**\n * Create a custom query matcher\n * that uses the hooks to ensure\n * we send for example compressed documents to match compressed queries.\n */\n const queryMatcher = collection.database.storage.statics.getQueryMatcher(\n collection.schema.jsonSchema,\n preparedQuery\n );\n const useQueryMatcher: QueryMatcher> = (doc: RxDocumentData) => {\n const queryMatcherData = {\n doc,\n rxQuery\n };\n return queryMatcher(queryMatcherData.doc);\n };\n\n const ret: QueryParams = {\n primaryKey: rxQuery.collection.schema.primaryPath as any,\n skip: normalizedMangoQuery.skip,\n limit: normalizedMangoQuery.limit,\n sortFields: getSortFieldsOfQuery(primaryKey, normalizedMangoQuery) as string[],\n sortComparator: useSortComparator,\n queryMatcher: useQueryMatcher\n };\n RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret);\n return ret;\n } else {\n return RXQUERY_QUERY_PARAMS_CACHE.get(rxQuery) as QueryParams;\n }\n}\n\n\nexport function calculateNewResults(\n rxQuery: RxQuery,\n rxChangeEvents: RxChangeEvent[]\n): EventReduceResult {\n if (!rxQuery.collection.database.eventReduce) {\n return {\n runFullQueryAgain: true\n };\n }\n const queryParams = getQueryParams(rxQuery);\n const previousResults: RxDocumentType[] = ensureNotFalsy(rxQuery._result).docsData.slice(0);\n const previousResultsMap: Map = ensureNotFalsy(rxQuery._result).docsDataMap;\n let changed: boolean = false;\n\n const eventReduceEvents: ChangeEvent[] = rxChangeEvents\n .map(cE => rxChangeEventToEventReduceChangeEvent(cE))\n .filter(arrayFilterNotEmpty);\n const foundNonOptimizeable = eventReduceEvents.find(eventReduceEvent => {\n const stateResolveFunctionInput: StateResolveFunctionInput = {\n queryParams,\n changeEvent: eventReduceEvent,\n previousResults,\n keyDocumentMap: previousResultsMap\n };\n\n const actionName: ActionName = calculateActionName(stateResolveFunctionInput);\n if (actionName === 'runFullQueryAgain') {\n return true;\n } else if (actionName !== 'doNothing') {\n changed = true;\n runAction(\n actionName,\n queryParams,\n eventReduceEvent,\n previousResults,\n previousResultsMap\n );\n return false;\n }\n });\n if (foundNonOptimizeable) {\n return {\n runFullQueryAgain: true,\n };\n } else {\n return {\n runFullQueryAgain: false,\n changed,\n newResults: previousResults\n };\n }\n}\n"],"mappings":"AAAA,SAEIA,mBAAmB,EACnBC,SAAS,QAMN,iBAAiB;AASxB,SAASC,qCAAqC,QAAQ,mBAAmB;AACzE,SAASC,mBAAmB,EAAEC,KAAK,EAAEC,cAAc,QAAQ,iBAAiB;AAC5E,SAASC,mBAAmB,QAAQ,mBAAmB;AAavD,OAAO,SAASC,oBAAoB,CAChCC,UAAiD,EACjDC,KAA4B,EACM;EAClC,IAAI,CAACA,KAAK,CAACC,IAAI,IAAID,KAAK,CAACC,IAAI,CAACC,MAAM,KAAK,CAAC,EAAE;IACxC,OAAO,CAACH,UAAU,CAAC;EACvB,CAAC,MAAM;IACH,OAAOC,KAAK,CAACC,IAAI,CAACE,GAAG,CAAC,UAAAC,IAAI;MAAA,OAAIC,MAAM,CAACC,IAAI,CAACF,IAAI,CAAC,CAAC,CAAC,CAAC;IAAA,EAAC;EACvD;AACJ;AAIA,OAAO,IAAMG,0BAA8D,GAAG,IAAIC,OAAO,EAAE;AAC3F,OAAO,SAASC,cAAc,CAC1BC,OAA2B,EACL;EACtB,IAAI,CAACH,0BAA0B,CAACI,GAAG,CAACD,OAAO,CAAC,EAAE;IAC1C,IAAME,UAAU,GAAGF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yB,CAAC;IAC7E,IAAIG,UAAU,KAAK,mBAAmB,EAAE;MACpC,OAAO,IAAI;IACf,CAAC,MAAM,IAAIA,UAAU,KAAK,WAAW,EAAE;MACnCV,OAAO,GAAG,IAAI;MACd5D,SAAS,CACLsE,UAAU,EACVjB,WAAW,EACXa,gBAAgB,EAChBZ,eAAe,EACfI,kBAAkB,CACrB;MACD,OAAO,KAAK;IAChB;EACJ,CAAC,CAAC;EACF,IAAIM,oBAAoB,EAAE;IACtB,OAAO;MACHZ,iBAAiB,EAAE;IACvB,CAAC;EACL,CAAC,MAAM;IACH,OAAO;MACHA,iBAAiB,EAAE,KAAK;MACxBQ,OAAO,EAAPA,OAAO;MACPW,UAAU,EAAEjB;IAChB,CAAC;EACL;AACJ"} \ No newline at end of file diff --git a/dist/es/incremental-write.js b/dist/es/incremental-write.js new file mode 100644 index 00000000000..f9bbece634f --- /dev/null +++ b/dist/es/incremental-write.js @@ -0,0 +1,265 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +import { isBulkWriteConflictError, rxStorageWriteErrorToRxError } from './rx-error'; +import { clone, ensureNotFalsy, getFromMapOrFill, getFromMapOrThrow, parseRevision, stripMetaDataFromDocument } from './plugins/utils'; +/** + * The incremental write queue + * batches up all incremental writes to a collection + * so that performance can be improved by: + * - Running only one write even when there are multiple modifications to the same document. + * - Run all writes ins a single bulkWrite() call even when there are writes to many documents. + */ +export var IncrementalWriteQueue = /*#__PURE__*/function () { + function IncrementalWriteQueue(storageInstance, primaryPath, + // can be used to run hooks etc. + preWrite, postWrite) { + this.queueByDocId = new Map(); + this.isRunning = false; + this.storageInstance = storageInstance; + this.primaryPath = primaryPath; + this.preWrite = preWrite; + this.postWrite = postWrite; + } + var _proto = IncrementalWriteQueue.prototype; + _proto.addWrite = function addWrite(lastKnownDocumentState, modifier) { + var _this = this; + var docId = lastKnownDocumentState[this.primaryPath]; + var ar = getFromMapOrFill(this.queueByDocId, docId, function () { + return []; + }); + var ret = new Promise(function (resolve, reject) { + var item = { + lastKnownDocumentState: lastKnownDocumentState, + modifier: modifier, + resolve: resolve, + reject: reject + }; + ensureNotFalsy(ar).push(item); + _this.triggerRun(); + }); + return ret; + }; + _proto.triggerRun = /*#__PURE__*/function () { + var _triggerRun = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var _this2 = this; + var writeRows, itemsById, writeResult; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(this.isRunning === true || this.queueByDocId.size === 0)) { + _context2.next = 2; + break; + } + return _context2.abrupt("return"); + case 2: + this.isRunning = true; + writeRows = []; + /** + * 'take over' so that while the async functions runs, + * new incremental updates could be added from the outside. + */ + itemsById = this.queueByDocId; + this.queueByDocId = new Map(); + _context2.next = 8; + return Promise.all(Array.from(itemsById.entries()).map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) { + var _docId, items, oldData, newData, _iterator, _step, item; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _docId = _ref[0], items = _ref[1]; + oldData = findNewestOfDocumentStates(items.map(function (i) { + return i.lastKnownDocumentState; + })); + newData = oldData; + _iterator = _createForOfIteratorHelperLoose(items); + case 4: + if ((_step = _iterator()).done) { + _context.next = 19; + break; + } + item = _step.value; + _context.prev = 6; + _context.next = 9; + return item.modifier( + /** + * We have to clone() each time because the modifier + * might throw while it already changed some properties + * of the document. + */ + clone(newData)); + case 9: + newData = _context.sent; + _context.next = 17; + break; + case 12: + _context.prev = 12; + _context.t0 = _context["catch"](6); + item.reject(_context.t0); + item.reject = function () {}; + item.resolve = function () {}; + case 17: + _context.next = 4; + break; + case 19: + _context.prev = 19; + _context.next = 22; + return _this2.preWrite(newData, oldData); + case 22: + _context.next = 28; + break; + case 24: + _context.prev = 24; + _context.t1 = _context["catch"](19); + /** + * If the before-hooks fail, + * we reject all of the writes because it is + * not possible to determine which one is to blame. + */ + items.forEach(function (item) { + return item.reject(_context.t1); + }); + return _context.abrupt("return"); + case 28: + writeRows.push({ + previous: oldData, + document: newData + }); + case 29: + case "end": + return _context.stop(); + } + }, _callee, null, [[6, 12], [19, 24]]); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); + case 8: + if (!(writeRows.length > 0)) { + _context2.next = 14; + break; + } + _context2.next = 11; + return this.storageInstance.bulkWrite(writeRows, 'incremental-write'); + case 11: + _context2.t0 = _context2.sent; + _context2.next = 15; + break; + case 14: + _context2.t0 = { + error: {}, + success: {} + }; + case 15: + writeResult = _context2.t0; + _context2.next = 18; + return Promise.all(Array.from(Object.entries(writeResult.success)).map(function (_ref3) { + var docId = _ref3[0], + result = _ref3[1]; + _this2.postWrite(result); + var items = getFromMapOrThrow(itemsById, docId); + items.forEach(function (item) { + return item.resolve(result); + }); + })); + case 18: + // process errors + Array.from(Object.entries(writeResult.error)).forEach(function (_ref4) { + var docId = _ref4[0], + error = _ref4[1]; + var items = getFromMapOrThrow(itemsById, docId); + var isConflict = isBulkWriteConflictError(error); + if (isConflict) { + // had conflict -> retry afterwards + var ar = getFromMapOrFill(_this2.queueByDocId, docId, function () { + return []; + }); + /** + * Add the items back to this.queueByDocId + * by maintaining the original order. + */ + items.reverse().forEach(function (item) { + item.lastKnownDocumentState = ensureNotFalsy(isConflict.documentInDb); + ensureNotFalsy(ar).unshift(item); + }); + } else { + // other error -> must be thrown + var rxError = rxStorageWriteErrorToRxError(error); + items.forEach(function (item) { + return item.reject(rxError); + }); + } + }); + this.isRunning = false; + + /** + * Always trigger another run + * because in between there might be new items + * been added to the queue. + */ + return _context2.abrupt("return", this.triggerRun()); + case 21: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function triggerRun() { + return _triggerRun.apply(this, arguments); + } + return triggerRun; + }(); + return IncrementalWriteQueue; +}(); +export function modifierFromPublicToInternal(publicModifier) { + var ret = /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(docData) { + var withoutMeta, modified, reattachedMeta; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + withoutMeta = stripMetaDataFromDocument(docData); + withoutMeta._deleted = docData._deleted; + _context3.next = 4; + return publicModifier(withoutMeta); + case 4: + modified = _context3.sent; + reattachedMeta = Object.assign({}, modified, { + _meta: docData._meta, + _attachments: docData._attachments, + _rev: docData._rev, + _deleted: typeof modified._deleted !== 'undefined' ? modified._deleted : docData._deleted + }); + if (typeof reattachedMeta._deleted === 'undefined') { + reattachedMeta._deleted = false; + } + return _context3.abrupt("return", reattachedMeta); + case 8: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function ret(_x2) { + return _ref5.apply(this, arguments); + }; + }(); + return ret; +} +export function findNewestOfDocumentStates(docs) { + var newest = docs[0]; + var newestRevisionHeight = parseRevision(newest._rev).height; + docs.forEach(function (doc) { + var height = parseRevision(doc._rev).height; + if (height > newestRevisionHeight) { + newest = doc; + newestRevisionHeight = height; + } + }); + return newest; +} +//# sourceMappingURL=incremental-write.js.map \ No newline at end of file diff --git a/dist/es/incremental-write.js.map b/dist/es/incremental-write.js.map new file mode 100644 index 00000000000..2344c8b2d9c --- /dev/null +++ b/dist/es/incremental-write.js.map @@ -0,0 +1 @@ +{"version":3,"file":"incremental-write.js","names":["isBulkWriteConflictError","rxStorageWriteErrorToRxError","clone","ensureNotFalsy","getFromMapOrFill","getFromMapOrThrow","parseRevision","stripMetaDataFromDocument","IncrementalWriteQueue","storageInstance","primaryPath","preWrite","postWrite","queueByDocId","Map","isRunning","addWrite","lastKnownDocumentState","modifier","docId","ar","ret","Promise","resolve","reject","item","push","triggerRun","size","writeRows","itemsById","all","Array","from","entries","map","_docId","items","oldData","findNewestOfDocumentStates","i","newData","forEach","previous","document","length","bulkWrite","error","success","writeResult","Object","result","isConflict","reverse","documentInDb","unshift","rxError","modifierFromPublicToInternal","publicModifier","docData","withoutMeta","_deleted","modified","reattachedMeta","assign","_meta","_attachments","_rev","docs","newest","newestRevisionHeight","height","doc"],"sources":["../../src/incremental-write.ts"],"sourcesContent":["import {\n isBulkWriteConflictError,\n rxStorageWriteErrorToRxError\n} from './rx-error';\nimport type {\n ModifyFunction,\n BulkWriteRow,\n MaybePromise,\n RxDocumentData,\n RxDocumentWriteData,\n RxError,\n RxStorageBulkWriteResponse,\n RxStorageInstance,\n StringKeys,\n WithDeleted\n} from './types';\nimport {\n clone,\n ensureNotFalsy,\n getFromMapOrFill,\n getFromMapOrThrow,\n parseRevision,\n stripMetaDataFromDocument\n} from './plugins/utils';\n\n\n\nexport type IncrementalWriteModifier = (\n doc: RxDocumentData\n) => MaybePromise> | MaybePromise>;\n\n\ntype IncrementalWriteQueueItem = {\n lastKnownDocumentState: RxDocumentData;\n modifier: IncrementalWriteModifier;\n resolve: (d: RxDocumentData) => void;\n reject: (error: RxError) => void;\n};\n\n/**\n * The incremental write queue\n * batches up all incremental writes to a collection\n * so that performance can be improved by:\n * - Running only one write even when there are multiple modifications to the same document.\n * - Run all writes ins a single bulkWrite() call even when there are writes to many documents.\n */\nexport class IncrementalWriteQueue {\n public queueByDocId = new Map[]>();\n public isRunning: boolean = false;\n\n constructor(\n public readonly storageInstance: RxStorageInstance,\n public readonly primaryPath: StringKeys>,\n // can be used to run hooks etc.\n public readonly preWrite: (newData: RxDocumentData, oldData: RxDocumentData) => MaybePromise,\n public readonly postWrite: (docData: RxDocumentData) => void\n\n ) { }\n\n addWrite(\n lastKnownDocumentState: RxDocumentData,\n modifier: IncrementalWriteModifier\n ): Promise> {\n const docId: string = lastKnownDocumentState[this.primaryPath] as any;\n const ar = getFromMapOrFill(this.queueByDocId, docId, () => []);\n const ret = new Promise>((resolve, reject) => {\n const item: IncrementalWriteQueueItem = {\n lastKnownDocumentState,\n modifier,\n resolve,\n reject\n };\n ensureNotFalsy(ar).push(item);\n this.triggerRun();\n });\n return ret;\n }\n\n async triggerRun(): Promise {\n if (\n this.isRunning === true ||\n this.queueByDocId.size === 0\n ) {\n // already running\n return;\n }\n this.isRunning = true;\n const writeRows: BulkWriteRow[] = [];\n\n /**\n * 'take over' so that while the async functions runs,\n * new incremental updates could be added from the outside.\n */\n const itemsById = this.queueByDocId;\n this.queueByDocId = new Map();\n await Promise.all(\n Array.from(itemsById.entries())\n .map(async ([_docId, items]) => {\n const oldData = findNewestOfDocumentStates(\n items.map(i => i.lastKnownDocumentState)\n );\n let newData = oldData;\n for (const item of items) {\n try {\n newData = await item.modifier(\n /**\n * We have to clone() each time because the modifier\n * might throw while it already changed some properties\n * of the document.\n */\n clone(newData)\n ) as any;\n } catch (err: any) {\n item.reject(err);\n item.reject = () => { };\n item.resolve = () => { };\n }\n }\n\n try {\n await this.preWrite(newData, oldData);\n } catch (err: any) {\n /**\n * If the before-hooks fail,\n * we reject all of the writes because it is\n * not possible to determine which one is to blame.\n */\n items.forEach(item => item.reject(err));\n return;\n }\n writeRows.push({\n previous: oldData,\n document: newData\n });\n })\n );\n const writeResult: RxStorageBulkWriteResponse = writeRows.length > 0 ?\n await this.storageInstance.bulkWrite(writeRows, 'incremental-write') :\n { error: {}, success: {} };\n\n // process success\n await Promise.all(\n Array\n .from(Object.entries(writeResult.success))\n .map(([docId, result]) => {\n this.postWrite(result);\n const items = getFromMapOrThrow(itemsById, docId);\n items.forEach(item => item.resolve(result));\n })\n );\n\n // process errors\n Array\n .from(Object.entries(writeResult.error))\n .forEach(([docId, error]) => {\n const items = getFromMapOrThrow(itemsById, docId);\n const isConflict = isBulkWriteConflictError(error);\n if (isConflict) {\n // had conflict -> retry afterwards\n const ar = getFromMapOrFill(this.queueByDocId, docId, () => []);\n /**\n * Add the items back to this.queueByDocId\n * by maintaining the original order.\n */\n items\n .reverse()\n .forEach(item => {\n item.lastKnownDocumentState = ensureNotFalsy(isConflict.documentInDb);\n ensureNotFalsy(ar).unshift(item);\n });\n } else {\n // other error -> must be thrown\n const rxError = rxStorageWriteErrorToRxError(error);\n items.forEach(item => item.reject(rxError));\n }\n });\n this.isRunning = false;\n\n /**\n * Always trigger another run\n * because in between there might be new items\n * been added to the queue.\n */\n return this.triggerRun();\n }\n}\n\n\nexport function modifierFromPublicToInternal(\n publicModifier: ModifyFunction\n): IncrementalWriteModifier {\n const ret = async (docData: RxDocumentData) => {\n const withoutMeta: WithDeleted = stripMetaDataFromDocument(docData) as any;\n withoutMeta._deleted = docData._deleted;\n const modified = await publicModifier(withoutMeta);\n const reattachedMeta: RxDocumentData = Object.assign({}, modified, {\n _meta: docData._meta,\n _attachments: docData._attachments,\n _rev: docData._rev,\n _deleted: typeof (modified as WithDeleted)._deleted !== 'undefined' ?\n (modified as WithDeleted)._deleted :\n docData._deleted\n });\n if (typeof reattachedMeta._deleted === 'undefined') {\n reattachedMeta._deleted = false;\n }\n return reattachedMeta;\n };\n return ret;\n}\n\n\nexport function findNewestOfDocumentStates(\n docs: RxDocumentData[]\n): RxDocumentData {\n\n let newest = docs[0];\n let newestRevisionHeight = parseRevision(newest._rev).height;\n docs.forEach(doc => {\n const height = parseRevision(doc._rev).height;\n if (height > newestRevisionHeight) {\n newest = doc;\n newestRevisionHeight = height;\n }\n });\n return newest;\n}\n"],"mappings":";;;;;AAAA,SACIA,wBAAwB,EACxBC,4BAA4B,QACzB,YAAY;AAanB,SACIC,KAAK,EACLC,cAAc,EACdC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,EACbC,yBAAyB,QACtB,iBAAiB;AAgBxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,qBAAqB;EAI9B,+BACoBC,eAAuD,EACvDC,WAAkD;EAClE;EACgBC,QAAwG,EACxGC,SAAuD,EAEzE;IAAA,KAVKC,YAAY,GAAG,IAAIC,GAAG,EAAkD;IAAA,KACxEC,SAAS,GAAY,KAAK;IAAA,KAGbN,eAAuD,GAAvDA,eAAuD;IAAA,KACvDC,WAAkD,GAAlDA,WAAkD;IAAA,KAElDC,QAAwG,GAAxGA,QAAwG;IAAA,KACxGC,SAAuD,GAAvDA,SAAuD;EAEvE;EAAC;EAAA,OAELI,QAAQ,GAAR,kBACIC,sBAAiD,EACjDC,QAA6C,EACX;IAAA;IAClC,IAAMC,KAAa,GAAGF,sBAAsB,CAAC,IAAI,CAACP,WAAW,CAAQ;IACrE,IAAMU,EAAE,GAAGhB,gBAAgB,CAAC,IAAI,CAACS,YAAY,EAAEM,KAAK,EAAE;MAAA,OAAM,EAAE;IAAA,EAAC;IAC/D,IAAME,GAAG,GAAG,IAAIC,OAAO,CAA4B,UAACC,OAAO,EAAEC,MAAM,EAAK;MACpE,IAAMC,IAA0C,GAAG;QAC/CR,sBAAsB,EAAtBA,sBAAsB;QACtBC,QAAQ,EAARA,QAAQ;QACRK,OAAO,EAAPA,OAAO;QACPC,MAAM,EAANA;MACJ,CAAC;MACDrB,cAAc,CAACi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W,CAACC,QAAQ,GAAGF,OAAO,CAACE,QAAQ;YAAC;YAAA,OACjBH,cAAc,CAACE,WAAW,CAAC;UAAA;YAA5CE,QAAQ;YACRC,cAAyC,GAAGb,MAAM,CAACc,MAAM,CAAC,CAAC,CAAC,EAAEF,QAAQ,EAAE;cAC1EG,KAAK,EAAEN,OAAO,CAACM,KAAK;cACpBC,YAAY,EAAEP,OAAO,CAACO,YAAY;cAClCC,IAAI,EAAER,OAAO,CAACQ,IAAI;cAClBN,QAAQ,EAAE,OAAQC,QAAQ,CAA4BD,QAAQ,KAAK,WAAW,GACzEC,QAAQ,CAA4BD,QAAQ,GAC7CF,OAAO,CAACE;YAChB,CAAC,CAAC;YACF,IAAI,OAAOE,cAAc,CAACF,QAAQ,KAAK,WAAW,EAAE;cAChDE,cAAc,CAACF,QAAQ,GAAG,KAAK;YACnC;YAAC,kCACME,cAAc;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACxB;IAAA,gBAhBK1C,GAAG;MAAA;IAAA;EAAA,GAgBR;EACD,OAAOA,GAAG;AACd;AAGA,OAAO,SAASkB,0BAA0B,CACtC6B,IAAiC,EACR;EAEzB,IAAIC,MAAM,GAAGD,IAAI,CAAC,CAAC,CAAC;EACpB,IAAIE,oBAAoB,GAAGhE,aAAa,CAAC+D,MAAM,CAACF,IAAI,CAAC,CAACI,MAAM;EAC5DH,IAAI,CAAC1B,OAAO,CAAC,UAAA8B,GAAG,EAAI;IAChB,IAAMD,MAAM,GAAGjE,aAAa,CAACkE,GAAG,CAACL,IAAI,CAAC,CAACI,MAAM;IAC7C,IAAIA,MAAM,GAAGD,oBAAoB,EAAE;MAC/BD,MAAM,GAAGG,GAAG;MACZF,oBAAoB,GAAGC,MAAM;IACjC;EACJ,CAAC,CAAC;EACF,OAAOF,MAAM;AACjB"} \ No newline at end of file diff --git a/dist/es/index.js b/dist/es/index.js index b9e65ffc53e..978d44a635b 100644 --- a/dist/es/index.js +++ b/dist/es/index.js @@ -26,10 +26,10 @@ export * from './rx-storage-multiinstance'; export * from './custom-index'; export * from './query-planner'; export * from './plugin-helpers'; +export * from './plugins/utils'; export { _clearHook // used in tests } from './hooks'; export * from './query-cache'; -export * from './util'; // TODO how to do 'export type * ..' ? //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/index.js.map b/dist/es/index.js.map index f49ec9804f3..520ee8ca2b9 100644 --- a/dist/es/index.js.map +++ b/dist/es/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["addRxPlugin","createRxDatabase","removeRxDatabase","isRxDatabase","dbCount","isRxDatabaseFirstTimeInstantiated","ensureNoStartupErrors","overwritable","isRxCollection","RxCollectionBase","createRxCollection","fillObjectDataBeforeInsert","isRxDocument","flattenEvents","getDocumentOrmPrototype","getDocumentPrototype","isInstanceOf","isRxQuery","isRxSchema","createRxSchema","RxSchema","getIndexes","getPreviousVersions","toTypedRxJsonSchema","_clearHook"],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * this is the main entry-point\n * for when the you call \"import from 'rxdb'\".\n */\n\nimport './types/modules/mocha.parallel.d';\nimport './types/modules/modifiyjs.d';\n\n\nexport { addRxPlugin } from './plugin';\n\nexport {\n createRxDatabase,\n removeRxDatabase,\n isRxDatabase,\n dbCount,\n isRxDatabaseFirstTimeInstantiated,\n ensureNoStartupErrors\n} from './rx-database';\n\nexport * from './rx-error';\n\nexport * from './rx-database-internal-store';\n\nexport {\n overwritable\n} from './overwritable';\n\nexport {\n isRxCollection,\n RxCollectionBase,\n createRxCollection // used in tests\n} from './rx-collection';\n\nexport {\n fillObjectDataBeforeInsert\n} from './rx-collection-helper';\n\nexport {\n isRxDocument\n} from './rx-document';\n\nexport {\n flattenEvents\n} from './rx-change-event';\n\nexport {\n getDocumentOrmPrototype,\n getDocumentPrototype\n} from './rx-document-prototype-merge';\n\nexport {\n isInstanceOf as isRxQuery\n} from './rx-query';\nexport * from './rx-query-helper';\n\nexport {\n isInstanceOf as isRxSchema,\n createRxSchema,\n RxSchema,\n getIndexes,\n getPreviousVersions,\n toTypedRxJsonSchema\n} from './rx-schema';\nexport * from './rx-schema-helper';\n\nexport * from './rx-storage-helper';\nexport * from './replication-protocol/index';\nexport * from './rx-storage-multiinstance';\nexport * from './custom-index';\nexport * from './query-planner';\nexport * from './plugin-helpers';\n\nexport {\n _clearHook // used in tests\n} from './hooks';\n\nexport * from './query-cache';\n\nexport * from './util';\n\n// TODO how to do 'export type * ..' ?\nexport type {\n JsonSchemaTypes,\n GraphQLSyncPullOptions,\n GraphQLSyncPushOptions,\n AtomicUpdateFunction,\n CollectionsOfDatabase,\n MangoQuery,\n MangoQueryNoLimit,\n JsonSchema,\n ExtractDocumentTypeFromTypedRxJsonSchema,\n KeyFunctionMap,\n MangoQuerySelector,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n MigrationState,\n NumberFunctionMap,\n DeepReadonlyObject,\n RxAttachment,\n RxAttachmentCreator,\n RxCollection,\n RxCacheReplacementPolicy,\n RxChangeEvent,\n RxChangeEventBulk,\n RxCollectionCreator,\n RxCollectionGenerated,\n RxCollectionHookCallback,\n RxCollectionHookCallbackNonAsync,\n RxCollectionHookNoInstance,\n RxCollectionHookNoInstanceCallback,\n RxDatabase,\n RxDatabaseCreator,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n RxDumpCollectionAsAny,\n RxDumpDatabase,\n Buffer,\n Debug,\n ExtractDTcol,\n RxDatabaseGenerated,\n RxDocumentBase,\n StringKeys,\n\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n\n // stuff from the RxStorage interface\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n WithDeleted,\n BulkWriteRow,\n BulkWriteRowById,\n RxAttachmentDataBase,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxStorage,\n RxStorageStatics,\n RxStorageBulkWriteError,\n RxStorageBulkWriteResponse,\n PreparedQuery,\n RxStorageQueryResult,\n RxStorageInstanceCreationParams,\n ChangeStreamOptions,\n EventBulk,\n ChangeStreamEvent,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n DexiePreparedQuery,\n RxStorageCountResult,\n\n // conflict handling\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxReplicationWriteToMasterRow,\n\n // stuff from the RxStorage replication\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta,\n DocumentsWithCheckpoint,\n RxReplicationPullStreamItem,\n ReplicationPullHandlerResult,\n\n // crdt\n UpdateQuery,\n CRDTEntry,\n CRDTOperation,\n CRDTDocumentField,\n\n // other stuff\n RxDumpCollectionBase,\n RxDumpDatabaseAny,\n RxDumpDatabaseBase,\n RxError,\n RxErrorItem,\n RxErrorParameters,\n RxGraphQLReplicationPushQueryBuilder,\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLPullResponseModifier,\n RxJsonSchema,\n RxLocalDocument,\n RxPlugin,\n RxQuery,\n RxQueryOP,\n RxQueryObject,\n RxQueryOptions,\n RxCouchDBReplicationState,\n RxTypeError,\n CouchDBServerOptions,\n SyncOptions,\n SyncOptionsGraphQL,\n MigrationStrategy,\n MigrationStrategies,\n FilledMangoQuery,\n OldRxCollection,\n WithAttachmentsData,\n RxTestStorage,\n ById,\n RxQueryPlan,\n PlainJsonError\n} from './types';\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAO,kCAAkC;AACzC,OAAO,6BAA6B;AAGpC,SAASA,WAAW,QAAQ,UAAU;AAEtC,SACIC,gBAAgB,EAChBC,gBAAgB,EAChBC,YAAY,EACZC,OAAO,EACPC,iCAAiC,EACjCC,qBAAqB,QAClB,eAAe;AAEtB,cAAc,YAAY;AAE1B,cAAc,8BAA8B;AAE5C,SACIC,YAAY,QACT,gBAAgB;AAEvB,SACIC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,CAAC;AAAA,OAChB,iBAAiB;AAExB,SACIC,0BAA0B,QACvB,wBAAwB;AAE/B,SACIC,YAAY,QACT,eAAe;AAEtB,SACIC,aAAa,QACV,mBAAmB;AAE1B,SACIC,uBAAuB,EACvBC,oBAAoB,QACjB,+BAA+B;AAEtC,SACIC,YAAY,IAAIC,SAAS,QACtB,YAAY;AACnB,cAAc,mBAAmB;AAEjC,SACID,YAAY,IAAIE,UAAU,EAC1BC,cAAc,EACdC,QAAQ,EACRC,UAAU,EACVC,mBAAmB,EACnBC,mBAAmB,QAChB,aAAa;AACpB,cAAc,oBAAoB;AAElC,cAAc,qBAAqB;AACnC,cAAc,8BAA8B;AAC5C,cAAc,4BAA4B;AAC1C,cAAc,gBAAgB;AAC9B,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAEhC,SACIC,UAAU,CAAC;AAAA,OACR,SAAS;AAEhB,cAAc,eAAe;AAE7B,cAAc,QAAQ;;AAEtB"} \ No newline at end of file +{"version":3,"file":"index.js","names":["addRxPlugin","createRxDatabase","removeRxDatabase","isRxDatabase","dbCount","isRxDatabaseFirstTimeInstantiated","ensureNoStartupErrors","overwritable","isRxCollection","RxCollectionBase","createRxCollection","fillObjectDataBeforeInsert","isRxDocument","flattenEvents","getDocumentOrmPrototype","getDocumentPrototype","isInstanceOf","isRxQuery","isRxSchema","createRxSchema","RxSchema","getIndexes","getPreviousVersions","toTypedRxJsonSchema","_clearHook"],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * this is the main entry-point\n * for when the you call \"import from 'rxdb'\".\n */\n\nimport './types/modules/mocha.parallel.d';\nimport './types/modules/modifiyjs.d';\n\n\nexport { addRxPlugin } from './plugin';\n\nexport {\n createRxDatabase,\n removeRxDatabase,\n isRxDatabase,\n dbCount,\n isRxDatabaseFirstTimeInstantiated,\n ensureNoStartupErrors\n} from './rx-database';\n\nexport * from './rx-error';\n\nexport * from './rx-database-internal-store';\n\nexport {\n overwritable\n} from './overwritable';\n\nexport {\n isRxCollection,\n RxCollectionBase,\n createRxCollection // used in tests\n} from './rx-collection';\n\nexport {\n fillObjectDataBeforeInsert\n} from './rx-collection-helper';\n\nexport {\n isRxDocument\n} from './rx-document';\n\nexport {\n flattenEvents\n} from './rx-change-event';\n\nexport {\n getDocumentOrmPrototype,\n getDocumentPrototype\n} from './rx-document-prototype-merge';\n\nexport {\n isInstanceOf as isRxQuery\n} from './rx-query';\nexport * from './rx-query-helper';\n\nexport {\n isInstanceOf as isRxSchema,\n createRxSchema,\n RxSchema,\n getIndexes,\n getPreviousVersions,\n toTypedRxJsonSchema\n} from './rx-schema';\nexport * from './rx-schema-helper';\n\nexport * from './rx-storage-helper';\nexport * from './replication-protocol/index';\nexport * from './rx-storage-multiinstance';\nexport * from './custom-index';\nexport * from './query-planner';\nexport * from './plugin-helpers';\nexport * from './plugins/utils';\n\nexport {\n _clearHook // used in tests\n} from './hooks';\n\nexport * from './query-cache';\n\n// TODO how to do 'export type * ..' ?\nexport type {\n JsonSchemaTypes,\n GraphQLSyncPullOptions,\n GraphQLSyncPushOptions,\n ModifyFunction,\n CollectionsOfDatabase,\n MangoQuery,\n MangoQueryNoLimit,\n JsonSchema,\n ExtractDocumentTypeFromTypedRxJsonSchema,\n KeyFunctionMap,\n MangoQuerySelector,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n MigrationState,\n NumberFunctionMap,\n DeepReadonlyObject,\n RxAttachment,\n RxAttachmentCreator,\n RxCollection,\n RxCacheReplacementPolicy,\n RxChangeEvent,\n RxChangeEventBulk,\n RxCollectionCreator,\n RxCollectionGenerated,\n RxCollectionHookCallback,\n RxCollectionHookCallbackNonAsync,\n RxCollectionHookNoInstance,\n RxCollectionHookNoInstanceCallback,\n RxDatabase,\n RxDatabaseCreator,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n RxDumpCollectionAsAny,\n RxDumpDatabase,\n Buffer,\n Debug,\n ExtractDTcol,\n RxDatabaseGenerated,\n RxDocumentBase,\n StringKeys,\n\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n\n // stuff from the RxStorage interface\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n WithDeleted,\n BulkWriteRow,\n BulkWriteRowById,\n RxAttachmentDataBase,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxStorage,\n RxStorageStatics,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n PreparedQuery,\n RxStorageQueryResult,\n RxStorageInstanceCreationParams,\n ChangeStreamOptions,\n EventBulk,\n ChangeStreamEvent,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n DexiePreparedQuery,\n RxStorageCountResult,\n\n // conflict handling\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxReplicationWriteToMasterRow,\n\n // stuff from the RxStorage replication\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta,\n DocumentsWithCheckpoint,\n RxReplicationPullStreamItem,\n ReplicationPullHandlerResult,\n\n // crdt\n UpdateQuery,\n CRDTEntry,\n CRDTOperation,\n CRDTDocumentField,\n\n // other stuff\n RxDumpCollectionBase,\n RxDumpDatabaseAny,\n RxDumpDatabaseBase,\n RxError,\n RxTypeError,\n RxValidationError,\n RxErrorParameters,\n RxGraphQLReplicationPushQueryBuilder,\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLPullResponseModifier,\n RxJsonSchema,\n RxLocalDocument,\n RxPlugin,\n RxQuery,\n RxQueryOP,\n MangoQueryOperators,\n SyncOptionsGraphQL,\n MigrationStrategy,\n MigrationStrategies,\n FilledMangoQuery,\n OldRxCollection,\n WithAttachmentsData,\n RxTestStorage,\n ById,\n RxQueryPlan,\n PlainJsonError\n} from './types';\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAO,kCAAkC;AACzC,OAAO,6BAA6B;AAGpC,SAASA,WAAW,QAAQ,UAAU;AAEtC,SACIC,gBAAgB,EAChBC,gBAAgB,EAChBC,YAAY,EACZC,OAAO,EACPC,iCAAiC,EACjCC,qBAAqB,QAClB,eAAe;AAEtB,cAAc,YAAY;AAE1B,cAAc,8BAA8B;AAE5C,SACIC,YAAY,QACT,gBAAgB;AAEvB,SACIC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,CAAC;AAAA,OAChB,iBAAiB;AAExB,SACIC,0BAA0B,QACvB,wBAAwB;AAE/B,SACIC,YAAY,QACT,eAAe;AAEtB,SACIC,aAAa,QACV,mBAAmB;AAE1B,SACIC,uBAAuB,EACvBC,oBAAoB,QACjB,+BAA+B;AAEtC,SACIC,YAAY,IAAIC,SAAS,QACtB,YAAY;AACnB,cAAc,mBAAmB;AAEjC,SACID,YAAY,IAAIE,UAAU,EAC1BC,cAAc,EACdC,QAAQ,EACRC,UAAU,EACVC,mBAAmB,EACnBC,mBAAmB,QAChB,aAAa;AACpB,cAAc,oBAAoB;AAElC,cAAc,qBAAqB;AACnC,cAAc,8BAA8B;AAC5C,cAAc,4BAA4B;AAC1C,cAAc,gBAAgB;AAC9B,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAChC,cAAc,iBAAiB;AAE/B,SACIC,UAAU,CAAC;AAAA,OACR,SAAS;AAEhB,cAAc,eAAe;;AAE7B"} \ No newline at end of file diff --git a/dist/es/plugin-helpers.js b/dist/es/plugin-helpers.js index 3f26b4b1658..fc70377df63 100644 --- a/dist/es/plugin-helpers.js +++ b/dist/es/plugin-helpers.js @@ -1,5 +1,8 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { mergeMap } from 'rxjs/operators'; -import { fastUnsecureHash, flatClone, getFromMapOrThrow, requestIdleCallbackIfAvailable } from './util'; +import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper'; +import { fastUnsecureHash, flatClone, getFromMapOrThrow, requestIdleCallbackIfAvailable } from './plugins/utils'; /** * cache the validators by the schema-hash * so we can reuse them when multiple collections have the same schema @@ -35,35 +38,71 @@ validatorKey) { } return function (args) { return Object.assign({}, args.storage, { - createStorageInstance: function createStorageInstance(params) { - try { - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (instance) { - /** - * Lazy initialize the validator - * to save initial page load performance. - * Some libraries take really long to initialize the validator - * from the schema. - */ - var validatorCached; - requestIdleCallbackIfAvailable(function () { - return validatorCached = initValidator(params.schema); - }); - var oldBulkWrite = instance.bulkWrite.bind(instance); - instance.bulkWrite = function (documentWrites, context) { - if (!validatorCached) { - validatorCached = initValidator(params.schema); - } - documentWrites.forEach(function (row) { - validatorCached(row.document); - }); - return oldBulkWrite(documentWrites, context); - }; - return instance; - }); - } catch (e) { - return Promise.reject(e); + createStorageInstance: function () { + var _createStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(params) { + var instance, primaryPath, validatorCached, oldBulkWrite; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return args.storage.createStorageInstance(params); + case 2: + instance = _context.sent; + primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey); + /** + * Lazy initialize the validator + * to save initial page load performance. + * Some libraries take really long to initialize the validator + * from the schema. + */ + requestIdleCallbackIfAvailable(function () { + return validatorCached = initValidator(params.schema); + }); + oldBulkWrite = instance.bulkWrite.bind(instance); + instance.bulkWrite = function (documentWrites, context) { + if (!validatorCached) { + validatorCached = initValidator(params.schema); + } + var errors = []; + var continueWrites = []; + documentWrites.forEach(function (row) { + var documentId = row.document[primaryPath]; + var validationErrors = validatorCached(row.document); + if (validationErrors.length > 0) { + errors.push({ + status: 422, + isError: true, + documentId: documentId, + writeRow: row, + validationErrors: validationErrors + }); + } else { + continueWrites.push(row); + } + }); + var writePromise = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ + error: {}, + success: {} + }); + return writePromise.then(function (writeResult) { + errors.forEach(function (validationError) { + writeResult.error[validationError.documentId] = validationError; + }); + return writeResult; + }); + }; + return _context.abrupt("return", instance); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); }; } @@ -73,246 +112,409 @@ validatorKey) { * data of that storage instance. */ export function wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage) { - var errorFromStorage = function errorFromStorage(error) { - try { - var _temp4 = function _temp4() { - function _temp2() { - return Promise.resolve(fromStorage(ret.writeRow.document)).then(function (_fromStorage4) { - ret.writeRow.document = _fromStorage4; - return ret; - }); - } - var _temp = function () { - if (ret.writeRow.previous) { - return Promise.resolve(fromStorage(ret.writeRow.previous)).then(function (_fromStorage3) { - ret.writeRow.previous = _fromStorage3; - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }; - var ret = flatClone(error); - ret.writeRow = flatClone(ret.writeRow); - var _temp3 = function () { - if (ret.documentInDb) { - return Promise.resolve(fromStorage(ret.documentInDb)).then(function (_fromStorage2) { - ret.documentInDb = _fromStorage2; - }); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); - } - }; - var fromStorage = function fromStorage(docData) { - try { - if (!docData) { - return Promise.resolve(docData); - } - return Promise.resolve(modifyFromStorage(docData)); - } catch (e) { - return Promise.reject(e); - } - }; - var toStorage = function toStorage(docData) { - try { - if (!docData) { - return Promise.resolve(docData); - } - return Promise.resolve(modifyToStorage(docData)); - } catch (e) { - return Promise.reject(e); - } - }; var modifyAttachmentFromStorage = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function (v) { return v; }; - var oldBulkWrite = instance.bulkWrite.bind(instance); - instance.bulkWrite = function (documentWrites, context) { - try { - var useRows = []; - return Promise.resolve(Promise.all(documentWrites.map(function (row) { - try { - return Promise.resolve(Promise.all([row.previous ? toStorage(row.previous) : undefined, toStorage(row.document)])).then(function (_ref) { - var previous = _ref[0], - document = _ref[1]; - useRows.push({ - previous: previous, - document: document - }); - }); - } catch (e) { - return Promise.reject(e); + function toStorage(_x2) { + return _toStorage.apply(this, arguments); + } + function _toStorage() { + _toStorage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(docData) { + return _regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + if (docData) { + _context11.next = 2; + break; + } + return _context11.abrupt("return", docData); + case 2: + _context11.next = 4; + return modifyToStorage(docData); + case 4: + return _context11.abrupt("return", _context11.sent); + case 5: + case "end": + return _context11.stop(); } - }))).then(function () { - return Promise.resolve(oldBulkWrite(useRows, context)).then(function (writeResult) { - var ret = { - success: {}, - error: {} - }; - var promises = []; - Object.entries(writeResult.success).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - promises.push(fromStorage(v).then(function (v2) { - return ret.success[k] = v2; - })); - }); - Object.entries(writeResult.error).forEach(function (_ref3) { - var k = _ref3[0], - error = _ref3[1]; - promises.push(errorFromStorage(error).then(function (err) { - return ret.error[k] = err; - })); - }); - return Promise.resolve(Promise.all(promises)).then(function () { - return ret; - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - var oldQuery = instance.query.bind(instance); - instance.query = function (preparedQuery) { - return oldQuery(preparedQuery).then(function (queryResult) { - return Promise.all(queryResult.documents.map(function (doc) { - return fromStorage(doc); + }, _callee11); + })); + return _toStorage.apply(this, arguments); + } + function fromStorage(_x3) { + return _fromStorage.apply(this, arguments); + } + function _fromStorage() { + _fromStorage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(docData) { + return _regeneratorRuntime.wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + if (docData) { + _context12.next = 2; + break; + } + return _context12.abrupt("return", docData); + case 2: + _context12.next = 4; + return modifyFromStorage(docData); + case 4: + return _context12.abrupt("return", _context12.sent); + case 5: + case "end": + return _context12.stop(); + } + }, _callee12); + })); + return _fromStorage.apply(this, arguments); + } + function errorFromStorage(_x4) { + return _errorFromStorage.apply(this, arguments); + } + function _errorFromStorage() { + _errorFromStorage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(error) { + var ret; + return _regeneratorRuntime.wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + ret = flatClone(error); + ret.writeRow = flatClone(ret.writeRow); + if (!ret.documentInDb) { + _context13.next = 6; + break; + } + _context13.next = 5; + return fromStorage(ret.documentInDb); + case 5: + ret.documentInDb = _context13.sent; + case 6: + if (!ret.writeRow.previous) { + _context13.next = 10; + break; + } + _context13.next = 9; + return fromStorage(ret.writeRow.previous); + case 9: + ret.writeRow.previous = _context13.sent; + case 10: + _context13.next = 12; + return fromStorage(ret.writeRow.document); + case 12: + ret.writeRow.document = _context13.sent; + return _context13.abrupt("return", ret); + case 14: + case "end": + return _context13.stop(); + } + }, _callee13); + })); + return _errorFromStorage.apply(this, arguments); + } + var wrappedInstance = { + databaseName: instance.databaseName, + internals: instance.internals, + cleanup: instance.cleanup.bind(instance), + options: instance.options, + close: instance.close.bind(instance), + schema: instance.schema, + collectionName: instance.collectionName, + count: instance.count.bind(instance), + remove: instance.remove.bind(instance), + originalStorageInstance: instance, + bulkWrite: function () { + var _bulkWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(documentWrites, context) { + var useRows, writeResult, ret, promises; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + useRows = []; + _context3.next = 3; + return Promise.all(documentWrites.map( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(row) { + var _yield$Promise$all, previous, document; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all([row.previous ? toStorage(row.previous) : undefined, toStorage(row.document)]); + case 2: + _yield$Promise$all = _context2.sent; + previous = _yield$Promise$all[0]; + document = _yield$Promise$all[1]; + useRows.push({ + previous: previous, + document: document + }); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x7) { + return _ref.apply(this, arguments); + }; + }())); + case 3: + _context3.next = 5; + return instance.bulkWrite(useRows, context); + case 5: + writeResult = _context3.sent; + ret = { + success: {}, + error: {} + }; + promises = []; + Object.entries(writeResult.success).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; + promises.push(fromStorage(v).then(function (v2) { + return ret.success[k] = v2; + })); + }); + Object.entries(writeResult.error).forEach(function (_ref3) { + var k = _ref3[0], + error = _ref3[1]; + promises.push(errorFromStorage(error).then(function (err) { + return ret.error[k] = err; + })); + }); + _context3.next = 12; + return Promise.all(promises); + case 12: + return _context3.abrupt("return", ret); + case 13: + case "end": + return _context3.stop(); + } + }, _callee3); })); - }).then(function (documents) { - return { - documents: documents - }; - }); - }; - var oldGetAttachmentData = instance.getAttachmentData.bind(instance); - instance.getAttachmentData = function (documentId, attachmentId) { - try { - return Promise.resolve(oldGetAttachmentData(documentId, attachmentId)).then(function (data) { - return Promise.resolve(modifyAttachmentFromStorage(data)).then(function (_modifyAttachmentFrom) { - data = _modifyAttachmentFrom; - return data; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - var oldFindDocumentsById = instance.findDocumentsById.bind(instance); - instance.findDocumentsById = function (ids, deleted) { - return oldFindDocumentsById(ids, deleted).then(function (findResult) { - try { - var ret = {}; - return Promise.resolve(Promise.all(Object.entries(findResult).map(function (_ref4) { - var key = _ref4[0], - doc = _ref4[1]; - return Promise.resolve(fromStorage(doc)).then(function (_fromStorage) { - ret[key] = _fromStorage; - }); - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }); - }; - var oldGetChangedDocumentsSince = instance.getChangedDocumentsSince.bind(instance); - instance.getChangedDocumentsSince = function (limit, checkpoint) { - return oldGetChangedDocumentsSince(limit, checkpoint).then(function (result) { - try { - var _result$checkpoint = result.checkpoint; - return Promise.resolve(Promise.all(result.documents.map(function (d) { - return fromStorage(d); - }))).then(function (_Promise$all) { - return { - checkpoint: _result$checkpoint, - documents: _Promise$all - }; - }); - } catch (e) { - return Promise.reject(e); + function bulkWrite(_x5, _x6) { + return _bulkWrite.apply(this, arguments); } - }); - }; - var oldChangeStream = instance.changeStream.bind(instance); - instance.changeStream = function () { - return oldChangeStream().pipe(mergeMap(function (eventBulk) { - try { - return Promise.resolve(Promise.all(eventBulk.events.map(function (event) { - try { - return Promise.resolve(Promise.all([fromStorage(event.documentData), fromStorage(event.previousDocumentData)])).then(function (_ref5) { - var documentData = _ref5[0], - previousDocumentData = _ref5[1]; - var ev = { - operation: event.operation, - eventId: event.eventId, - documentId: event.documentId, - endTime: event.endTime, - startTime: event.startTime, - documentData: documentData, - previousDocumentData: previousDocumentData, - isLocal: false - }; - return ev; - }); - } catch (e) { - return Promise.reject(e); + return bulkWrite; + }(), + query: function query(preparedQuery) { + return instance.query(preparedQuery).then(function (queryResult) { + return Promise.all(queryResult.documents.map(function (doc) { + return fromStorage(doc); + })); + }).then(function (documents) { + return { + documents: documents + }; + }); + }, + getAttachmentData: function () { + var _getAttachmentData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(documentId, attachmentId) { + var data; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return instance.getAttachmentData(documentId, attachmentId); + case 2: + data = _context4.sent; + _context4.next = 5; + return modifyAttachmentFromStorage(data); + case 5: + data = _context4.sent; + return _context4.abrupt("return", data); + case 7: + case "end": + return _context4.stop(); } - }))).then(function (useEvents) { - var ret = { - id: eventBulk.id, - events: useEvents, - checkpoint: eventBulk.checkpoint, - context: eventBulk.context - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); + }, _callee4); + })); + function getAttachmentData(_x8, _x9) { + return _getAttachmentData.apply(this, arguments); } - })); - }; - var oldConflictResultionTasks = instance.conflictResultionTasks.bind(instance); - instance.conflictResultionTasks = function () { - return oldConflictResultionTasks().pipe(mergeMap(function (task) { - try { - return Promise.resolve(fromStorage(task.input.assumedMasterState)).then(function (assumedMasterState) { - return Promise.resolve(fromStorage(task.input.newDocumentState)).then(function (newDocumentState) { - return Promise.resolve(fromStorage(task.input.realMasterState)).then(function (realMasterState) { - return { - id: task.id, - context: task.context, - input: { - assumedMasterState: assumedMasterState, - realMasterState: realMasterState, - newDocumentState: newDocumentState - } - }; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + return getAttachmentData; + }(), + findDocumentsById: function findDocumentsById(ids, deleted) { + return instance.findDocumentsById(ids, deleted).then( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(findResult) { + var ret; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + ret = {}; + _context6.next = 3; + return Promise.all(Object.entries(findResult).map( /*#__PURE__*/function () { + var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(_ref5) { + var key, doc; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + key = _ref5[0], doc = _ref5[1]; + _context5.next = 3; + return fromStorage(doc); + case 3: + ret[key] = _context5.sent; + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x11) { + return _ref6.apply(this, arguments); + }; + }())); + case 3: + return _context6.abrupt("return", ret); + case 4: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return function (_x10) { + return _ref4.apply(this, arguments); + }; + }()); + }, + getChangedDocumentsSince: function getChangedDocumentsSince(limit, checkpoint) { + return instance.getChangedDocumentsSince(limit, checkpoint).then( /*#__PURE__*/function () { + var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(result) { + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.t0 = result.checkpoint; + _context7.next = 3; + return Promise.all(result.documents.map(function (d) { + return fromStorage(d); + })); + case 3: + _context7.t1 = _context7.sent; + return _context7.abrupt("return", { + checkpoint: _context7.t0, + documents: _context7.t1 + }); + case 5: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return function (_x12) { + return _ref7.apply(this, arguments); + }; + }()); + }, + changeStream: function changeStream() { + return instance.changeStream().pipe(mergeMap( /*#__PURE__*/function () { + var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(eventBulk) { + var useEvents, ret; + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return Promise.all(eventBulk.events.map( /*#__PURE__*/function () { + var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(event) { + var _yield$Promise$all2, documentData, previousDocumentData, ev; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return Promise.all([fromStorage(event.documentData), fromStorage(event.previousDocumentData)]); + case 2: + _yield$Promise$all2 = _context8.sent; + documentData = _yield$Promise$all2[0]; + previousDocumentData = _yield$Promise$all2[1]; + ev = { + operation: event.operation, + eventId: event.eventId, + documentId: event.documentId, + endTime: event.endTime, + startTime: event.startTime, + documentData: documentData, + previousDocumentData: previousDocumentData, + isLocal: false + }; + return _context8.abrupt("return", ev); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + return function (_x14) { + return _ref9.apply(this, arguments); + }; + }())); + case 2: + useEvents = _context9.sent; + ret = { + id: eventBulk.id, + events: useEvents, + checkpoint: eventBulk.checkpoint, + context: eventBulk.context + }; + return _context9.abrupt("return", ret); + case 5: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + return function (_x13) { + return _ref8.apply(this, arguments); + }; + }())); + }, + conflictResultionTasks: function conflictResultionTasks() { + return instance.conflictResultionTasks().pipe(mergeMap( /*#__PURE__*/function () { + var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(task) { + var assumedMasterState, newDocumentState, realMasterState; + return _regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return fromStorage(task.input.assumedMasterState); + case 2: + assumedMasterState = _context10.sent; + _context10.next = 5; + return fromStorage(task.input.newDocumentState); + case 5: + newDocumentState = _context10.sent; + _context10.next = 8; + return fromStorage(task.input.realMasterState); + case 8: + realMasterState = _context10.sent; + return _context10.abrupt("return", { + id: task.id, + context: task.context, + input: { + assumedMasterState: assumedMasterState, + realMasterState: realMasterState, + newDocumentState: newDocumentState + } + }); + case 10: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + return function (_x15) { + return _ref10.apply(this, arguments); + }; + }())); + }, + resolveConflictResultionTask: function resolveConflictResultionTask(taskSolution) { + if (taskSolution.output.isEqual) { + return instance.resolveConflictResultionTask(taskSolution); } - })); - }; - var oldResolveConflictResultionTask = instance.resolveConflictResultionTask.bind(instance); - instance.resolveConflictResultionTask = function (taskSolution) { - if (taskSolution.output.isEqual) { - return oldResolveConflictResultionTask(taskSolution); + var useSolution = { + id: taskSolution.id, + output: { + isEqual: false, + documentData: taskSolution.output.documentData + } + }; + return instance.resolveConflictResultionTask(useSolution); } - var useSolution = { - id: taskSolution.id, - output: { - isEqual: false, - documentData: taskSolution.output.documentData - } - }; - return oldResolveConflictResultionTask(useSolution); }; - return instance; + return wrappedInstance; } //# sourceMappingURL=plugin-helpers.js.map \ No newline at end of file diff --git a/dist/es/plugin-helpers.js.map b/dist/es/plugin-helpers.js.map index 9f7bb30c6a7..a20c6fa3b70 100644 --- a/dist/es/plugin-helpers.js.map +++ b/dist/es/plugin-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin-helpers.js","names":["mergeMap","fastUnsecureHash","flatClone","getFromMapOrThrow","requestIdleCallbackIfAvailable","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","has","set","VALIDATOR_CACHE","initValidator","schema","hash","JSON","stringify","validator","args","Object","assign","storage","createStorageInstance","params","instance","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","forEach","row","document","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","errorFromStorage","error","fromStorage","ret","writeRow","previous","documentInDb","docData","toStorage","modifyAttachmentFromStorage","v","useRows","Promise","all","map","undefined","push","writeResult","success","promises","entries","k","then","v2","err","oldQuery","query","preparedQuery","queryResult","documents","doc","oldGetAttachmentData","getAttachmentData","documentId","attachmentId","data","oldFindDocumentsById","findDocumentsById","ids","deleted","findResult","key","oldGetChangedDocumentsSince","getChangedDocumentsSince","limit","checkpoint","result","d","oldChangeStream","changeStream","pipe","eventBulk","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","useEvents","id","oldConflictResultionTasks","conflictResultionTasks","task","input","assumedMasterState","newDocumentState","realMasterState","oldResolveConflictResultionTask","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { mergeMap } from 'rxjs/operators';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\nimport {\n fastUnsecureHash,\n flatClone,\n getFromMapOrThrow,\n requestIdleCallbackIfAvailable\n} from './util';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\ntype ValidatorFunction = (docData: RxDocumentData) => void;\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n if (!VALIDATOR_CACHE_BY_VALIDATOR_KEY.has(validatorKey)) {\n VALIDATOR_CACHE_BY_VALIDATOR_KEY.set(validatorKey, new Map());\n }\n const VALIDATOR_CACHE = getFromMapOrThrow(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey);\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = fastUnsecureHash(JSON.stringify(schema));\n if (!VALIDATOR_CACHE.has(hash)) {\n const validator = getValidator(schema);\n VALIDATOR_CACHE.set(hash, validator);\n return validator;\n }\n return getFromMapOrThrow(VALIDATOR_CACHE, hash);\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n documentWrites.forEach(row => {\n validatorCached(row.document);\n });\n return oldBulkWrite(documentWrites, context);\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n) {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageBulkWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if (ret.documentInDb) {\n ret.documentInDb = await fromStorage(ret.documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await oldBulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n return ret;\n };\n\n const oldQuery = instance.query.bind(instance);\n instance.query = (preparedQuery) => {\n return oldQuery(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n };\n\n const oldGetAttachmentData = instance.getAttachmentData.bind(instance);\n instance.getAttachmentData = async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await oldGetAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n };\n\n const oldFindDocumentsById = instance.findDocumentsById.bind(instance);\n instance.findDocumentsById = (ids, deleted) => {\n return oldFindDocumentsById(ids, deleted).then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n };\n\n const oldGetChangedDocumentsSince = instance.getChangedDocumentsSince.bind(instance);\n instance.getChangedDocumentsSince = (limit, checkpoint) => {\n return oldGetChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n };\n\n const oldChangeStream = instance.changeStream.bind(instance);\n instance.changeStream = () => {\n return oldChangeStream().pipe(\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n })\n );\n };\n\n const oldConflictResultionTasks = instance.conflictResultionTasks.bind(instance);\n instance.conflictResultionTasks = () => {\n return oldConflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n };\n\n const oldResolveConflictResultionTask = instance.resolveConflictResultionTask.bind(instance);\n instance.resolveConflictResultionTask = (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return oldResolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return oldResolveConflictResultionTask(useSolution);\n };\n\n return instance;\n}\n"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AAgBzC,SACIC,gBAAgB,EAChBC,SAAS,EACTC,iBAAiB,EACjBC,8BAA8B,QAC3B,QAAQ;AAWf;AACA;AACA;AACA;AACA,IAAMC,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6B;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAI,CAACJ,gCAAgC,CAACK,GAAG,CAACD,YAAY,CAAC,EAAE;IACrDJ,gCAAgC,CAACM,GAAG,CAACF,YAAY,EAAE,IAAIH,GAAG,EAAE,CAAC;EACjE;EACA,IAAMM,eAAe,GAAGT,iBAAiB,CAACE,gCAAgC,EAAEI,YAAY,CAAC;EAEzF,SAASI,aAAa,CAClBC,MAAyB,EACR;IACjB,IAAMC,IAAI,GAAGd,gBAAgB,CAACe,IAAI,CAACC,SAAS,CAACH,MAAM,CAAC,CAAC;IACrD,IAAI,CAACF,eAAe,CAACF,GAAG,CAACK,IAAI,CAAC,EAAE;MAC5B,IAAMG,SAAS,GAAGV,YAAY,CAACM,MAAM,CAAC;MACtCF,eAAe,CAACD,GAAG,CAACI,IAAI,EAAEG,SAAS,CAAC;MACpC,OAAOA,SAAS;IACpB;IACA,OAAOf,iBAAiB,CAACS,eAAe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;gBACXtE,OAAO,EAAEyE,IAAI,CAACzE,OAAO;gBACrB0E,KAAK,EAAE;kBACHC,kBAAkB,EAAlBA,kBAAkB;kBAClBE,eAAe,EAAfA,eAAe;kBACfD,gBAAgB,EAAhBA;gBACJ;cACJ,CAAC;YAAC;UAAA;QAAA;MACN,CAAC;QAAA;MAAA;IAAA,EAAC,CACL;EACL,CAAC;EAED,IAAME,+BAA+B,GAAGpF,QAAQ,CAACqF,4BAA4B,CAACjF,IAAI,CAACJ,QAAQ,CAAC;EAC5FA,QAAQ,CAACqF,4BAA4B,GAAG,UAACC,YAAY,EAAK;IACtD,IAAIA,YAAY,CAACC,MAAM,CAACC,OAAO,EAAE;MAC7B,OAAOJ,+BAA+B,CAACE,YAAY,CAAC;IACxD;IACA,IAAMG,WAAW,GAAG;MAChBb,EAAE,EAAEU,YAAY,CAACV,EAAE;MACnBW,MAAM,EAAE;QACJC,OAAO,EAAE,KAAK;QACdrB,YAAY,EAAEmB,YAAY,CAACC,MAAM,CAACpB;MACtC;IACJ,CAAC;IACD,OAAOiB,+BAA+B,CAACK,WAAW,CAAC;EACvD,CAAC;EAED,OAAOzF,QAAQ;AACnB"} \ No newline at end of file +{"version":3,"file":"plugin-helpers.js","names":["mergeMap","getPrimaryFieldOfPrimaryKey","fastUnsecureHash","flatClone","getFromMapOrThrow","requestIdleCallbackIfAvailable","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","has","set","VALIDATOR_CACHE","initValidator","schema","hash","JSON","stringify","validator","args","Object","assign","storage","createStorageInstance","params","instance","primaryPath","primaryKey","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","documentInDb","previous","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","entries","k","v2","err","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","data","findDocumentsById","ids","deleted","findResult","key","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","pipe","eventBulk","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","useEvents","id","conflictResultionTasks","task","input","assumedMasterState","newDocumentState","realMasterState","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { mergeMap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport { WrappedRxStorageInstance } from './rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n fastUnsecureHash,\n flatClone,\n getFromMapOrThrow,\n requestIdleCallbackIfAvailable\n} from './plugins/utils';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n if (!VALIDATOR_CACHE_BY_VALIDATOR_KEY.has(validatorKey)) {\n VALIDATOR_CACHE_BY_VALIDATOR_KEY.set(validatorKey, new Map());\n }\n const VALIDATOR_CACHE = getFromMapOrThrow(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey);\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = fastUnsecureHash(JSON.stringify(schema));\n if (!VALIDATOR_CACHE.has(hash)) {\n const validator = getValidator(schema);\n VALIDATOR_CACHE.set(hash, validator);\n return validator;\n }\n return getFromMapOrThrow(VALIDATOR_CACHE, hash);\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ error: {}, success: {} });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error[validationError.documentId] = validationError;\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: instance.schema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: (limit, checkpoint) => {\n return instance.getChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n })\n );\n },\n conflictResultionTasks: () => {\n return instance.conflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n },\n resolveConflictResultionTask: (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return instance.resolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return instance.resolveConflictResultionTask(useSolution);\n }\n };\n\n return wrappedInstance;\n}\n"],"mappings":";;AAAA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,SAASC,2BAA2B,QAAQ,oBAAoB;AAmBhE,SACIC,gBAAgB,EAChBC,SAAS,EACTC,iBAAiB,EACjBC,8BAA8B,QAC3B,iBAAiB;AAexB;AACA;AACA;AACA;AACA,IAAMC,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6B;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAI,CAACJ,gCAAgC,CAACK,GAAG,CAACD,YAAY,CAAC,EAAE;IACrDJ,gCAAgC,CAACM,GAAG,CAACF,YAAY,EAAE,IAAIH,GAAG,EAAE,CAAC;EACjE;EACA,IAAMM,eAAe,GAAGT,iBAAiB,CAACE,gCAAgC,EAAEI,YAAY,CAAC;EAEzF,SAASI,aAAa,CAClBC,MAAyB,EACR;IACjB,IAAMC,IAAI,GAAGd,gBAAgB,CAACe,IAAI,CAACC,SAAS,CAACH,MAAM,CAAC,CAAC;IACrD,IAAI,CAACF,eAAe,CAACF,GAAG,CAACK,IAAI,CAAC,EAAE;MAC5B,IAAMG,SAAS,GAAGV,YAAY,CAACM,MAAM,CAAC;MACtCF,eAAe,CAACD,GAAG,CAACI,IAAI,EAAEG,SAAS,CAAC;MACpC,OAAOA,SAAS;IACpB;IACA,OAAOf,iBAAiB,CAACS,eAAe,EA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ACdnB,YAAY,EAAEiB,YAAY,CAACC,MAAM,CAAClB;QACtC;MACJ,CAAC;MACD,OAAOnF,QAAQ,CAACmG,4BAA4B,CAACI,WAAW,CAAC;IAC7D;EACJ,CAAC;EAED,OAAO9D,eAAe;AAC1B"} \ No newline at end of file diff --git a/dist/es/plugin.js b/dist/es/plugin.js index 62dc7577338..8bba6999f76 100644 --- a/dist/es/plugin.js +++ b/dist/es/plugin.js @@ -51,9 +51,8 @@ export function addRxPlugin(plugin) { } /** - * Since version 10.0.0 we decoupled pouchdb from - * the rxdb core. Therefore pouchdb plugins must be added - * with the addPouchPlugin() method of the pouchdb plugin. + * To identify broken configurations, + * we only allow RxDB plugins to be passed into addRxPlugin(). */ if (!plugin.rxdb) { throw newRxTypeError('PL1', { diff --git a/dist/es/plugin.js.map b/dist/es/plugin.js.map index 89b970666bb..db23d465f49 100644 --- a/dist/es/plugin.js.map +++ b/dist/es/plugin.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.js","names":["RxSchema","basePrototype","RxDocumentPrototype","RxQueryBase","RxCollectionBase","RxDatabaseBase","overwritable","HOOKS","runPluginHooks","newRxError","newRxTypeError","PROTOTYPES","prototype","RxDocument","RxQuery","RxCollection","RxDatabase","ADDED_PLUGINS","Set","ADDED_PLUGIN_NAMES","addRxPlugin","plugin","plugins","has","name","add","rxdb","init","prototypes","Object","entries","forEach","fun","assign","hooks","hooksObj","after","push","before","unshift"],"sources":["../../src/plugin.ts"],"sourcesContent":["/**\n * this handles how plugins are added to rxdb\n * basically it changes the internal prototypes\n * by passing them to the plugins-functions\n */\nimport {\n RxSchema\n} from './rx-schema';\nimport {\n basePrototype as RxDocumentPrototype\n} from './rx-document';\nimport {\n RxQueryBase\n} from './rx-query';\nimport {\n RxCollectionBase\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from './rx-database';\nimport type {\n RxPlugin\n} from './types';\n\nimport { overwritable } from './overwritable';\nimport {\n HOOKS,\n runPluginHooks\n} from './hooks';\nimport { newRxError, newRxTypeError } from './rx-error';\n\n/**\n * prototypes that can be manipulated with a plugin\n */\nconst PROTOTYPES: { [k: string]: any; } = {\n RxSchema: RxSchema.prototype,\n RxDocument: RxDocumentPrototype,\n RxQuery: RxQueryBase.prototype,\n RxCollection: RxCollectionBase.prototype,\n RxDatabase: RxDatabaseBase.prototype\n};\n\nconst ADDED_PLUGINS: Set = new Set();\nconst ADDED_PLUGIN_NAMES: Set = new Set();\n\n/**\n * Add a plugin to the RxDB library.\n * Plugins are added globally and cannot be removed.\n */\nexport function addRxPlugin(plugin: RxPlugin) {\n runPluginHooks('preAddRxPlugin', { plugin, plugins: ADDED_PLUGINS });\n\n // do nothing if added before\n if (ADDED_PLUGINS.has(plugin)) {\n return;\n } else {\n\n // ensure no other plugin with the same name was already added\n if (ADDED_PLUGIN_NAMES.has(plugin.name)) {\n throw newRxError('PL3', {\n name: plugin.name,\n plugin,\n });\n }\n\n ADDED_PLUGINS.add(plugin);\n ADDED_PLUGIN_NAMES.add(plugin.name);\n }\n\n /**\n * Since version 10.0.0 we decoupled pouchdb from\n * the rxdb core. Therefore pouchdb plugins must be added\n * with the addPouchPlugin() method of the pouchdb plugin.\n */\n if (!plugin.rxdb) {\n throw newRxTypeError('PL1', {\n plugin\n });\n }\n\n if (plugin.init) {\n plugin.init();\n }\n\n // prototype-overwrites\n if (plugin.prototypes) {\n Object\n .entries(plugin.prototypes)\n .forEach(([name, fun]) => {\n return (fun as any)(PROTOTYPES[name]);\n });\n }\n // overwritable-overwrites\n if (plugin.overwritable) {\n Object.assign(\n overwritable,\n plugin.overwritable\n );\n }\n // extend-hooks\n if (plugin.hooks) {\n Object\n .entries(plugin.hooks)\n .forEach(([name, hooksObj]) => {\n if (hooksObj.after) {\n HOOKS[name].push(hooksObj.after);\n }\n if (hooksObj.before) {\n HOOKS[name].unshift(hooksObj.before);\n }\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,SACIA,QAAQ,QACL,aAAa;AACpB,SAC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C,KAAK,EAAE;MACxBW,MAAM,EAANA;IACJ,CAAC,CAAC;EACN;EAEA,IAAIA,MAAM,CAACM,IAAI,EAAE;IACbN,MAAM,CAACM,IAAI,EAAE;EACjB;;EAEA;EACA,IAAIN,MAAM,CAACO,UAAU,EAAE;IACnBC,MAAM,CACDC,OAAO,CAACT,MAAM,CAACO,UAAU,CAAC,CAC1BG,OAAO,CAAC,gBAAiB;MAAA,IAAfP,IAAI;QAAEQ,GAAG;MAChB,OAAQA,GAAG,CAASrB,UAAU,CAACa,IAAI,CAAC,CAAC;IACzC,CAAC,CAAC;EACV;EACA;EACA,IAAIH,MAAM,CAACf,YAAY,EAAE;IACrBuB,MAAM,CAACI,MAAM,CACT3B,YAAY,EACZe,MAAM,CAACf,YAAY,CACtB;EACL;EACA;EACA,IAAIe,MAAM,CAACa,KAAK,EAAE;IACdL,MAAM,CACDC,OAAO,CAACT,MAAM,CAACa,KAAK,CAAC,CACrBH,OAAO,CAAC,iBAAsB;MAAA,IAApBP,IAAI;QAAEW,QAAQ;MACrB,IAAIA,QAAQ,CAACC,KAAK,EAAE;QAChB7B,KAAK,CAACiB,IAAI,CAAC,CAACa,IAAI,CAACF,QAAQ,CAACC,KAAK,CAAC;MACpC;MACA,IAAID,QAAQ,CAACG,MAAM,EAAE;QACjB/B,KAAK,CAACiB,IAAI,CAAC,CAACe,OAAO,CAACJ,QAAQ,CAACG,MAAM,CAAC;MACxC;IACJ,CAAC,CAAC;EACV;AACJ"} \ No newline at end of file +{"version":3,"file":"plugin.js","names":["RxSchema","basePrototype","RxDocumentPrototype","RxQueryBase","RxCollectionBase","RxDatabaseBase","overwritable","HOOKS","runPluginHooks","newRxError","newRxTypeError","PROTOTYPES","prototype","RxDocument","RxQuery","RxCollection","RxDatabase","ADDED_PLUGINS","Set","ADDED_PLUGIN_NAMES","addRxPlugin","plugin","plugins","has","name","add","rxdb","init","prototypes","Object","entries","forEach","fun","assign","hooks","hooksObj","after","push","before","unshift"],"sources":["../../src/plugin.ts"],"sourcesContent":["/**\n * this handles how plugins are added to rxdb\n * basically it changes the internal prototypes\n * by passing them to the plugins-functions\n */\nimport {\n RxSchema\n} from './rx-schema';\nimport {\n basePrototype as RxDocumentPrototype\n} from './rx-document';\nimport {\n RxQueryBase\n} from './rx-query';\nimport {\n RxCollectionBase\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from './rx-database';\nimport type {\n RxPlugin\n} from './types';\n\nimport { overwritable } from './overwritable';\nimport {\n HOOKS,\n runPluginHooks\n} from './hooks';\nimport { newRxError, newRxTypeError } from './rx-error';\n\n/**\n * prototypes that can be manipulated with a plugin\n */\nconst PROTOTYPES: { [k: string]: any; } = {\n RxSchema: RxSchema.prototype,\n RxDocument: RxDocumentPrototype,\n RxQuery: RxQueryBase.prototype,\n RxCollection: RxCollectionBase.prototype,\n RxDatabase: RxDatabaseBase.prototype\n};\n\nconst ADDED_PLUGINS: Set = new Set();\nconst ADDED_PLUGIN_NAMES: Set = new Set();\n\n/**\n * Add a plugin to the RxDB library.\n * Plugins are added globally and cannot be removed.\n */\nexport function addRxPlugin(plugin: RxPlugin) {\n runPluginHooks('preAddRxPlugin', { plugin, plugins: ADDED_PLUGINS });\n\n // do nothing if added before\n if (ADDED_PLUGINS.has(plugin)) {\n return;\n } else {\n\n // ensure no other plugin with the same name was already added\n if (ADDED_PLUGIN_NAMES.has(plugin.name)) {\n throw newRxError('PL3', {\n name: plugin.name,\n plugin,\n });\n }\n\n ADDED_PLUGINS.add(plugin);\n ADDED_PLUGIN_NAMES.add(plugin.name);\n }\n\n /**\n * To identify broken configurations,\n * we only allow RxDB plugins to be passed into addRxPlugin().\n */\n if (!plugin.rxdb) {\n throw newRxTypeError('PL1', {\n plugin\n });\n }\n\n if (plugin.init) {\n plugin.init();\n }\n\n // prototype-overwrites\n if (plugin.prototypes) {\n Object\n .entries(plugin.prototypes)\n .forEach(([name, fun]) => {\n return (fun as any)(PROTOTYPES[name]);\n });\n }\n // overwritable-overwrites\n if (plugin.overwritable) {\n Object.assign(\n overwritable,\n plugin.overwritable\n );\n }\n // extend-hooks\n if (plugin.hooks) {\n Object\n .entries(plugin.hooks)\n .forEach(([name, hooksObj]) => {\n if (hooksObj.after) {\n HOOKS[name].push(hooksObj.after);\n }\n if (hooksObj.before) {\n HOOKS[name].unshift(hooksObj.before);\n }\n });\n }\n}\n\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,SACIA,QAAQ,QACL,aAAa;AACpB,SACIC,aAAa,IAAIC,mBAAmB,QACjC,eAAe;AACtB,SACIC,WAAW,QACR,YAAY;AACnB,SACIC,gBAAgB,QACb,iBAAiB;AACxB,SACIC,cAAc,QACX,eAAe;AAKtB,SAASC,YAAY,QAAQ,gBAAgB;AAC7C,SACIC,KAAK,EACLC,cAAc,QACX,SAAS;AAChB,SAASC,UAAU,EAAEC,cAAc,QAAQ,YAAY;;AAEvD;AACA;AACA;AACA,IAAMC,UAAiC,GAAG;EACtCX,QAAQ,EAAEA,QAAQ,CAACY,SAAS;EAC5BC,UAAU,EAAEX,mBAAmB;EAC/BY,OAAO,EAAEX,WAAW,CAACS,SAAS;EAC9BG,YAAY,EAAEX,gBAAgB,CAACQ,SAAS;EACxCI,UAAU,EAAEX,cAAc,CAACO;AAC/B,CAAC;AAED,IAAMK,aAAkC,GAAG,IAAIC,GAAG,EAAE;AACpD,IAAMC,kBAA+B,GAAG,IAAID,GAAG,EAAE;;AAEjD;AACA;AACA;AACA;AACA,OAAO,SAASE,WAAW,CAACC,MAAgB,EAAE;EAC1Cb,cAAc,CAAC,gBAAgB,EAAE;IAAEa,MAAM,EAANA,MAAM;IAAEC,OAAO,EAAEL;EAAc,CAAC,CAAC;;EAEpE;EACA,IAAIA,aAAa,CAACM,GAAG,CAACF,MAAM,CAAC,EAAE;IAC3B;EACJ,CAAC,MAAM;IAEH;IACA,IAAIF,kBAAkB,CAACI,GAAG,CAACF,MAAM,CAACG,IAAI,CAAC,EAAE;MACrC,MAAMf,UAAU,CAAC,KAAK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ments/index.js b/dist/es/plugins/attachments/index.js index f43abc78a78..a0c7cd1672b 100644 --- a/dist/es/plugins/attachments/index.js +++ b/dist/es/plugins/attachments/index.js @@ -1,7 +1,8 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { map } from 'rxjs/operators'; -import { blobBufferUtil, flatClone, PROMISE_RESOLVE_VOID } from '../../util'; +import { blobBufferUtil, flatClone, PROMISE_RESOLVE_VOID } from '../../plugins/utils'; import { newRxError } from '../../rx-error'; -import { flatCloneDocWithMeta, writeSingle } from '../../rx-storage-helper'; function ensureSchemaSupportsAttachments(doc) { var schemaJson = doc.collection.schema.jsonSchema; if (!schemaJson.attachments) { @@ -10,87 +11,6 @@ function ensureSchemaSupportsAttachments(doc) { }); } } -export var preMigrateDocument = function preMigrateDocument(data) { - try { - var attachments = data.docData._attachments; - var _temp = function () { - if (attachments) { - var newAttachments = {}; - return Promise.resolve(Promise.all(Object.keys(attachments).map(function (attachmentId) { - try { - var attachment = attachments[attachmentId]; - var docPrimary = data.docData[data.oldCollection.schema.primaryPath]; - return Promise.resolve(data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId)).then(function (rawAttachmentData) { - newAttachments[attachmentId] = { - length: attachment.length, - type: attachment.type, - data: rawAttachmentData - }; - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - /** - * Hooks mutate the input - * instead of returning stuff - */ - data.docData._attachments = newAttachments; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -export var putAttachment = function putAttachment(attachmentData) { - try { - var _arguments = arguments, - _this4 = this; - var _skipIfSame = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true; - ensureSchemaSupportsAttachments(_this4); - var dataSize = blobBufferUtil.size(attachmentData.data); - return Promise.resolve(blobBufferUtil.toBase64String(attachmentData.data)).then(function (dataString) { - var id = attachmentData.id; - var type = attachmentData.type; - var data = dataString; - _this4._atomicQueue = _this4._atomicQueue.then(function () { - try { - var docWriteData = flatCloneDocWithMeta(_this4._data); - docWriteData._attachments = flatClone(docWriteData._attachments); - docWriteData._attachments[id] = { - length: dataSize, - type: type, - data: data - }; - var writeRow = { - previous: flatClone(_this4._data), - document: flatClone(docWriteData) - }; - return Promise.resolve(writeSingle(_this4.collection.storageInstance, writeRow, 'attachment-put')).then(function (writeResult) { - var attachmentDataOfId = writeResult._attachments[id]; - var attachment = fromStorageInstanceResult(id, attachmentDataOfId, _this4); - var newData = flatClone(_this4._data); - newData._rev = writeResult._rev; - newData._attachments = writeResult._attachments; - _this4._dataSync$.next(newData); - return attachment; - }); - } catch (e) { - return Promise.reject(e); - } - }); - return _this4._atomicQueue; - }); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * get an attachment of the document by its id - */ var _assignMethodsToAttachment = function _assignMethodsToAttachment(attachment) { Object.entries(attachment.doc.collection.attachments).forEach(function (_ref) { var funName = _ref[0], @@ -124,51 +44,69 @@ export var RxAttachment = /*#__PURE__*/function () { var _proto = RxAttachment.prototype; _proto.remove = function remove() { var _this = this; - this.doc._atomicQueue = this.doc._atomicQueue.then(function () { - try { - var docWriteData = flatCloneDocWithMeta(_this.doc._data); - docWriteData._attachments = flatClone(docWriteData._attachments); - delete docWriteData._attachments[_this.id]; - return Promise.resolve(writeSingle(_this.doc.collection.storageInstance, { - previous: flatClone(_this.doc._data), - // TODO do we need a flatClone here? - document: docWriteData - }, 'attachment-remove')).then(function (writeResult) { - var newData = flatClone(_this.doc._data); - newData._rev = writeResult._rev; - newData._attachments = writeResult._attachments; - _this.doc._dataSync$.next(newData); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return this.doc._atomicQueue; + return this.doc.collection.incrementalWriteQueue.addWrite(this.doc._data, function (docWriteData) { + delete docWriteData._attachments[_this.id]; + return docWriteData; + }).then(function () {}); } /** * returns the data for the attachment */; - _proto.getData = function getData() { - try { - var _this2 = this; - return Promise.resolve(_this2.doc.collection.storageInstance.getAttachmentData(_this2.doc.primary, _this2.id)).then(function (plainDataBase64) { - return Promise.resolve(blobBufferUtil.createBlobBufferFromBase64(plainDataBase64, _this2.type)); - }); - } catch (e) { - return Promise.reject(e); + _proto.getData = + /*#__PURE__*/ + function () { + var _getData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var plainDataBase64, ret; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.doc.collection.storageInstance.getAttachmentData(this.doc.primary, this.id); + case 2: + plainDataBase64 = _context.sent; + _context.next = 5; + return blobBufferUtil.createBlobBufferFromBase64(plainDataBase64, this.type); + case 5: + ret = _context.sent; + return _context.abrupt("return", ret); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getData() { + return _getData.apply(this, arguments); } - }; - _proto.getStringData = function getStringData() { - try { - var _this3 = this; - return Promise.resolve(_this3.getData()).then(function (data) { - return Promise.resolve(blobBufferUtil.toString(data)); - }); - } catch (e) { - return Promise.reject(e); + return getData; + }(); + _proto.getStringData = /*#__PURE__*/function () { + var _getStringData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var data, asString; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.getData(); + case 2: + data = _context2.sent; + _context2.next = 5; + return blobBufferUtil.toString(data); + case 5: + asString = _context2.sent; + return _context2.abrupt("return", asString); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getStringData() { + return _getStringData.apply(this, arguments); } - }; + return getStringData; + }(); return RxAttachment; }(); export function fromStorageInstanceResult(id, attachmentData, rxDocument) { @@ -180,9 +118,54 @@ export function fromStorageInstanceResult(id, attachmentData, rxDocument) { digest: attachmentData.digest }); } +export function putAttachment(_x) { + return _putAttachment.apply(this, arguments); +} + +/** + * get an attachment of the document by its id + */ +function _putAttachment() { + _putAttachment = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(attachmentData) { + var _this4 = this; + var dataSize, dataString, id, type, data; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + ensureSchemaSupportsAttachments(this); + dataSize = blobBufferUtil.size(attachmentData.data); + _context3.next = 4; + return blobBufferUtil.toBase64String(attachmentData.data); + case 4: + dataString = _context3.sent; + id = attachmentData.id; + type = attachmentData.type; + data = dataString; + return _context3.abrupt("return", this.collection.incrementalWriteQueue.addWrite(this._data, function (docWriteData) { + docWriteData._attachments = flatClone(docWriteData._attachments); + docWriteData._attachments[id] = { + length: dataSize, + type: type, + data: data + }; + return docWriteData; + }).then(function (writeResult) { + var newDocument = _this4.collection._docCache.getCachedRxDocument(writeResult); + var attachmentDataOfId = writeResult._attachments[id]; + var attachment = fromStorageInstanceResult(id, attachmentDataOfId, newDocument); + return attachment; + })); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + return _putAttachment.apply(this, arguments); +} export function getAttachment(id) { ensureSchemaSupportsAttachments(this); - var docData = this._dataSync$.getValue(); + var docData = this._data; if (!docData._attachments || !docData._attachments[id]) return null; var attachmentData = docData._attachments[id]; var attachment = fromStorageInstanceResult(id, attachmentData, this); @@ -193,18 +176,75 @@ export function getAttachment(id) { * returns all attachments of the document */ export function allAttachments() { - var _this5 = this; + var _this2 = this; ensureSchemaSupportsAttachments(this); - var docData = this._dataSync$.getValue(); + var docData = this._data; // if there are no attachments, the field is missing if (!docData._attachments) { return []; } return Object.keys(docData._attachments).map(function (id) { - return fromStorageInstanceResult(id, docData._attachments[id], _this5); + return fromStorageInstanceResult(id, docData._attachments[id], _this2); }); } +export function preMigrateDocument(_x2) { + return _preMigrateDocument.apply(this, arguments); +} +function _preMigrateDocument() { + _preMigrateDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(data) { + var attachments, newAttachments; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + attachments = data.docData._attachments; + if (!attachments) { + _context5.next = 6; + break; + } + newAttachments = {}; + _context5.next = 5; + return Promise.all(Object.keys(attachments).map( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(attachmentId) { + var attachment, docPrimary, rawAttachmentData; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + attachment = attachments[attachmentId]; + docPrimary = data.docData[data.oldCollection.schema.primaryPath]; + _context4.next = 4; + return data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId); + case 4: + rawAttachmentData = _context4.sent; + newAttachments[attachmentId] = { + length: attachment.length, + type: attachment.type, + data: rawAttachmentData + }; + case 6: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return function (_x3) { + return _ref4.apply(this, arguments); + }; + }())); + case 5: + /** + * Hooks mutate the input + * instead of returning stuff + */ + data.docData._attachments = newAttachments; + case 6: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _preMigrateDocument.apply(this, arguments); +} export function postMigrateDocument(_action) { /** * No longer needed because @@ -222,19 +262,14 @@ export var RxDBAttachmentsPlugin = { proto.allAttachments = allAttachments; Object.defineProperty(proto, 'allAttachments$', { get: function allAttachments$() { - var _this6 = this; - return this._dataSync$.pipe(map(function (data) { - if (!data['_attachments']) { - return {}; - } - return data['_attachments']; - }), map(function (attachmentsData) { - return Object.entries(attachmentsData); + var _this3 = this; + return this.$.pipe(map(function (data) { + return Object.entries(data._attachments); }), map(function (entries) { return entries.map(function (_ref3) { var id = _ref3[0], attachmentData = _ref3[1]; - return fromStorageInstanceResult(id, attachmentData, _this6); + return fromStorageInstanceResult(id, attachmentData, _this3); }); })); } diff --git a/dist/es/plugins/attachments/index.js.map b/dist/es/plugins/attachments/index.js.map index 6c879352d50..06c82731153 100644 --- a/dist/es/plugins/attachments/index.js.map +++ b/dist/es/plugins/attachments/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["map","blobBufferUtil","flatClone","PROMISE_RESOLVE_VOID","newRxError","flatCloneDocWithMeta","writeSingle","ensureSchemaSupportsAttachments","doc","schemaJson","collection","schema","jsonSchema","attachments","link","preMigrateDocument","data","docData","_attachments","newAttachments","Promise","all","Object","keys","attachmentId","attachment","docPrimary","oldCollection","primaryPath","storageInstance","getAttachmentData","rawAttachmentData","length","type","putAttachment","attachmentData","_skipIfSame","dataSize","size","toBase64String","dataString","id","_atomicQueue","then","docWriteData","_data","writeRow","previous","document","writeResult","attachmentDataOfId","fromStorageInstanceResult","newData","_rev","_dataSync$","next","_assignMethodsToAttachment","entries","forEach","funName","fun","defineProperty","get","bind","RxAttachment","digest","remove","getData","primary","plainDataBase64","createBlobBufferFromBase64","getStringData","toString","rxDocument","getAttachment","getValue","allAttachments","postMigrateDocument","_action","RxDBAttachmentsPlugin","name","rxdb","prototypes","RxDocument","proto","allAttachments$","pipe","attachmentsData","overwritable","hooks","after"],"sources":["../../../../src/plugins/attachments/index.ts"],"sourcesContent":["import {\n map\n} from 'rxjs/operators';\n\nimport {\n blobBufferUtil,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDocument,\n RxPlugin,\n BlobBuffer,\n OldRxCollection,\n RxDocumentWriteData,\n RxAttachmentData,\n RxDocumentData,\n RxAttachmentCreator,\n RxAttachmentWriteData\n} from '../../types';\nimport { flatCloneDocWithMeta, writeSingle } from '../../rx-storage-helper';\n\n\n\nfunction ensureSchemaSupportsAttachments(doc: any) {\n const schemaJson = doc.collection.schema.jsonSchema;\n if (!schemaJson.attachments) {\n throw newRxError('AT1', {\n link: 'https://pubkey.github.io/rxdb/rx-attachment.html'\n });\n }\n}\n\nconst _assignMethodsToAttachment = function (attachment: any) {\n Object\n .entries(attachment.doc.collection.attachments)\n .forEach(([funName, fun]) => {\n Object.defineProperty(attachment, funName, {\n get: () => (fun as any).bind(attachment)\n });\n });\n};\n\n/**\n * an RxAttachment is basically just the attachment-stub\n * wrapped so that you can access the attachment-data\n */\nexport class RxAttachment {\n public doc: RxDocument;\n public id: string;\n public type: string;\n public length: number;\n public digest: string;\n constructor({\n doc,\n id,\n type,\n length,\n digest\n }: any) {\n this.doc = doc;\n this.id = id;\n this.type = type;\n this.length = length;\n this.digest = digest;\n\n _assignMethodsToAttachment(this);\n }\n\n remove(): Promise {\n this.doc._atomicQueue = this.doc._atomicQueue\n .then(async () => {\n const docWriteData: RxDocumentWriteData<{}> = flatCloneDocWithMeta(this.doc._data);\n docWriteData._attachments = flatClone(docWriteData._attachments);\n delete docWriteData._attachments[this.id];\n const writeResult: RxDocumentData = await writeSingle(\n this.doc.collection.storageInstance,\n {\n previous: flatClone(this.doc._data), // TODO do we need a flatClone here?\n document: docWriteData\n },\n 'attachment-remove'\n );\n\n const newData = flatClone(this.doc._data);\n newData._rev = writeResult._rev;\n newData._attachments = writeResult._attachments;\n this.doc._dataSync$.next(newData);\n\n });\n return this.doc._atomicQueue;\n }\n\n /**\n * returns the data for the attachment\n */\n async getData(): Promise {\n const plainDataBase64 = await this.doc.collection.storageInstance.getAttachmentData(\n this.doc.primary,\n this.id\n );\n const ret = await blobBufferUtil.createBlobBufferFromBase64(\n plainDataBase64,\n this.type as any\n );\n return ret;\n }\n\n async getStringData(): Promise {\n const data = await this.getData();\n const asString = await blobBufferUtil.toString(data);\n return asString;\n }\n}\n\nexport function fromStorageInstanceResult(\n id: string,\n attachmentData: RxAttachmentData,\n rxDocument: RxDocument\n) {\n return new RxAttachment({\n doc: rxDocument,\n id,\n type: attachmentData.type,\n length: attachmentData.length,\n digest: attachmentData.digest\n });\n}\n\nexport async function putAttachment(\n this: RxDocument,\n attachmentData: RxAttachmentCreator,\n /**\n * If set to true, the write will be skipped\n * when the attachment already contains the same data.\n * @deprecated The check if the data has changed is now performed\n * inside of the RxStorage, no longer by RxDB itself. So we do\n * no longer need 'skipIfSame'.\n */\n _skipIfSame: boolean = true\n): Promise {\n ensureSchemaSupportsAttachments(this);\n\n const dataSize = blobBufferUtil.size(attachmentData.data);\n const dataString = await blobBufferUtil.toBase64String(attachmentData.data);\n\n const id = attachmentData.id;\n const type = attachmentData.type;\n const data = dataString;\n\n this._atomicQueue = this._atomicQueue\n .then(async () => {\n const docWriteData: RxDocumentWriteData<{}> = flatCloneDocWithMeta(this._data);\n docWriteData._attachments = flatClone(docWriteData._attachments);\n\n docWriteData._attachments[id] = {\n length: dataSize,\n type,\n data\n };\n const writeRow = {\n previous: flatClone(this._data),\n document: flatClone(docWriteData)\n };\n\n const writeResult = await writeSingle(\n this.collection.storageInstance,\n writeRow,\n 'attachment-put'\n );\n\n const attachmentDataOfId = writeResult._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentDataOfId,\n this\n );\n\n const newData = flatClone(this._data);\n newData._rev = writeResult._rev;\n newData._attachments = writeResult._attachments;\n this._dataSync$.next(newData);\n\n return attachment;\n });\n return this._atomicQueue;\n}\n\n/**\n * get an attachment of the document by its id\n */\nexport function getAttachment(\n this: RxDocument,\n id: string\n): RxAttachment | null {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._dataSync$.getValue();\n if (!docData._attachments || !docData._attachments[id])\n return null;\n\n const attachmentData = docData._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n return attachment;\n}\n\n/**\n * returns all attachments of the document\n */\nexport function allAttachments(\n this: RxDocument\n): RxAttachment[] {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._dataSync$.getValue();\n\n // if there are no attachments, the field is missing\n if (!docData._attachments) {\n return [];\n }\n return Object.keys(docData._attachments)\n .map(id => {\n return fromStorageInstanceResult(\n id,\n docData._attachments[id],\n this\n );\n });\n}\n\nexport async function preMigrateDocument(\n data: {\n docData: RxDocumentData;\n oldCollection: OldRxCollection;\n }\n): Promise {\n const attachments = data.docData._attachments;\n if (attachments) {\n const newAttachments: { [attachmentId: string]: RxAttachmentWriteData; } = {};\n await Promise.all(\n Object.keys(attachments).map(async (attachmentId) => {\n const attachment: RxAttachmentData = attachments[attachmentId];\n const docPrimary: string = (data.docData as any)[data.oldCollection.schema.primaryPath];\n const rawAttachmentData = await data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId);\n newAttachments[attachmentId] = {\n length: attachment.length,\n type: attachment.type,\n data: rawAttachmentData\n };\n })\n );\n\n /**\n * Hooks mutate the input\n * instead of returning stuff\n */\n (data.docData as RxDocumentWriteData)._attachments = newAttachments;\n }\n}\n\nexport function postMigrateDocument(_action: any): Promise {\n /**\n * No longer needed because\n * we store the attachments data buffers directly in the document.\n */\n return PROMISE_RESOLVE_VOID;\n}\n\nexport const RxDBAttachmentsPlugin: RxPlugin = {\n name: 'attachments',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.putAttachment = putAttachment;\n proto.getAttachment = getAttachment;\n proto.allAttachments = allAttachments;\n Object.defineProperty(proto, 'allAttachments$', {\n get: function allAttachments$() {\n return this._dataSync$\n .pipe(\n map((data: any) => {\n if (!data['_attachments']) {\n return {};\n }\n return data['_attachments'];\n }),\n map((attachmentsData: any) => Object.entries(\n attachmentsData\n )),\n map(entries => {\n return (entries as any)\n .map(([id, attachmentData]: any) => {\n return fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n });\n })\n );\n }\n });\n }\n },\n overwritable: {},\n hooks: {\n preMigrateDocument: {\n after: preMigrateDocument\n },\n postMigrateDocument: {\n after: postMigrateDocument\n }\n }\n};\n"],"mappings":"AAAA,SACIA,GAAG,QACA,gBAAgB;AAEvB,SACIC,cAAc,EACdC,SAAS,EACTC,oBAAoB,QACjB,YAAY;AACnB,SACIC,UAAU,QACP,gBAAgB;AAYvB,SAASC,oBAAoB,EAAEC,WAAW,QAAQ,yBAAyB;AAI3E,SAASC,+BAA+B,CAACC,GAAQ,EAAE;EAC/C,IAAMC,UAAU,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O,IAAM4E,qBAA+B,GAAG;EAC3CC,IAAI,EAAE,aAAa;EACnBC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAAClD,aAAa,GAAGA,aAAa;MACnCkD,KAAK,CAACV,aAAa,GAAGA,aAAa;MACnCU,KAAK,CAACR,cAAc,GAAGA,cAAc;MACrCtD,MAAM,CAACuC,cAAc,CAACuB,KAAK,EAAE,iBAAiB,EAAE;QAC5CtB,GAAG,EAAE,SAASuB,eAAe,GAAG;UAAA;UAC5B,OAAO,IAAI,CAAC/B,UAAU,CACjBgC,IAAI,CACDtF,GAAG,CAAC,UAACgB,IAAS,EAAK;YACf,IAAI,CAACA,IAAI,CAAC,cAAc,CAAC,EAAE;cACvB,OAAO,CAAC,CAAC;YACb;YACA,OAAOA,IAAI,CAAC,cAAc,CAAC;UAC/B,CAAC,CAAC,EACFhB,GAAG,CAAC,UAACuF,eAAoB;YAAA,OAAKjE,MAAM,CAACmC,OAAO,CACxC8B,eAAe,CAClB;UAAA,EAAC,EACFvF,GAAG,CAAC,UAAAyD,OAAO,EAAI;YACX,OAAQA,OAAO,CACVzD,GAAG,CAAC,iBAA+B;cAAA,IAA7ByC,EAAE;gBAAEN,cAAc;cACrB,OAAOgB,yBAAyB,CAC5BV,EAAE,EACFN,cAAc,EACd,MAAI,CACP;YACL,CAAC,CAAC;UACV,CAAC,CAAC,CACL;QACT;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;EACDqD,YAAY,EAAE,CAAC,CAAC;EAChBC,KAAK,EAAE;IACH1E,kBAAkB,EAAE;MAChB2E,KAAK,EAAE3E;IACX,CAAC;IACD8D,mBAAmB,EAAE;MACjBa,KAAK,EAAEb;IACX;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["map","blobBufferUtil","flatClone","PROMISE_RESOLVE_VOID","newRxError","ensureSchemaSupportsAttachments","doc","schemaJson","collection","schema","jsonSchema","attachments","link","_assignMethodsToAttachment","attachment","Object","entries","forEach","funName","fun","defineProperty","get","bind","RxAttachment","id","type","length","digest","remove","incrementalWriteQueue","addWrite","_data","docWriteData","_attachments","then","getData","storageInstance","getAttachmentData","primary","plainDataBase64","createBlobBufferFromBase64","ret","getStringData","data","toString","asString","fromStorageInstanceResult","attachmentData","rxDocument","putAttachment","dataSize","size","toBase64String","dataString","writeResult","newDocument","_docCache","getCachedRxDocument","attachmentDataOfId","getAttachment","docData","allAttachments","keys","preMigrateDocument","newAttachments","Promise","all","attachmentId","docPrimary","oldCollection","primaryPath","rawAttachmentData","postMigrateDocument","_action","RxDBAttachmentsPlugin","name","rxdb","prototypes","RxDocument","proto","allAttachments$","$","pipe","overwritable","hooks","after"],"sources":["../../../../src/plugins/attachments/index.ts"],"sourcesContent":["import {\n map\n} from 'rxjs/operators';\n\nimport {\n blobBufferUtil,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDocument,\n RxPlugin,\n BlobBuffer,\n OldRxCollection,\n RxDocumentWriteData,\n RxAttachmentData,\n RxDocumentData,\n RxAttachmentCreator,\n RxAttachmentWriteData\n} from '../../types';\n\nfunction ensureSchemaSupportsAttachments(doc: any) {\n const schemaJson = doc.collection.schema.jsonSchema;\n if (!schemaJson.attachments) {\n throw newRxError('AT1', {\n link: 'https://pubkey.github.io/rxdb/rx-attachment.html'\n });\n }\n}\n\nconst _assignMethodsToAttachment = function (attachment: any) {\n Object\n .entries(attachment.doc.collection.attachments)\n .forEach(([funName, fun]) => {\n Object.defineProperty(attachment, funName, {\n get: () => (fun as any).bind(attachment)\n });\n });\n};\n\n/**\n * an RxAttachment is basically just the attachment-stub\n * wrapped so that you can access the attachment-data\n */\nexport class RxAttachment {\n public doc: RxDocument;\n public id: string;\n public type: string;\n public length: number;\n public digest: string;\n constructor({\n doc,\n id,\n type,\n length,\n digest\n }: any) {\n this.doc = doc;\n this.id = id;\n this.type = type;\n this.length = length;\n this.digest = digest;\n\n _assignMethodsToAttachment(this);\n }\n\n remove(): Promise {\n return this.doc.collection.incrementalWriteQueue.addWrite(\n this.doc._data,\n docWriteData => {\n delete docWriteData._attachments[this.id];\n return docWriteData;\n }\n ).then(() => { });\n }\n\n /**\n * returns the data for the attachment\n */\n async getData(): Promise {\n const plainDataBase64 = await this.doc.collection.storageInstance.getAttachmentData(\n this.doc.primary,\n this.id\n );\n const ret = await blobBufferUtil.createBlobBufferFromBase64(\n plainDataBase64,\n this.type as any\n );\n return ret;\n }\n\n async getStringData(): Promise {\n const data = await this.getData();\n const asString = await blobBufferUtil.toString(data);\n return asString;\n }\n}\n\nexport function fromStorageInstanceResult(\n id: string,\n attachmentData: RxAttachmentData,\n rxDocument: RxDocument\n) {\n return new RxAttachment({\n doc: rxDocument,\n id,\n type: attachmentData.type,\n length: attachmentData.length,\n digest: attachmentData.digest\n });\n}\n\nexport async function putAttachment(\n this: RxDocument,\n attachmentData: RxAttachmentCreator\n): Promise {\n ensureSchemaSupportsAttachments(this);\n\n const dataSize = blobBufferUtil.size(attachmentData.data);\n const dataString = await blobBufferUtil.toBase64String(attachmentData.data);\n\n const id = attachmentData.id;\n const type = attachmentData.type;\n const data = dataString;\n\n return this.collection.incrementalWriteQueue.addWrite(\n this._data,\n (docWriteData: RxDocumentWriteData) => {\n docWriteData._attachments = flatClone(docWriteData._attachments);\n\n docWriteData._attachments[id] = {\n length: dataSize,\n type,\n data\n };\n return docWriteData;\n }).then(writeResult => {\n const newDocument = this.collection._docCache.getCachedRxDocument(writeResult);\n const attachmentDataOfId = writeResult._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentDataOfId,\n newDocument\n );\n return attachment;\n });\n}\n\n/**\n * get an attachment of the document by its id\n */\nexport function getAttachment(\n this: RxDocument,\n id: string\n): RxAttachment | null {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._data;\n if (!docData._attachments || !docData._attachments[id])\n return null;\n\n const attachmentData = docData._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n return attachment;\n}\n\n/**\n * returns all attachments of the document\n */\nexport function allAttachments(\n this: RxDocument\n): RxAttachment[] {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._data;\n\n // if there are no attachments, the field is missing\n if (!docData._attachments) {\n return [];\n }\n return Object.keys(docData._attachments)\n .map(id => {\n return fromStorageInstanceResult(\n id,\n docData._attachments[id],\n this\n );\n });\n}\n\nexport async function preMigrateDocument(\n data: {\n docData: RxDocumentData;\n oldCollection: OldRxCollection;\n }\n): Promise {\n const attachments = data.docData._attachments;\n if (attachments) {\n const newAttachments: { [attachmentId: string]: RxAttachmentWriteData; } = {};\n await Promise.all(\n Object.keys(attachments).map(async (attachmentId) => {\n const attachment: RxAttachmentData = attachments[attachmentId];\n const docPrimary: string = (data.docData as any)[data.oldCollection.schema.primaryPath];\n const rawAttachmentData = await data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId);\n newAttachments[attachmentId] = {\n length: attachment.length,\n type: attachment.type,\n data: rawAttachmentData\n };\n })\n );\n\n /**\n * Hooks mutate the input\n * instead of returning stuff\n */\n (data.docData as RxDocumentWriteData)._attachments = newAttachments;\n }\n}\n\nexport function postMigrateDocument(_action: any): Promise {\n /**\n * No longer needed because\n * we store the attachments data buffers directly in the document.\n */\n return PROMISE_RESOLVE_VOID;\n}\n\nexport const RxDBAttachmentsPlugin: RxPlugin = {\n name: 'attachments',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.putAttachment = putAttachment;\n proto.getAttachment = getAttachment;\n proto.allAttachments = allAttachments;\n Object.defineProperty(proto, 'allAttachments$', {\n get: function allAttachments$(this: RxDocument) {\n return this.$\n .pipe(\n map(data => Object.entries(\n data._attachments\n )),\n map(entries => {\n return (entries as any)\n .map(([id, attachmentData]: any) => {\n return fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n });\n })\n );\n }\n });\n }\n },\n overwritable: {},\n hooks: {\n preMigrateDocument: {\n after: preMigrateDocument\n },\n postMigrateDocument: {\n after: postMigrateDocument\n }\n }\n};\n"],"mappings":";;AAAA,SACIA,GAAG,QACA,gBAAgB;AAEvB,SACIC,cAAc,EACdC,SAAS,EACTC,oBAAoB,QACjB,qBAAqB;AAC5B,SACIC,UAAU,QACP,gBAAgB;AAavB,SAASC,+BAA+B,CAACC,GAAQ,EAAE;EAC/C,IAAMC,UAAU,GAAGD,GAAG,CAACE,UAAU,CAACC,MAAM,CAACC,UAAU;EACnD,IAAI,CAACH,UAAU,CAACI,WAAW,EAAE;IACzB,MAAMP,UAAU,CAAC,KAAK,EAAE;MACpBQ,IAAI,EAAE;IACV,CAAC,CAAC;EACN;AACJ;AAEA,IAAMC,0BAA0B,GAAG,SAA7BA,0BAA0B,CAAaC,UAAe,EAAE;EAC1DC,MAAM,CACDC,OAAO,CAACF,UAAU,CAACR,GAAG,CAACE,UAAU,CAACG,WAAW,CAAC,CAC9CM,OAAO,CAAC,gBAAoB;IAAA,IAAlBC,OAAO;MAAEC,GAAG;IACnBJ,MAAM,CAACK,cAAc,CAACN,UAAU,EAAEI,OAAO,EAAE;MACvCG,GAAG,EAAE;QAAA,OAAOF,GAAG,CAASG,IAAI,CAACR,UAAU,CAAC;MAAA;IAC5C,CAAC,CAAC;EACN,CAAC,CAAC;AACV,CAAC;;AAED;AACA;AACA;AACA;AACA,WAAaS,YAAY;EAMrB,6BAMQ;IAAA,IALJjB,GAAG,SAAHA,GAAG;MACHkB,EAAE,SAAFA,EAAE;MACFC,IAAI,SAAJA,IAAI;MACJC,MAAM,SAANA,MAAM;MACNC,MAAM,SAANA,MAAM;IAEN,IAAI,CAACrB,GAAG,GAAGA,GAAG;IACd,IAAI,CAACkB,EAAE,GAAGA,EAAE;IACZ,IAAI,CAACC,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACC,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACC,MAAM,GAAGA,MAAM;IAEpBd,0B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AE,SAAS2D,eAAe,GAAmB;UAAA;UAC5C,OAAO,IAAI,CAACC,CAAC,CACRC,IAAI,CACDlF,GAAG,CAAC,UAAA2C,IAAI;YAAA,OAAI5B,MAAM,CAACC,OAAO,CACtB2B,IAAI,CAACV,YAAY,CACpB;UAAA,EAAC,EACFjC,GAAG,CAAC,UAAAgB,OAAO,EAAI;YACX,OAAQA,OAAO,CACVhB,GAAG,CAAC,iBAA+B;cAAA,IAA7BwB,EAAE;gBAAEuB,cAAc;cACrB,OAAOD,yBAAyB,CAC5BtB,EAAE,EACFuB,cAAc,EACd,MAAI,CACP;YACL,CAAC,CAAC;UACV,CAAC,CAAC,CACL;QACT;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;EACDoC,YAAY,EAAE,CAAC,CAAC;EAChBC,KAAK,EAAE;IACHrB,kBAAkB,EAAE;MAChBsB,KAAK,EAAEtB;IACX,CAAC;IACDS,mBAAmB,EAAE;MACjBa,KAAK,EAAEb;IACX;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/backup/file-util.js b/dist/es/plugins/backup/file-util.js index fd6c2281dc9..cb4fa046c1d 100644 --- a/dist/es/plugins/backup/file-util.js +++ b/dist/es/plugins/backup/file-util.js @@ -1,36 +1,12 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import * as fs from 'fs'; import * as path from 'path'; -import { blobBufferUtil, now } from '../../util'; +import { blobBufferUtil, now } from '../../plugins/utils'; /** * ensure that the given folder exists */ - -export var writeToFile = function writeToFile(location, data) { - try { - var _temp2 = function _temp2() { - return new Promise(function (res, rej) { - fs.writeFile(location, data, 'utf-8', function (err) { - if (err) { - rej(err); - } else { - res(); - } - }); - }); - }; - var _temp = function () { - if (typeof data !== 'string') { - return Promise.resolve(blobBufferUtil.toString(data)).then(function (_blobBufferUtil$toStr) { - data = _blobBufferUtil$toStr; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } -}; export function ensureFolderExists(folderPath) { if (!fs.existsSync(folderPath)) { fs.mkdirSync(folderPath, { @@ -70,6 +46,40 @@ export function prepareFolders(database, options) { ensureFolderExists(path.join(options.directory, collectionName)); }); } +export function writeToFile(_x, _x2) { + return _writeToFile.apply(this, arguments); +} +function _writeToFile() { + _writeToFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(location, data) { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(typeof data !== 'string')) { + _context.next = 4; + break; + } + _context.next = 3; + return blobBufferUtil.toString(data); + case 3: + data = _context.sent; + case 4: + return _context.abrupt("return", new Promise(function (res, rej) { + fs.writeFile(location, data, 'utf-8', function (err) { + if (err) { + rej(err); + } else { + res(); + } + }); + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _writeToFile.apply(this, arguments); +} export function writeJsonToFile(location, data) { return writeToFile(location, JSON.stringify(data)); } diff --git a/dist/es/plugins/backup/file-util.js.map b/dist/es/plugins/backup/file-util.js.map index d2e57d79487..b92dd8eea2c 100644 --- a/dist/es/plugins/backup/file-util.js.map +++ b/dist/es/plugins/backup/file-util.js.map @@ -1 +1 @@ -{"version":3,"file":"file-util.js","names":["fs","path","blobBufferUtil","now","writeToFile","location","data","Promise","res","rej","writeFile","err","toString","ensureFolderExists","folderPath","existsSync","mkdirSync","recursive","clearFolder","deleteFolder","rmdirSync","prepareFolders","database","options","directory","metaLoc","metaFileLocation","currentTime","metaData","createdAt","updatedAt","collectionStates","writeFileSync","JSON","stringify","Object","keys","collections","forEach","collectionName","join","writeJsonToFile","getMeta","loc","readFile","metaContent","parse","setMeta","meta","documentFolder","docId"],"sources":["../../../../src/plugins/backup/file-util.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n BackupMetaFileContent,\n BackupOptions,\n BlobBuffer,\n RxDatabase\n} from '../../types';\nimport { blobBufferUtil, now } from '../../util';\n\n/**\n * ensure that the given folder exists\n */\nexport function ensureFolderExists(folderPath: string): void {\n if (!fs.existsSync(folderPath)) {\n fs.mkdirSync(folderPath, { recursive: true });\n }\n}\n\n/**\n * deletes and recreates the folder\n */\nexport function clearFolder(folderPath: string): void {\n deleteFolder(folderPath);\n ensureFolderExists(folderPath);\n}\n\nexport function deleteFolder(folderPath: string): void {\n // only remove if exists to not raise warning\n if (fs.existsSync(folderPath)) {\n fs.rmdirSync(folderPath, { recursive: true });\n }\n}\n\nexport function prepareFolders(\n database: RxDatabase,\n options: BackupOptions\n) {\n ensureFolderExists(options.directory);\n\n const metaLoc = metaFileLocation(options);\n\n if (!fs.existsSync(metaLoc)) {\n const currentTime = now();\n const metaData: BackupMetaFileContent = {\n createdAt: currentTime,\n updatedAt: currentTime,\n collectionStates: {}\n };\n fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8');\n }\n\n Object.keys(database.collections).forEach(collectionName => {\n ensureFolderExists(\n path.join(\n options.directory,\n collectionName\n )\n );\n });\n}\n\nexport async function writeToFile(\n location: string,\n data: string | BlobBuffer\n): Promise {\n if (typeof data !== 'string') {\n data = await blobBufferUtil.toString(data);\n }\n return new Promise(function (res, rej) {\n fs.writeFile(\n location,\n data as string,\n 'utf-8',\n (err) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n }\n );\n });\n}\n\nexport function writeJsonToFile(\n location: string,\n data: any\n): Promise {\n return writeToFile(\n location,\n JSON.stringify(data)\n );\n}\n\nexport function metaFileLocation(options: BackupOptions): string {\n return path.join(\n options.directory,\n 'backup_meta.json'\n );\n}\n\nexport function getMeta(options: BackupOptions): Promise {\n const loc = metaFileLocation(options);\n return new Promise((res, rej) => {\n fs.readFile(loc, 'utf-8', (err, data) => {\n if (err) {\n rej(err);\n } else {\n const metaContent = JSON.parse(data);\n res(metaContent);\n }\n });\n });\n}\n\nexport function setMeta(\n options: BackupOptions,\n meta: BackupMetaFileContent\n): Promise {\n const loc = metaFileLocation(options);\n return writeJsonToFile(loc, meta);\n}\n\nexport function documentFolder(\n options: BackupOptions,\n docId: string\n): string {\n return path.join(\n options.directory,\n docId\n );\n}\n"],"mappings":"AAAA,OAAO,KAAKA,EAAE,MAAM,IAAI;AACxB,OAAO,KAAKC,IAAI,MAAM,MAAM;AAO5B,SAASC,cAAc,EAAEC,GAAG,QAAQ,YAAY;;AAEhD;AACA;AACA;;AAkDA,WAAsBC,WAAW,YAAXA,WAAW,CAC7BC,QAAgB,EAChBC,IAAyB;EAAA,IACZ;IAAA;MAIb,OAAO,IAAIC,OAAO,CAAC,UAAUC,GAAG,EAAEC,GAAG,EAAE;QACnCT,EAAE,CAACU,SAAS,CACRL,QAAQ,EACRC,IAAI,EACJ,OAAO,EACP,UAACK,GAAG,EAAK;UACL,IAAIA,GAAG,EAAE;YACLF,GAAG,CAACE,GAAG,CAAC;UACZ,CAAC,MAAM;YACHH,GAAG,EAAE;UACT;QACJ,CAAC,CACJ;MACL,CAAC,CAAC;IAAC;IAAA;MAAA,IAhBC,OAAOF,IAAI,KAAK,QAAQ;QAAA,uBACXJ,cAAc,CAACU,QAAQ,CAACN,IAAI,CAAC;UAA1CA,IAAI,wBAAsC;QAAC;MAAA;IAAA;IAAA;EAgBnD,CAAC;IAAA;EAAA;AAAA;AAtED,OAAO,SAASO,kBAAkB,CAACC,UAAkB,EAAQ;EACzD,IAAI,CAACd,EAAE,CAACe,UAAU,CAACD,UAAU,CAAC,EAAE;IAC5Bd,EAAE,CAACgB,SAAS,CAACF,UAAU,EAAE;MAAEG,SAAS,EAAE;IAAK,CAAC,CAAC;EACjD;AACJ;;AAEA;AACA;AACA;AACA,OAAO,SAASC,WAAW,CAACJ,UAAkB,EAAQ;EAClDK,YAAY,CAACL,UAAU,CAAC;EACxBD,kBAAkB,CAACC,UAAU,CAAC;AAClC;AAEA,OAAO,SAASK,YAAY,CAACL,UAAkB,EAAQ;EACnD;EACA,IAAId,EAAE,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,OAAO,CAAC,UAACC,GAAG,EAAEC,GAAG,EAAK;IAC7BT,EAAE,CAAC4C,QAAQ,CAACD,GAAG,EAAE,OAAO,EAAE,UAAChC,GAAG,EAAEL,IAAI,EAAK;MACrC,IAAIK,GAAG,EAAE;QACLF,GAAG,CAACE,GAAG,CAAC;MACZ,CAAC,MAAM;QACH,IAAMkC,WAAW,GAAGZ,IAAI,CAACa,KAAK,CAACxC,IAAI,CAAC;QACpCE,GAAG,CAACqC,WAAW,CAAC;MACpB;IACJ,CAAC,CAAC;EACN,CAAC,CAAC;AACN;AAEA,OAAO,SAASE,OAAO,CACnBxB,OAAsB,EACtByB,IAA2B,EACd;EACb,IAAML,GAAG,GAAGjB,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAOkB,eAAe,CAACE,GAAG,EAAEK,IAAI,CAAC;AACrC;AAEA,OAAO,SAASC,cAAc,CAC1B1B,OAAsB,EACtB2B,KAAa,EACP;EACN,OAAOjD,IAAI,CAACuC,IAAI,CACZjB,OAAO,CAACC,SAAS,EACjB0B,KAAK,CACR;AACL"} \ No newline at end of file +{"version":3,"file":"file-util.js","names":["fs","path","blobBufferUtil","now","ensureFolderExists","folderPath","existsSync","mkdirSync","recursive","clearFolder","deleteFolder","rmdirSync","prepareFolders","database","options","directory","metaLoc","metaFileLocation","currentTime","metaData","createdAt","updatedAt","collectionStates","writeFileSync","JSON","stringify","Object","keys","collections","forEach","collectionName","join","writeToFile","location","data","toString","Promise","res","rej","writeFile","err","writeJsonToFile","getMeta","loc","readFile","metaContent","parse","setMeta","meta","documentFolder","docId"],"sources":["../../../../src/plugins/backup/file-util.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n BackupMetaFileContent,\n BackupOptions,\n BlobBuffer,\n RxDatabase\n} from '../../types';\nimport { blobBufferUtil, now } from '../../plugins/utils';\n\n/**\n * ensure that the given folder exists\n */\nexport function ensureFolderExists(folderPath: string): void {\n if (!fs.existsSync(folderPath)) {\n fs.mkdirSync(folderPath, { recursive: true });\n }\n}\n\n/**\n * deletes and recreates the folder\n */\nexport function clearFolder(folderPath: string): void {\n deleteFolder(folderPath);\n ensureFolderExists(folderPath);\n}\n\nexport function deleteFolder(folderPath: string): void {\n // only remove if exists to not raise warning\n if (fs.existsSync(folderPath)) {\n fs.rmdirSync(folderPath, { recursive: true });\n }\n}\n\nexport function prepareFolders(\n database: RxDatabase,\n options: BackupOptions\n) {\n ensureFolderExists(options.directory);\n\n const metaLoc = metaFileLocation(options);\n\n if (!fs.existsSync(metaLoc)) {\n const currentTime = now();\n const metaData: BackupMetaFileContent = {\n createdAt: currentTime,\n updatedAt: currentTime,\n collectionStates: {}\n };\n fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8');\n }\n\n Object.keys(database.collections).forEach(collectionName => {\n ensureFolderExists(\n path.join(\n options.directory,\n collectionName\n )\n );\n });\n}\n\nexport async function writeToFile(\n location: string,\n data: string | BlobBuffer\n): Promise {\n if (typeof data !== 'string') {\n data = await blobBufferUtil.toString(data);\n }\n return new Promise(function (res, rej) {\n fs.writeFile(\n location,\n data as string,\n 'utf-8',\n (err) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n }\n );\n });\n}\n\nexport function writeJsonToFile(\n location: string,\n data: any\n): Promise {\n return writeToFile(\n location,\n JSON.stringify(data)\n );\n}\n\nexport function metaFileLocation(options: BackupOptions): string {\n return path.join(\n options.directory,\n 'backup_meta.json'\n );\n}\n\nexport function getMeta(options: BackupOptions): Promise {\n const loc = metaFileLocation(options);\n return new Promise((res, rej) => {\n fs.readFile(loc, 'utf-8', (err, data) => {\n if (err) {\n rej(err);\n } else {\n const metaContent = JSON.parse(data);\n res(metaContent);\n }\n });\n });\n}\n\nexport function setMeta(\n options: BackupOptions,\n meta: BackupMetaFileContent\n): Promise {\n const loc = metaFileLocation(options);\n return writeJsonToFile(loc, meta);\n}\n\nexport function documentFolder(\n options: BackupOptions,\n docId: string\n): string {\n return path.join(\n options.directory,\n docId\n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AE,UAACH,GAAG,EAAEN,IAAI,EAAK;MACrC,IAAIM,GAAG,EAAE;QACLF,GAAG,CAACE,GAAG,CAAC;MACZ,CAAC,MAAM;QACH,IAAMK,WAAW,GAAGrB,IAAI,CAACsB,KAAK,CAACZ,IAAI,CAAC;QACpCG,GAAG,CAACQ,WAAW,CAAC;MACpB;IACJ,CAAC,CAAC;EACN,CAAC,CAAC;AACN;AAEA,OAAO,SAASE,OAAO,CACnBjC,OAAsB,EACtBkC,IAA2B,EACd;EACb,IAAML,GAAG,GAAG1B,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAO2B,eAAe,CAACE,GAAG,EAAEK,IAAI,CAAC;AACrC;AAEA,OAAO,SAASC,cAAc,CAC1BnC,OAAsB,EACtBoC,KAAa,EACP;EACN,OAAOjD,IAAI,CAAC8B,IAAI,CACZjB,OAAO,CAACC,SAAS,EACjBmC,KAAK,CACR;AACL"} \ No newline at end of file diff --git a/dist/es/plugins/backup/index.js b/dist/es/plugins/backup/index.js index 403839b5a3a..7b100505b7c 100644 --- a/dist/es/plugins/backup/index.js +++ b/dist/es/plugins/backup/index.js @@ -1,200 +1,79 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import * as path from 'path'; import { BehaviorSubject, firstValueFrom, Subject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { newRxError } from '../../rx-error'; -import { getFromMapOrThrow, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, PROMISE_RESOLVE_VOID } from '../../util'; +import { getFromMapOrThrow, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, PROMISE_RESOLVE_VOID } from '../../plugins/utils'; import { clearFolder, deleteFolder, documentFolder, ensureFolderExists, getMeta, prepareFolders, setMeta, writeJsonToFile, writeToFile } from './file-util'; /** * Backups a single documents, * returns the paths to all written files */ -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; +export function backupSingleDocument(_x, _x2) { + return _backupSingleDocument.apply(this, arguments); } -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); +function _backupSingleDocument() { + _backupSingleDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(rxDocument, options) { + var data, writtenFiles, docFolder, fileLocation, attachmentsFolder, attachments; + return _regeneratorRuntime.wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + data = rxDocument.toJSON(true); + writtenFiles = []; + docFolder = documentFolder(options, rxDocument.primary); + _context7.next = 5; + return clearFolder(docFolder); + case 5: + fileLocation = path.join(docFolder, 'document.json'); + _context7.next = 8; + return writeJsonToFile(fileLocation, data); + case 8: + writtenFiles.push(fileLocation); + if (!options.attachments) { + _context7.next = 15; + break; + } + attachmentsFolder = path.join(docFolder, 'attachments'); + ensureFolderExists(attachmentsFolder); + attachments = rxDocument.allAttachments(); + _context7.next = 15; + return Promise.all(attachments.map( /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(attachment) { + var content, attachmentFileLocation; + return _regeneratorRuntime.wrap(function _callee5$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return attachment.getData(); + case 2: + content = _context6.sent; + attachmentFileLocation = path.join(attachmentsFolder, attachment.id); + _context6.next = 6; + return writeToFile(attachmentFileLocation, content); + case 6: + writtenFiles.push(attachmentFileLocation); + case 7: + case "end": + return _context6.stop(); + } + }, _callee5); + })); + return function (_x6) { + return _ref5.apply(this, arguments); + }; + }())); + case 15: + return _context7.abrupt("return", writtenFiles); + case 16: + case "end": + return _context7.stop(); } - } else { - _settle(pact, 1, result); - } - } + }, _callee6); + })); + return _backupSingleDocument.apply(this, arguments); } -export var backupSingleDocument = function backupSingleDocument(rxDocument, options) { - try { - var data = rxDocument.toJSON(true); - var writtenFiles = []; - var docFolder = documentFolder(options, rxDocument.primary); - return Promise.resolve(clearFolder(docFolder)).then(function () { - var fileLocation = path.join(docFolder, 'document.json'); - return Promise.resolve(writeJsonToFile(fileLocation, data)).then(function () { - writtenFiles.push(fileLocation); - var _temp = function () { - if (options.attachments) { - var attachmentsFolder = path.join(docFolder, 'attachments'); - ensureFolderExists(attachmentsFolder); - var attachments = rxDocument.allAttachments(); - return Promise.resolve(Promise.all(attachments.map(function (attachment) { - try { - return Promise.resolve(attachment.getData()).then(function (content) { - var attachmentFileLocation = path.join(attachmentsFolder, attachment.id); - return Promise.resolve(writeToFile(attachmentFileLocation, content)).then(function () { - writtenFiles.push(attachmentFileLocation); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(function () { - return writtenFiles; - }) : writtenFiles; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; var BACKUP_STATES_BY_DB = new WeakMap(); function addToBackupStates(db, state) { if (!BACKUP_STATES_BY_DB.has(db)) { @@ -237,103 +116,181 @@ export var RxBackupState = /*#__PURE__*/function () { return _this._persistOnce(); }); }; - _proto._persistOnce = function _persistOnce() { - try { + _proto._persistOnce = /*#__PURE__*/function () { + var _persistOnce2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { var _this2 = this; - return Promise.resolve(getMeta(_this2.options)).then(function (meta) { - return Promise.resolve(Promise.all(Object.entries(_this2.database.collections).map(function (_ref) { - try { - var collectionName = _ref[0], - collection = _ref[1]; - var primaryKey = collection.schema.primaryPath; - var processedDocuments = new Set(); - return Promise.resolve(_this2.database.requestIdlePromise()).then(function () { - function _temp3() { - meta.collectionStates[collectionName].checkpoint = lastCheckpoint; - return Promise.resolve(setMeta(_this2.options, meta)).then(function () {}); - } - if (!meta.collectionStates[collectionName]) { - meta.collectionStates[collectionName] = {}; - } - var lastCheckpoint = meta.collectionStates[collectionName].checkpoint; - var hasMore = true; - var _temp2 = _for(function () { - return !!hasMore && !_this2.isStopped; - }, void 0, function () { - return Promise.resolve(_this2.database.requestIdlePromise()).then(function () { - return Promise.resolve(collection.storageInstance.getChangedDocumentsSince(_this2.options.batchSize ? _this2.options.batchSize : 0, lastCheckpoint)).then(function (changesResult) { - lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint; - meta.collectionStates[collectionName].checkpoint = lastCheckpoint; - var docIds = changesResult.documents.map(function (doc) { - return doc[primaryKey]; - }).filter(function (id) { - if (processedDocuments.has(id)) { - return false; - } else { - processedDocuments.add(id); - return true; + var meta; + return _regeneratorRuntime.wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return getMeta(this.options); + case 2: + meta = _context5.sent; + _context5.next = 5; + return Promise.all(Object.entries(this.database.collections).map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref) { + var collectionName, collection, primaryKey, processedDocuments, lastCheckpoint, hasMore, _loop, _ret; + return _regeneratorRuntime.wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + collectionName = _ref[0], collection = _ref[1]; + primaryKey = collection.schema.primaryPath; + processedDocuments = new Set(); + _context4.next = 5; + return _this2.database.requestIdlePromise(); + case 5: + if (!meta.collectionStates[collectionName]) { + meta.collectionStates[collectionName] = {}; } - }).filter(function (elem, pos, arr) { - return arr.indexOf(elem) === pos; - }); // unique - return Promise.resolve(_this2.database.requestIdlePromise()).then(function () { - return Promise.resolve(collection.findByIds(docIds)).then(function (docs) { - if (docs.size === 0) { - hasMore = false; - return; - } - return Promise.resolve(Promise.all(Array.from(docs.values()).map(function (doc) { - try { - return Promise.resolve(backupSingleDocument(doc, _this2.options)).then(function (writtenFiles) { - _this2.internalWriteEvents$.next({ - collectionName: collection.name, - documentId: doc.primary, - files: writtenFiles, - deleted: false - }); - }); - } catch (e) { - return Promise.reject(e); + lastCheckpoint = meta.collectionStates[collectionName].checkpoint; + hasMore = true; + _loop = /*#__PURE__*/_regeneratorRuntime.mark(function _loop() { + var changesResult, docIds, docs; + return _regeneratorRuntime.wrap(function _loop$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return _this2.database.requestIdlePromise(); + case 2: + _context3.next = 4; + return collection.storageInstance.getChangedDocumentsSince(_this2.options.batchSize ? _this2.options.batchSize : 0, lastCheckpoint); + case 4: + changesResult = _context3.sent; + lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint; + meta.collectionStates[collectionName].checkpoint = lastCheckpoint; + docIds = changesResult.documents.map(function (doc) { + return doc[primaryKey]; + }).filter(function (id) { + if (processedDocuments.has(id)) { + return false; + } else { + processedDocuments.add(id); + return true; + } + }).filter(function (elem, pos, arr) { + return arr.indexOf(elem) === pos; + }); // unique + _context3.next = 10; + return _this2.database.requestIdlePromise(); + case 10: + _context3.next = 12; + return collection.findByIds(docIds).exec(); + case 12: + docs = _context3.sent; + if (!(docs.size === 0)) { + _context3.next = 16; + break; + } + hasMore = false; + return _context3.abrupt("return", "continue"); + case 16: + _context3.next = 18; + return Promise.all(Array.from(docs.values()).map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(doc) { + var writtenFiles; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return backupSingleDocument(doc, _this2.options); + case 2: + writtenFiles = _context.sent; + _this2.internalWriteEvents$.next({ + collectionName: collection.name, + documentId: doc.primary, + files: writtenFiles, + deleted: false + }); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 18: + _context3.next = 20; + return Promise.all(docIds.filter(function (docId) { + return !docs.has(docId); + }).map( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(docId) { + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return deleteFolder(documentFolder(_this2.options, docId)); + case 2: + _this2.internalWriteEvents$.next({ + collectionName: collection.name, + documentId: docId, + files: [], + deleted: true + }); + case 3: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x5) { + return _ref4.apply(this, arguments); + }; + }())); + case 20: + case "end": + return _context3.stop(); } - }))).then(function () { - // handle deleted documents - return Promise.resolve(Promise.all(docIds.filter(function (docId) { - return !docs.has(docId); - }).map(function (docId) { - try { - return Promise.resolve(deleteFolder(documentFolder(_this2.options, docId))).then(function () { - _this2.internalWriteEvents$.next({ - collectionName: collection.name, - documentId: docId, - files: [], - deleted: true - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - }); + }, _loop); }); - }); - }); - }); - }); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - if (!_this2.initialReplicationDone$.getValue()) { - _this2.initialReplicationDone$.next(true); - } - }); - }); - } catch (e) { - return Promise.reject(e); + case 9: + if (!(hasMore && !_this2.isStopped)) { + _context4.next = 16; + break; + } + return _context4.delegateYield(_loop(), "t0", 11); + case 11: + _ret = _context4.t0; + if (!(_ret === "continue")) { + _context4.next = 14; + break; + } + return _context4.abrupt("continue", 9); + case 14: + _context4.next = 9; + break; + case 16: + meta.collectionStates[collectionName].checkpoint = lastCheckpoint; + _context4.next = 19; + return setMeta(_this2.options, meta); + case 19: + case "end": + return _context4.stop(); + } + }, _callee3); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }())); + case 5: + if (!this.initialReplicationDone$.getValue()) { + this.initialReplicationDone$.next(true); + } + case 6: + case "end": + return _context5.stop(); + } + }, _callee4, this); + })); + function _persistOnce() { + return _persistOnce2.apply(this, arguments); } - }; + return _persistOnce; + }(); _proto.watchForChanges = function watchForChanges() { var _this3 = this; var collections = Object.values(this.database.collections); diff --git a/dist/es/plugins/backup/index.js.map b/dist/es/plugins/backup/index.js.map index 3e07ac97688..84c6fb1dff3 100644 --- a/dist/es/plugins/backup/index.js.map +++ b/dist/es/plugins/backup/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["path","BehaviorSubject","firstValueFrom","Subject","filter","map","newRxError","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_VOID","clearFolder","deleteFolder","documentFolder","ensureFolderExists","getMeta","prepareFolders","setMeta","writeJsonToFile","writeToFile","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","backupSingleDocument","rxDocument","options","data","toJSON","writtenFiles","docFolder","primary","fileLocation","join","push","attachments","attachmentsFolder","allAttachments","Promise","all","attachment","getData","content","attachmentFileLocation","id","BACKUP_STATES_BY_DB","WeakMap","addToBackupStates","db","has","set","ar","RxBackupState","database","isStopped","subs","persistRunning","initialReplicationDone$","internalWriteEvents$","writeEvents$","asObservable","batchSize","persistOnce","_persistOnce","meta","Object","entries","collections","collectionName","collection","primaryKey","schema","primaryPath","processedDocuments","Set","requestIdlePromise","collectionStates","checkpoint","lastCheckpoint","hasMore","storageInstance","getChangedDocumentsSince","changesResult","documents","length","docIds","doc","add","elem","pos","arr","indexOf","findByIds","docs","size","Array","from","values","next","name","documentId","files","deleted","docId","getValue","watchForChanges","forEach","changes$","changeStream","sub","subscribe","awaitInitialBackup","pipe","cancel","unsubscribe","backup","backupState","live","RxDBBackupPlugin","rxdb","prototypes","RxDatabase","proto","hooks","preDestroyRxDatabase","after","states","get"],"sources":["../../../../src/plugins/backup/index.ts"],"sourcesContent":["import * as path from 'path';\nimport {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n filter,\n map\n} from 'rxjs/operators';\nimport { newRxError } from '../../rx-error';\nimport type {\n BackupOptions,\n RxBackupWriteEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxPlugin\n} from '../../types';\nimport {\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport {\n clearFolder,\n deleteFolder,\n documentFolder,\n ensureFolderExists,\n getMeta,\n prepareFolders,\n setMeta,\n writeJsonToFile,\n writeToFile\n} from './file-util';\n\n\n/**\n * Backups a single documents,\n * returns the paths to all written files\n */\nexport async function backupSingleDocument(\n rxDocument: RxDocument,\n options: BackupOptions\n): Promise {\n const data = rxDocument.toJSON(true);\n const writtenFiles: string[] = [];\n\n const docFolder = documentFolder(options, rxDocument.primary);\n await clearFolder(docFolder);\n\n const fileLocation = path.join(\n docFolder,\n 'document.json'\n );\n await writeJsonToFile(fileLocation, data);\n writtenFiles.push(fileLocation);\n\n if (options.attachments) {\n const attachmentsFolder = path.join(\n docFolder,\n 'attachments'\n );\n ensureFolderExists(attachmentsFolder);\n const attachments = (rxDocument as RxDocument).allAttachments();\n await Promise.all(\n attachments\n .map(async (attachment) => {\n const content = await attachment.getData();\n const attachmentFileLocation = path.join(\n attachmentsFolder,\n attachment.id\n );\n await writeToFile(attachmentFileLocation, content);\n writtenFiles.push(attachmentFileLocation);\n })\n );\n }\n\n return writtenFiles;\n}\n\nconst BACKUP_STATES_BY_DB: WeakMap = new WeakMap();\nfunction addToBackupStates(db: RxDatabase, state: RxBackupState) {\n if (!BACKUP_STATES_BY_DB.has(db)) {\n BACKUP_STATES_BY_DB.set(db, []);\n }\n const ar = getFromMapOrThrow(BACKUP_STATES_BY_DB, db);\n if (!ar) {\n throw newRxError('SNH');\n }\n ar.push(state);\n}\n\nexport class RxBackupState {\n public isStopped: boolean = false;\n private subs: Subscription[] = [];\n private persistRunning: Promise = PROMISE_RESOLVE_VOID;\n private initialReplicationDone$: BehaviorSubject = new BehaviorSubject(false as any);\n\n private readonly internalWriteEvents$: Subject = new Subject();\n public readonly writeEvents$: Observable = this.internalWriteEvents$.asObservable();\n\n constructor(\n public readonly database: RxDatabase,\n public readonly options: BackupOptions\n ) {\n if (!this.options.batchSize) {\n this.options.batchSize = 10;\n }\n addToBackupStates(database, this);\n prepareFolders(database, options);\n }\n\n /**\n * Persists all data from all collections,\n * beginning from the oldest sequence checkpoint\n * to the newest one.\n * Do not call this while it is already running.\n * Returns true if there are more documents to process\n */\n public persistOnce() {\n return this.persistRunning = this.persistRunning.then(() => this._persistOnce());\n }\n\n public async _persistOnce() {\n const meta = await getMeta(this.options);\n\n await Promise.all(\n Object\n .entries(this.database.collections)\n .map(async ([collectionName, collection]) => {\n const primaryKey = collection.schema.primaryPath;\n const processedDocuments: Set = new Set();\n\n await this.database.requestIdlePromise();\n\n if (!meta.collectionStates[collectionName]) {\n meta.collectionStates[collectionName] = {};\n }\n let lastCheckpoint = meta.collectionStates[collectionName].checkpoint;\n\n let hasMore = true;\n while (hasMore && !this.isStopped) {\n await this.database.requestIdlePromise();\n const changesResult = await collection.storageInstance.getChangedDocumentsSince(\n this.options.batchSize ? this.options.batchSize : 0,\n lastCheckpoint\n );\n lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint;\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n\n const docIds: string[] = changesResult.documents\n .map(doc => doc[primaryKey])\n .filter(id => {\n if (\n processedDocuments.has(id)\n ) {\n return false;\n } else {\n processedDocuments.add(id);\n return true;\n }\n })\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique\n await this.database.requestIdlePromise();\n\n const docs: Map = await collection.findByIds(docIds);\n if (docs.size === 0) {\n hasMore = false;\n continue;\n }\n await Promise.all(\n Array\n .from(docs.values())\n .map(async (doc) => {\n const writtenFiles = await backupSingleDocument(doc, this.options);\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: doc.primary,\n files: writtenFiles,\n deleted: false\n });\n })\n );\n // handle deleted documents\n await Promise.all(\n docIds\n .filter(docId => !docs.has(docId))\n .map(async (docId) => {\n await deleteFolder(documentFolder(this.options, docId));\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: docId,\n files: [],\n deleted: true\n });\n })\n );\n }\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n await setMeta(this.options, meta);\n })\n );\n\n if (!this.initialReplicationDone$.getValue()) {\n this.initialReplicationDone$.next(true);\n }\n }\n\n public watchForChanges() {\n const collections: RxCollection[] = Object.values(this.database.collections);\n collections.forEach(collection => {\n const changes$ = collection.storageInstance.changeStream();\n const sub = changes$.subscribe(() => {\n this.persistOnce();\n });\n this.subs.push(sub);\n });\n }\n\n /**\n * Returns a promise that resolves when the initial backup is done\n * and the filesystem is in sync with the database state\n */\n public awaitInitialBackup(): Promise {\n return firstValueFrom(\n this.initialReplicationDone$.pipe(\n filter(v => !!v),\n map(() => true)\n )\n );\n }\n\n cancel(): Promise {\n if (this.isStopped) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.isStopped = true;\n this.subs.forEach(sub => sub.unsubscribe());\n return PROMISE_RESOLVE_TRUE;\n }\n}\n\n\nexport function backup(\n this: RxDatabase,\n options: BackupOptions\n): RxBackupState {\n const backupState = new RxBackupState(this, options);\n backupState.persistOnce();\n\n if (options.live) {\n backupState.watchForChanges();\n }\n\n return backupState;\n}\n\nexport * from './file-util';\nexport const RxDBBackupPlugin: RxPlugin = {\n name: 'backup',\n rxdb: true,\n prototypes: {\n RxDatabase(proto: any) {\n proto.backup = backup;\n }\n },\n hooks: {\n preDestroyRxDatabase: {\n after: function preDestroyRxDatabase(db: RxDatabase) {\n const states = BACKUP_STATES_BY_DB.get(db);\n if (states) {\n states.forEach(state => state.cancel());\n }\n }\n }\n }\n};\n"],"mappings":"AAAA,OAAO,KAAKA,IAAI,MAAM,MAAM;AAC5B,SACIC,eAAe,EACfC,cAAc,EAEdC,OAAO,QAEJ,MAAM;AACb,SACIC,MAAM,EACNC,GAAG,QACA,gBAAgB;AACvB,SAASC,UAAU,QAAQ,gBAAgB;AAS3C,SACIC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,EACpBC,oBAAoB,QACjB,YAAY;AACnB,SACIC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,kBAAkB,EAClBC,OAAO,EACPC,cAAc,EACdC,OAAO,EACPC,eAAe,EACfC,WAAW,QACR,aAAa;;AAGpB;AACA;AACA;AACA;AAJO,iBAAiBC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACK,IAAI,EAAE;MACxBL,KAAK,CAACK,IAAI,CAAC,QAAQD,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAE,CAAC,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,aAAa,CAAC,IAAI,EAAE1B,OAAO,CAAC;EACpD0F,WAAW,CAACtD,WAAW,EAAE;EAEzB,IAAIpC,OAAO,CAAC2F,IAAI,EAAE;IACdD,WAAW,CAACX,eAAe,EAAE;EACjC;EAEA,OAAOW,WAAW;AACtB;AAEA,cAAc,aAAa;AAC3B,OAAO,IAAME,gBAA0B,GAAG;EACtCnB,IAAI,EAAE,QAAQ;EACdoB,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,sBAACC,KAAU,EAAE;MACnBA,KAAK,CAACP,MAAM,GAAGA,MAAM;IACzB;EACJ,CAAC;EACDQ,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAE,SAASD,oBAAoB,CAAC5E,EAAc,EAAE;QACjD,IAAM8E,MAAM,GAAGjF,mBAAmB,CAACkF,GAAG,CAAC/E,EAAE,CAAC;QAC1C,IAAI8E,MAAM,EAAE;UACRA,MAAM,CAACpB,OAAO,CAAC,UAAA5G,KAAK;YAAA,OAAIA,KAAK,CAACmH,MAAM,EAAE;UAAA,EAAC;QAC3C;MACJ;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["path","BehaviorSubject","firstValueFrom","Subject","filter","map","newRxError","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_VOID","clearFolder","deleteFolder","documentFolder","ensureFolderExists","getMeta","prepareFolders","setMeta","writeJsonToFile","writeToFile","backupSingleDocument","rxDocument","options","data","toJSON","writtenFiles","docFolder","primary","fileLocation","join","push","attachments","attachmentsFolder","allAttachments","Promise","all","attachment","getData","content","attachmentFileLocation","id","BACKUP_STATES_BY_DB","WeakMap","addToBackupStates","db","state","has","set","ar","RxBackupState","database","isStopped","subs","persistRunning","initialReplicationDone$","internalWriteEvents$","writeEvents$","asObservable","batchSize","persistOnce","then","_persistOnce","meta","Object","entries","collections","collectionName","collection","primaryKey","schema","primaryPath","processedDocuments","Set","requestIdlePromise","collectionStates","lastCheckpoint","checkpoint","hasMore","storageInstance","getChangedDocumentsSince","changesResult","documents","length","docIds","doc","add","elem","pos","arr","indexOf","findByIds","exec","docs","size","Array","from","values","next","name","documentId","files","deleted","docId","getValue","watchForChanges","forEach","changes$","changeStream","sub","subscribe","awaitInitialBackup","pipe","v","cancel","unsubscribe","backup","backupState","live","RxDBBackupPlugin","rxdb","prototypes","RxDatabase","proto","hooks","preDestroyRxDatabase","after","states","get"],"sources":["../../../../src/plugins/backup/index.ts"],"sourcesContent":["import * as path from 'path';\nimport {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n filter,\n map\n} from 'rxjs/operators';\nimport { newRxError } from '../../rx-error';\nimport type {\n BackupOptions,\n RxBackupWriteEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxPlugin\n} from '../../types';\nimport {\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils';\nimport {\n clearFolder,\n deleteFolder,\n documentFolder,\n ensureFolderExists,\n getMeta,\n prepareFolders,\n setMeta,\n writeJsonToFile,\n writeToFile\n} from './file-util';\n\n\n/**\n * Backups a single documents,\n * returns the paths to all written files\n */\nexport async function backupSingleDocument(\n rxDocument: RxDocument,\n options: BackupOptions\n): Promise {\n const data = rxDocument.toJSON(true);\n const writtenFiles: string[] = [];\n\n const docFolder = documentFolder(options, rxDocument.primary);\n await clearFolder(docFolder);\n\n const fileLocation = path.join(\n docFolder,\n 'document.json'\n );\n await writeJsonToFile(fileLocation, data);\n writtenFiles.push(fileLocation);\n\n if (options.attachments) {\n const attachmentsFolder = path.join(\n docFolder,\n 'attachments'\n );\n ensureFolderExists(attachmentsFolder);\n const attachments = (rxDocument as RxDocument).allAttachments();\n await Promise.all(\n attachments\n .map(async (attachment) => {\n const content = await attachment.getData();\n const attachmentFileLocation = path.join(\n attachmentsFolder,\n attachment.id\n );\n await writeToFile(attachmentFileLocation, content);\n writtenFiles.push(attachmentFileLocation);\n })\n );\n }\n\n return writtenFiles;\n}\n\nconst BACKUP_STATES_BY_DB: WeakMap = new WeakMap();\nfunction addToBackupStates(db: RxDatabase, state: RxBackupState) {\n if (!BACKUP_STATES_BY_DB.has(db)) {\n BACKUP_STATES_BY_DB.set(db, []);\n }\n const ar = getFromMapOrThrow(BACKUP_STATES_BY_DB, db);\n if (!ar) {\n throw newRxError('SNH');\n }\n ar.push(state);\n}\n\nexport class RxBackupState {\n public isStopped: boolean = false;\n private subs: Subscription[] = [];\n private persistRunning: Promise = PROMISE_RESOLVE_VOID;\n private initialReplicationDone$: BehaviorSubject = new BehaviorSubject(false as any);\n\n private readonly internalWriteEvents$: Subject = new Subject();\n public readonly writeEvents$: Observable = this.internalWriteEvents$.asObservable();\n\n constructor(\n public readonly database: RxDatabase,\n public readonly options: BackupOptions\n ) {\n if (!this.options.batchSize) {\n this.options.batchSize = 10;\n }\n addToBackupStates(database, this);\n prepareFolders(database, options);\n }\n\n /**\n * Persists all data from all collections,\n * beginning from the oldest sequence checkpoint\n * to the newest one.\n * Do not call this while it is already running.\n * Returns true if there are more documents to process\n */\n public persistOnce() {\n return this.persistRunning = this.persistRunning.then(() => this._persistOnce());\n }\n\n public async _persistOnce() {\n const meta = await getMeta(this.options);\n\n await Promise.all(\n Object\n .entries(this.database.collections)\n .map(async ([collectionName, collection]) => {\n const primaryKey = collection.schema.primaryPath;\n const processedDocuments: Set = new Set();\n\n await this.database.requestIdlePromise();\n\n if (!meta.collectionStates[collectionName]) {\n meta.collectionStates[collectionName] = {};\n }\n let lastCheckpoint = meta.collectionStates[collectionName].checkpoint;\n\n let hasMore = true;\n while (hasMore && !this.isStopped) {\n await this.database.requestIdlePromise();\n const changesResult = await collection.storageInstance.getChangedDocumentsSince(\n this.options.batchSize ? this.options.batchSize : 0,\n lastCheckpoint\n );\n lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint;\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n\n const docIds: string[] = changesResult.documents\n .map(doc => doc[primaryKey])\n .filter(id => {\n if (\n processedDocuments.has(id)\n ) {\n return false;\n } else {\n processedDocuments.add(id);\n return true;\n }\n })\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique\n await this.database.requestIdlePromise();\n\n const docs: Map = await collection.findByIds(docIds).exec();\n if (docs.size === 0) {\n hasMore = false;\n continue;\n }\n await Promise.all(\n Array\n .from(docs.values())\n .map(async (doc) => {\n const writtenFiles = await backupSingleDocument(doc, this.options);\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: doc.primary,\n files: writtenFiles,\n deleted: false\n });\n })\n );\n // handle deleted documents\n await Promise.all(\n docIds\n .filter(docId => !docs.has(docId))\n .map(async (docId) => {\n await deleteFolder(documentFolder(this.options, docId));\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: docId,\n files: [],\n deleted: true\n });\n })\n );\n }\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n await setMeta(this.options, meta);\n })\n );\n\n if (!this.initialReplicationDone$.getValue()) {\n this.initialReplicationDone$.next(true);\n }\n }\n\n public watchForChanges() {\n const collections: RxCollection[] = Object.values(this.database.collections);\n collections.forEach(collection => {\n const changes$ = collection.storageInstance.changeStream();\n const sub = changes$.subscribe(() => {\n this.persistOnce();\n });\n this.subs.push(sub);\n });\n }\n\n /**\n * Returns a promise that resolves when the initial backup is done\n * and the filesystem is in sync with the database state\n */\n public awaitInitialBackup(): Promise {\n return firstValueFrom(\n this.initialReplicationDone$.pipe(\n filter(v => !!v),\n map(() => true)\n )\n );\n }\n\n cancel(): Promise {\n if (this.isStopped) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.isStopped = true;\n this.subs.forEach(sub => sub.unsubscribe());\n return PROMISE_RESOLVE_TRUE;\n }\n}\n\n\nexport function backup(\n this: RxDatabase,\n options: BackupOptions\n): RxBackupState {\n const backupState = new RxBackupState(this, options);\n backupState.persistOnce();\n\n if (options.live) {\n backupState.watchForChanges();\n }\n\n return backupState;\n}\n\nexport * from './file-util';\nexport const RxDBBackupPlugin: RxPlugin = {\n name: 'backup',\n rxdb: true,\n prototypes: {\n RxDatabase(proto: any) {\n proto.backup = backup;\n }\n },\n hooks: {\n preDestroyRxDatabase: {\n after: function preDestroyRxDatabase(db: RxDatabase) {\n const states = BACKUP_STATES_BY_DB.get(db);\n if (states) {\n states.forEach(state => state.cancel());\n }\n }\n }\n }\n};\n"],"mappings":";;AAAA,OAAO,KAAKA,IAAI,MAAM,MAAM;AAC5B,SACIC,eAAe,EACfC,cAAc,EAEdC,OAAO,QAEJ,MAAM;AACb,SACIC,MAAM,EACNC,GAAG,QACA,gBAAgB;AACvB,SAASC,UAAU,QAAQ,gBAAgB;AAS3C,SACIC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,EACpBC,oBAAoB,QACjB,qBAAqB;AAC5B,SACIC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,kBAAkB,EAClBC,OAAO,EACPC,cAAc,EACdC,OAAO,EACPC,eAAe,EACfC,WAAW,QACR,aAAa;;AAGpB;AACA;AACA;AACA;AACA,gBAAsBC,oBAAoB;EAAA;AAAA;AAuCzC;EAAA,iFAvCM,kBACHC,UAAgC,EAChCC,OAAsB;IAAA;IAAA;MAAA;QAAA;UAEhBC,IAAI,GAAGF,UAAU,CAACG,MAAM,CAAC,IAAI,CAAC;UAC9BC,YAAsB,GAAG,EAAE;UAE3BC,SAAS,GAAGb,cAAc,CAACS,OAAO,EAAED,UAAU,CAACM,OAAO,CAAC;UAAA;UAAA,OACvDhB,WAAW,CAACe,SAAS,CAAC;QAAA;UAEtBE,YAAY,GAAG5B,IAAI,CAAC6B,IAAI,CAC1BH,SAAS,EACT,eAAe,CAClB;UAAA;UAAA,OACKR,eAAe,CAACU,YAAY,EAAEL,IAAI,CAAC;QAAA;UACzCE,YAAY,CA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DQ,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAE,SAASD,oBAAoB,CAAChF,EAAc,EAAE;QACjD,IAAMkF,MAAM,GAAGrF,mBAAmB,CAACsF,GAAG,CAACnF,EAAE,CAAC;QAC1C,IAAIkF,MAAM,EAAE;UACRA,MAAM,CAACrB,OAAO,CAAC,UAAA5D,KAAK;YAAA,OAAIA,KAAK,CAACoE,MAAM,EAAE;UAAA,EAAC;QAC3C;MACJ;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/cleanup/cleanup.js b/dist/es/plugins/cleanup/cleanup.js index 16e63270b4e..65c01875abd 100644 --- a/dist/es/plugins/cleanup/cleanup.js +++ b/dist/es/plugins/cleanup/cleanup.js @@ -1,4 +1,6 @@ -import { PROMISE_RESOLVE_TRUE } from '../../util'; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { PROMISE_RESOLVE_TRUE } from '../../plugins/utils'; import { REPLICATION_STATE_BY_COLLECTION } from '../replication'; import { DEFAULT_CLEANUP_POLICY } from './cleanup-helper'; @@ -9,264 +11,155 @@ import { DEFAULT_CLEANUP_POLICY } from './cleanup-helper'; * The cleanup is a background task which should * not affect the performance of other, more important tasks. */ - -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } +var RXSOTRAGE_CLEANUP_QUEUE = PROMISE_RESOLVE_TRUE; +export function startCleanupForRxCollection(_x) { + return _startCleanupForRxCollection.apply(this, arguments); } -export var runCleanupAfterDelete = function runCleanupAfterDelete(rxCollection, cleanupPolicy) { - try { - var _exit2 = false; - return Promise.resolve(_for(function () { - return !_exit2 && !rxCollection.destroyed; - }, void 0, function () { - return Promise.resolve(rxCollection.promiseWait(cleanupPolicy.runEach)).then(function () { - if (rxCollection.destroyed) { - _exit2 = true; - return; - } - return Promise.resolve(cleanupRxCollection(rxCollection, cleanupPolicy)).then(function () {}); - }); - })); - } catch (e) { - return Promise.reject(e); - } -}; + /** * Runs the cleanup for a single RxCollection */ -export var cleanupRxCollection = function cleanupRxCollection(rxCollection, cleanupPolicy) { - try { - var _exit = false; - var rxDatabase = rxCollection.database; - var storageInstance = rxCollection.storageInstance; - - // run cleanup() until it returns true - var isDone = false; - return Promise.resolve(_for(function () { - return !_exit && !isDone && !rxCollection.destroyed; - }, void 0, function () { - function _temp5() { - return Promise.resolve(rxDatabase.requestIdlePromise()).then(function () { - if (rxCollection.destroyed) { - _exit = true; - return; +function _startCleanupForRxCollection() { + _startCleanupForRxCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(rxCollection) { + var rxDatabase, cleanupPolicy; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + rxDatabase = rxCollection.database; + cleanupPolicy = Object.assign({}, DEFAULT_CLEANUP_POLICY, rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}); + /** + * Wait until minimumDatabaseInstanceAge is reached + * or collection is destroyed. + */ + _context.next = 4; + return rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge); + case 4: + if (!rxCollection.destroyed) { + _context.next = 6; + break; + } + return _context.abrupt("return"); + case 6: + if (!cleanupPolicy.waitForLeadership) { + _context.next = 9; + break; + } + _context.next = 9; + return rxDatabase.waitForLeadership(); + case 9: + if (!rxCollection.destroyed) { + _context.next = 11; + break; } + return _context.abrupt("return"); + case 11: + _context.next = 13; + return cleanupRxCollection(rxCollection, cleanupPolicy); + case 13: + _context.next = 15; + return runCleanupAfterDelete(rxCollection, cleanupPolicy); + case 15: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _startCleanupForRxCollection.apply(this, arguments); +} +export function cleanupRxCollection(_x2, _x3) { + return _cleanupRxCollection.apply(this, arguments); +} +function _cleanupRxCollection() { + _cleanupRxCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rxCollection, cleanupPolicy) { + var rxDatabase, storageInstance, isDone, replicationStates; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + rxDatabase = rxCollection.database; + storageInstance = rxCollection.storageInstance; // run cleanup() until it returns true + isDone = false; + case 3: + if (!(!isDone && !rxCollection.destroyed)) { + _context2.next = 19; + break; + } + if (!cleanupPolicy.awaitReplicationsInSync) { + _context2.next = 9; + break; + } + replicationStates = REPLICATION_STATE_BY_COLLECTION.get(rxCollection); + if (!replicationStates) { + _context2.next = 9; + break; + } + _context2.next = 9; + return Promise.all(replicationStates.map(function (replicationState) { + if (!replicationState.isStopped()) { + return replicationState.awaitInSync(); + } + })); + case 9: + _context2.next = 11; + return rxDatabase.requestIdlePromise(); + case 11: + if (!rxCollection.destroyed) { + _context2.next = 13; + break; + } + return _context2.abrupt("return"); + case 13: RXSOTRAGE_CLEANUP_QUEUE = RXSOTRAGE_CLEANUP_QUEUE.then(function () { if (rxCollection.destroyed) { return true; } return storageInstance.cleanup(cleanupPolicy.minimumDeletedTime); }); - return Promise.resolve(RXSOTRAGE_CLEANUP_QUEUE).then(function (_RXSOTRAGE_CLEANUP_QU) { - isDone = _RXSOTRAGE_CLEANUP_QU; - }); - }); - } - var _temp4 = function () { - if (cleanupPolicy.awaitReplicationsInSync) { - var replicationStates = REPLICATION_STATE_BY_COLLECTION.get(rxCollection); - var _temp3 = function () { - if (replicationStates) { - return Promise.resolve(Promise.all(replicationStates.map(function (replicationState) { - if (!replicationState.isStopped()) { - return replicationState.awaitInSync(); - } - }))).then(function () {}); - } - }(); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - } - }(); - return _temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4); - })); - } catch (e) { - return Promise.reject(e); - } -}; -export var startCleanupForRxCollection = function startCleanupForRxCollection(rxCollection) { - try { - var rxDatabase = rxCollection.database; - var cleanupPolicy = Object.assign({}, DEFAULT_CLEANUP_POLICY, rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}); - - /** - * Wait until minimumDatabaseInstanceAge is reached - * or collection is destroyed. - */ - return Promise.resolve(rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge)).then(function () { - function _temp2() { - if (rxCollection.destroyed) { - return; - } - - // initially cleanup the collection - return Promise.resolve(cleanupRxCollection(rxCollection, cleanupPolicy)).then(function () { - /** - * Afterwards we listen to deletes - * and only re-run the cleanup after - * minimumDeletedTime is reached. - */ - return Promise.resolve(runCleanupAfterDelete(rxCollection, cleanupPolicy)).then(function () {}); - }); + _context2.next = 16; + return RXSOTRAGE_CLEANUP_QUEUE; + case 16: + isDone = _context2.sent; + _context2.next = 3; + break; + case 19: + case "end": + return _context2.stop(); } - if (rxCollection.destroyed) { - return; + }, _callee2); + })); + return _cleanupRxCollection.apply(this, arguments); +} +export function runCleanupAfterDelete(_x4, _x5) { + return _runCleanupAfterDelete.apply(this, arguments); +} +function _runCleanupAfterDelete() { + _runCleanupAfterDelete = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(rxCollection, cleanupPolicy) { + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (rxCollection.destroyed) { + _context3.next = 9; + break; + } + _context3.next = 3; + return rxCollection.promiseWait(cleanupPolicy.runEach); + case 3: + if (!rxCollection.destroyed) { + _context3.next = 5; + break; + } + return _context3.abrupt("return"); + case 5: + _context3.next = 7; + return cleanupRxCollection(rxCollection, cleanupPolicy); + case 7: + _context3.next = 0; + break; + case 9: + case "end": + return _context3.stop(); } - var _temp = function () { - if (cleanupPolicy.waitForLeadership) { - return Promise.resolve(rxDatabase.waitForLeadership()).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); - } -}; -var RXSOTRAGE_CLEANUP_QUEUE = PROMISE_RESOLVE_TRUE; + }, _callee3); + })); + return _runCleanupAfterDelete.apply(this, arguments); +} //# sourceMappingURL=cleanup.js.map \ No newline at end of file diff --git a/dist/es/plugins/cleanup/cleanup.js.map b/dist/es/plugins/cleanup/cleanup.js.map index 16cb99a9f50..709de24b759 100644 --- a/dist/es/plugins/cleanup/cleanup.js.map +++ b/dist/es/plugins/cleanup/cleanup.js.map @@ -1 +1 @@ -{"version":3,"file":"cleanup.js","names":["PROMISE_RESOLVE_TRUE","REPLICATION_STATE_BY_COLLECTION","DEFAULT_CLEANUP_POLICY","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","runCleanupAfterDelete","rxCollection","cleanupPolicy","destroyed","promiseWait","runEach","cleanupRxCollection","rxDatabase","database","storageInstance","isDone","requestIdlePromise","RXSOTRAGE_CLEANUP_QUEUE","cleanup","minimumDeletedTime","awaitReplicationsInSync","replicationStates","get","Promise","all","map","replicationState","isStopped","awaitInSync","startCleanupForRxCollection","Object","assign","minimumCollectionAge","waitForLeadership"],"sources":["../../../../src/plugins/cleanup/cleanup.ts"],"sourcesContent":["import type { RxCleanupPolicy, RxCollection } from '../../types';\nimport { PROMISE_RESOLVE_TRUE } from '../../util';\nimport { REPLICATION_STATE_BY_COLLECTION } from '../replication';\nimport { DEFAULT_CLEANUP_POLICY } from './cleanup-helper';\n\n/**\n * Even on multiple databases,\n * the calls to RxStorage().cleanup()\n * must never run in parallel.\n * The cleanup is a background task which should\n * not affect the performance of other, more important tasks.\n */\nlet RXSOTRAGE_CLEANUP_QUEUE: Promise = PROMISE_RESOLVE_TRUE;\n\nexport async function startCleanupForRxCollection(\n rxCollection: RxCollection\n) {\n const rxDatabase = rxCollection.database;\n const cleanupPolicy = Object.assign(\n {},\n DEFAULT_CLEANUP_POLICY,\n rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}\n );\n\n /**\n * Wait until minimumDatabaseInstanceAge is reached\n * or collection is destroyed.\n */\n await rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge);\n if (rxCollection.destroyed) {\n return;\n }\n\n if (cleanupPolicy.waitForLeadership) {\n await rxDatabase.waitForLeadership();\n }\n if (rxCollection.destroyed) {\n return;\n }\n\n // initially cleanup the collection\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n\n /**\n * Afterwards we listen to deletes\n * and only re-run the cleanup after\n * minimumDeletedTime is reached.\n */\n await runCleanupAfterDelete(rxCollection, cleanupPolicy);\n}\n\n/**\n * Runs the cleanup for a single RxCollection\n */\nexport async function cleanupRxCollection(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n const rxDatabase = rxCollection.database;\n const storageInstance = rxCollection.storageInstance;\n\n // run cleanup() until it returns true\n let isDone = false;\n while (!isDone && !rxCollection.destroyed) {\n if (cleanupPolicy.awaitReplicationsInSync) {\n const replicationStates = REPLICATION_STATE_BY_COLLECTION.get(rxCollection);\n if (replicationStates) {\n await Promise.all(\n replicationStates.map(replicationState => {\n if (!replicationState.isStopped()) {\n return replicationState.awaitInSync();\n }\n })\n );\n }\n }\n\n await rxDatabase.requestIdlePromise();\n if (rxCollection.destroyed) {\n return;\n }\n RXSOTRAGE_CLEANUP_QUEUE = RXSOTRAGE_CLEANUP_QUEUE\n .then(() => {\n if (rxCollection.destroyed) {\n return true;\n }\n return storageInstance.cleanup(cleanupPolicy.minimumDeletedTime);\n });\n isDone = await RXSOTRAGE_CLEANUP_QUEUE;\n }\n}\n\nexport async function runCleanupAfterDelete(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n while (!rxCollection.destroyed) {\n await rxCollection.promiseWait(cleanupPolicy.runEach);\n if (rxCollection.destroyed) {\n return;\n }\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n }\n}\n"],"mappings":"AACA,SAASA,oBAAoB,QAAQ,YAAY;AACjD,SAASC,+BAA+B,QAAQ,gBAAgB;AAChE,SAASC,sBAAsB,QAAQ,kBAAkB;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;;AA4BO,iBAAiBC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACK,IAAI,EAAE;MACxBL,KAAK,CAACK,IAAI,CAAC,QAAQD,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAE,CAAC,CAAC,CAAC;MACxE;IACD;IACAA,IAAI,CAACG,CAAC,GAAGF,KAAK;IACdD,IAAI,CAACI,CAAC,GAAGF,KAAK;IACd,MAAMM,QAAQ,GAAGR,IAAI,CAACK,CAAC;IACvB,IAA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AID,YAAY,CAACE,SAAS,EAAE;QACxB;MACJ;MAAC;QAAA,IAEGD,aAAa,CAAC0B,iBAAiB;UAAA,uBACzBrB,UAAU,CAACqB,iBAAiB,EAAE;QAAA;MAAA;MAAA;IAAA;EAe5C,CAAC;IAAA;EAAA;AAAA;AArCD,IAAIhB,uBAAyC,GAAG1C,oBAAoB"} \ No newline at end of file +{"version":3,"file":"cleanup.js","names":["PROMISE_RESOLVE_TRUE","REPLICATION_STATE_BY_COLLECTION","DEFAULT_CLEANUP_POLICY","RXSOTRAGE_CLEANUP_QUEUE","startCleanupForRxCollection","rxCollection","rxDatabase","database","cleanupPolicy","Object","assign","promiseWait","minimumCollectionAge","destroyed","waitForLeadership","cleanupRxCollection","runCleanupAfterDelete","storageInstance","isDone","awaitReplicationsInSync","replicationStates","get","Promise","all","map","replicationState","isStopped","awaitInSync","requestIdlePromise","then","cleanup","minimumDeletedTime","runEach"],"sources":["../../../../src/plugins/cleanup/cleanup.ts"],"sourcesContent":["import type { RxCleanupPolicy, RxCollection } from '../../types';\nimport { PROMISE_RESOLVE_TRUE } from '../../plugins/utils';\nimport { REPLICATION_STATE_BY_COLLECTION } from '../replication';\nimport { DEFAULT_CLEANUP_POLICY } from './cleanup-helper';\n\n/**\n * Even on multiple databases,\n * the calls to RxStorage().cleanup()\n * must never run in parallel.\n * The cleanup is a background task which should\n * not affect the performance of other, more important tasks.\n */\nlet RXSOTRAGE_CLEANUP_QUEUE: Promise = PROMISE_RESOLVE_TRUE;\n\nexport async function startCleanupForRxCollection(\n rxCollection: RxCollection\n) {\n const rxDatabase = rxCollection.database;\n const cleanupPolicy = Object.assign(\n {},\n DEFAULT_CLEANUP_POLICY,\n rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}\n );\n\n /**\n * Wait until minimumDatabaseInstanceAge is reached\n * or collection is destroyed.\n */\n await rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge);\n if (rxCollection.destroyed) {\n return;\n }\n\n if (cleanupPolicy.waitForLeadership) {\n await rxDatabase.waitForLeadership();\n }\n if (rxCollection.destroyed) {\n return;\n }\n\n // initially cleanup the collection\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n\n /**\n * Afterwards we listen to deletes\n * and only re-run the cleanup after\n * minimumDeletedTime is reached.\n */\n await runCleanupAfterDelete(rxCollection, cleanupPolicy);\n}\n\n/**\n * Runs the cleanup for a single RxCollection\n */\nexport async function cleanupRxCollection(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n const rxDatabase = rxCollection.database;\n const storageInstance = rxCollection.storageInstance;\n\n // run cleanup() until it returns true\n let isDone = false;\n while (!isDone && !rxCollection.destroyed) {\n if (cleanupPolicy.awaitReplicationsInSync) {\n const replicationStates = REPLICATION_STATE_BY_COLLECTION.get(rxCollection);\n if (replicationStates) {\n await Promise.all(\n replicationStates.map(replicationState => {\n if (!replicationState.isStopped()) {\n return replicationState.awaitInSync();\n }\n })\n );\n }\n }\n\n await rxDatabase.requestIdlePromise();\n if (rxCollection.destroyed) {\n return;\n }\n RXSOTRAGE_CLEANUP_QUEUE = RXSOTRAGE_CLEANUP_QUEUE\n .then(() => {\n if (rxCollection.destroyed) {\n return true;\n }\n return storageInstance.cleanup(cleanupPolicy.minimumDeletedTime);\n });\n isDone = await RXSOTRAGE_CLEANUP_QUEUE;\n }\n}\n\nexport async function runCleanupAfterDelete(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n while (!rxCollection.destroyed) {\n await rxCollection.promiseWait(cleanupPolicy.runEach);\n if (rxCollection.destroyed) {\n return;\n }\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n }\n}\n"],"mappings":";;AACA,SAASA,oBAAoB,QAAQ,qBAAqB;AAC1D,SAASC,+BAA+B,QAAQ,gBAAgB;AAChE,SAASC,sBAAsB,QAAQ,kBAAkB;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIC,uBAAyC,GAAGH,oBAAoB;AAEpE,gB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vEe,iBAAiB;YAAA;YAAA;UAAA;UAAA;UAAA,OACXE,OAAO,CAACC,GAAG,CACbH,iBAAiB,CAACI,GAAG,CAAC,UAAAC,gBAAgB,EAAI;YACtC,IAAI,CAACA,gBAAgB,CAACC,SAAS,EAAE,EAAE;cAC/B,OAAOD,gBAAgB,CAACE,WAAW,EAAE;YACzC;UACJ,CAAC,CAAC,CACL;QAAA;UAAA;UAAA,OAIHrB,UAAU,CAACsB,kBAAkB,EAAE;QAAA;UAAA,KACjCvB,YAAY,CAACQ,SAAS;YAAA;YAAA;UAAA;UAAA;QAAA;UAG1BV,uBAAuB,GAAGA,uBAAuB,CAC5C0B,IAAI,CAAC,YAAM;YACR,IAAIxB,YAAY,CAACQ,SAAS,EAAE;cACxB,OAAO,IAAI;YACf;YACA,OAAOI,eAAe,CAACa,OAAO,CAACtB,aAAa,CAACuB,kBAAkB,CAAC;UACpE,CAAC,CAAC;UAAC;UAAA,OACQ5B,uBAAuB;QAAA;UAAtCe,MAAM;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAEb;EAAA;AAAA;AAED,gBAAsBF,qBAAqB;EAAA;AAAA;AAW1C;EAAA,kFAXM,kBACHX,YAA0B,EAC1BG,aAA8B;IAAA;MAAA;QAAA;UAAA,IAEtBH,YAAY,CAACQ,SAAS;YAAA;YAAA;UAAA;UAAA;UAAA,OACpBR,YAAY,CAACM,WAAW,CAACH,aAAa,CAACwB,OAAO,CAAC;QAAA;UAAA,KACjD3B,YAAY,CAACQ,SAAS;YAAA;YAAA;UAAA;UAAA;QAAA;UAAA;UAAA,OAGpBE,mBAAmB,CAACV,YAAY,EAAEG,aAAa,CAAC;QAAA;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAE7D;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/crdt/index.js b/dist/es/plugins/crdt/index.js index 06785d0f74d..0f4e65f8970 100644 --- a/dist/es/plugins/crdt/index.js +++ b/dist/es/plugins/crdt/index.js @@ -1,102 +1,144 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { newRxError } from '../../rx-error'; import deepEqual from 'fast-deep-equal'; import objectPath from 'object-path'; -import { clone, ensureNotFalsy, now, objectPathMonad } from '../../util'; +import { clone, ensureNotFalsy, now, objectPathMonad, toArray } from '../../plugins/utils'; import modifyjs from 'modifyjs'; import { overwritable } from '../..'; -export var insertCRDT = function insertCRDT(entry) { - try { - var _this2 = this; - entry = overwritable.deepFreezeWhenDevMode(entry); - var jsonSchema = _this2.schema.jsonSchema; - if (!jsonSchema.crdt) { - throw newRxError('CRDT1', { - schema: jsonSchema, - queryObj: entry - }); - } - var crdtOptions = ensureNotFalsy(jsonSchema.crdt); - return Promise.resolve(_this2.database.storageToken).then(function (storageToken) { - var operation = { - body: Array.isArray(entry) ? entry : [entry], - creator: storageToken, - time: now() - }; - var insertData = {}; - insertData = runOperationOnDocument(_this2.database.storage.statics, _this2.schema.jsonSchema, insertData, operation); - var crdtDocField = { - operations: [], - hash: '' - }; - objectPath.set(insertData, crdtOptions.field, crdtDocField); - var lastAr = [operation]; - crdtDocField.operations.push(lastAr); - crdtDocField.hash = hashCRDTOperations(_this2.database.hashFunction, crdtDocField); - return Promise.resolve(_this2.insert(insertData)["catch"](function (err) { - try { - if (err.code === 'COL19') { - // was a conflict, update document instead of inserting - return Promise.resolve(_this2.findOne(err.parameters.id).exec(true)).then(function (doc) { - return doc.updateCRDT(entry); - }); - } else { - throw err; - } - } catch (e) { - return Promise.reject(e); - } - })); - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var updateCRDT = function updateCRDT(entry) { - try { +export function updateCRDT(_x) { + return _updateCRDT.apply(this, arguments); +} +function _updateCRDT() { + _updateCRDT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(entry) { var _this = this; - entry = overwritable.deepFreezeWhenDevMode(entry); - var jsonSchema = _this.collection.schema.jsonSchema; - if (!jsonSchema.crdt) { - throw newRxError('CRDT1', { - schema: jsonSchema, - queryObj: entry - }); - } - var crdtOptions = ensureNotFalsy(jsonSchema.crdt); - return Promise.resolve(_this.collection.database.storageToken).then(function (storageToken) { - return _this.atomicUpdate(function (docData, rxDoc) { - var crdtDocField = clone(objectPath.get(docData, crdtOptions.field)); - var operation = { - body: Array.isArray(entry) ? entry : [entry], - creator: storageToken, - time: now() - }; - - /** - * A new write will ALWAYS be an operation in the last - * array which was non existing before. - */ - var lastAr = [operation]; - crdtDocField.operations.push(lastAr); - crdtDocField.hash = hashCRDTOperations(_this.collection.database.hashFunction, crdtDocField); - var newDocData = clone(rxDoc.toJSON()); - newDocData._deleted = rxDoc._data._deleted; - newDocData = runOperationOnDocument(_this.collection.database.storage.statics, _this.collection.schema.jsonSchema, newDocData, operation); - objectPath.set(newDocData, crdtOptions.field, crdtDocField); + var jsonSchema, crdtOptions, storageToken; + return _regeneratorRuntime.wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + entry = overwritable.deepFreezeWhenDevMode(entry); + jsonSchema = this.collection.schema.jsonSchema; + if (jsonSchema.crdt) { + _context3.next = 4; + break; + } + throw newRxError('CRDT1', { + schema: jsonSchema, + queryObj: entry + }); + case 4: + crdtOptions = ensureNotFalsy(jsonSchema.crdt); + _context3.next = 7; + return this.collection.database.storageToken; + case 7: + storageToken = _context3.sent; + return _context3.abrupt("return", this.incrementalModify(function (docData) { + var crdtDocField = clone(objectPath.get(docData, crdtOptions.field)); + var operation = { + body: toArray(entry), + creator: storageToken, + time: now() + }; - // add other internal fields - var fullDocData = Object.assign({ - _attachments: rxDoc._data._attachments, - _meta: rxDoc._data._meta, - _rev: rxDoc._data._rev - }, newDocData); - return fullDocData; - }, RX_CRDT_CONTEXT); - }); - } catch (e) { - return Promise.reject(e); - } -}; + /** + * A new write will ALWAYS be an operation in the last + * array which was non existing before. + */ + var lastAr = [operation]; + crdtDocField.operations.push(lastAr); + crdtDocField.hash = hashCRDTOperations(_this.collection.database.hashFunction, crdtDocField); + docData = runOperationOnDocument(_this.collection.database.storage.statics, _this.collection.schema.jsonSchema, docData, operation); + objectPath.set(docData, crdtOptions.field, crdtDocField); + return docData; + }, RX_CRDT_CONTEXT)); + case 9: + case "end": + return _context3.stop(); + } + }, _callee2, this); + })); + return _updateCRDT.apply(this, arguments); +} +export function insertCRDT(_x2) { + return _insertCRDT.apply(this, arguments); +} +function _insertCRDT() { + _insertCRDT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(entry) { + var _this2 = this; + var jsonSchema, crdtOptions, storageToken, operation, insertData, crdtDocField, lastAr, result; + return _regeneratorRuntime.wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + entry = overwritable.deepFreezeWhenDevMode(entry); + jsonSchema = this.schema.jsonSchema; + if (jsonSchema.crdt) { + _context5.next = 4; + break; + } + throw newRxError('CRDT1', { + schema: jsonSchema, + queryObj: entry + }); + case 4: + crdtOptions = ensureNotFalsy(jsonSchema.crdt); + _context5.next = 7; + return this.database.storageToken; + case 7: + storageToken = _context5.sent; + operation = { + body: Array.isArray(entry) ? entry : [entry], + creator: storageToken, + time: now() + }; + insertData = {}; + insertData = runOperationOnDocument(this.database.storage.statics, this.schema.jsonSchema, insertData, operation); + crdtDocField = { + operations: [], + hash: '' + }; + objectPath.set(insertData, crdtOptions.field, crdtDocField); + lastAr = [operation]; + crdtDocField.operations.push(lastAr); + crdtDocField.hash = hashCRDTOperations(this.database.hashFunction, crdtDocField); + _context5.next = 18; + return this.insert(insertData)["catch"]( /*#__PURE__*/function () { + var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(err) { + var doc; + return _regeneratorRuntime.wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(err.code === 'CONFLICT')) { + _context4.next = 7; + break; + } + _context4.next = 3; + return _this2.findOne(err.parameters.id).exec(true); + case 3: + doc = _context4.sent; + return _context4.abrupt("return", doc.updateCRDT(entry)); + case 7: + throw err; + case 8: + case "end": + return _context4.stop(); + } + }, _callee3); + })); + return function (_x4) { + return _ref6.apply(this, arguments); + }; + }()); + case 18: + result = _context5.sent; + return _context5.abrupt("return", result); + case 20: + case "end": + return _context5.stop(); + } + }, _callee4, this); + })); + return _insertCRDT.apply(this, arguments); +} export function sortOperationComparator(a, b) { return a.creator > b.creator ? 1 : -1; } @@ -278,10 +320,10 @@ export var RxDBcrdtPlugin = { } }); }; - var oldAtomicPatch = proto.atomicPatch; - proto.atomicPatch = function (patch) { + var oldincrementalPatch = proto.incrementalPatch; + proto.incrementalPatch = function (patch) { if (!this.collection.schema.jsonSchema.crdt) { - return oldAtomicPatch.bind(this)(patch); + return oldincrementalPatch.bind(this)(patch); } return this.updateCRDT({ ifMatch: { @@ -289,13 +331,13 @@ export var RxDBcrdtPlugin = { } }); }; - var oldAtomicUpdate = proto.atomicUpdate; - proto.atomicUpdate = function (fn, context) { + var oldincrementalModify = proto.incrementalModify; + proto.incrementalModify = function (fn, context) { if (!this.collection.schema.jsonSchema.crdt) { - return oldAtomicUpdate.bind(this)(fn); + return oldincrementalModify.bind(this)(fn); } if (context === RX_CRDT_CONTEXT) { - return oldAtomicUpdate.bind(this)(fn); + return oldincrementalModify.bind(this)(fn); } else { throw newRxError('CRDT2', { id: this.primary, @@ -379,40 +421,52 @@ export var RxDBcrdtPlugin = { }; } var bulkInsertBefore = collection.bulkInsert.bind(collection); - collection.bulkInsert = function (docsData) { - try { - return Promise.resolve(collection.database.storageToken).then(function (storageToken) { - var useDocsData = docsData.map(function (docData) { - var setMe = {}; - Object.entries(docData).forEach(function (_ref4) { - var key = _ref4[0], - value = _ref4[1]; - if (!key.startsWith('_') && key !== crdtField) { - setMe[key] = value; - } - }); - var crdtOperations = { - operations: [[{ - creator: storageToken, - body: [{ - ifMatch: { - $set: setMe + collection.bulkInsert = /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(docsData) { + var storageToken, useDocsData; + return _regeneratorRuntime.wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return collection.database.storageToken; + case 2: + storageToken = _context2.sent; + useDocsData = docsData.map(function (docData) { + var setMe = {}; + Object.entries(docData).forEach(function (_ref5) { + var key = _ref5[0], + value = _ref5[1]; + if (!key.startsWith('_') && key !== crdtField) { + setMe[key] = value; } - }], - time: now() - }]], - hash: '' - }; - crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations); - objectPath.set(docData, crdtOptions.field, crdtOperations); - return docData; - }); - return bulkInsertBefore(useDocsData); - }); - } catch (e) { - return Promise.reject(e); - } - }; + }); + var crdtOperations = { + operations: [[{ + creator: storageToken, + body: [{ + ifMatch: { + $set: setMe + } + }], + time: now() + }]], + hash: '' + }; + crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations); + objectPath.set(docData, crdtOptions.field, crdtOperations); + return docData; + }); + return _context2.abrupt("return", bulkInsertBefore(useDocsData)); + case 5: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return function (_x3) { + return _ref4.apply(this, arguments); + }; + }(); } } } diff --git a/dist/es/plugins/crdt/index.js.map b/dist/es/plugins/crdt/index.js.map index 22bde96ee09..c6b72aeeada 100644 --- a/dist/es/plugins/crdt/index.js.map +++ b/dist/es/plugins/crdt/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["newRxError","deepEqual","objectPath","clone","ensureNotFalsy","now","objectPathMonad","modifyjs","overwritable","insertCRDT","entry","deepFreezeWhenDevMode","jsonSchema","schema","crdt","queryObj","crdtOptions","database","storageToken","operation","body","Array","isArray","creator","time","insertData","runOperationOnDocument","storage","statics","crdtDocField","operations","hash","set","field","lastAr","push","hashCRDTOperations","hashFunction","insert","err","code","findOne","parameters","id","exec","doc","updateCRDT","collection","atomicUpdate","docData","rxDoc","get","newDocData","toJSON","_deleted","_data","fullDocData","Object","assign","_attachments","_meta","_rev","RX_CRDT_CONTEXT","sortOperationComparator","a","b","storageStatics","entryParts","forEach","entryPart","isMatching","selector","preparedQuery","prepareQuery","sort","skip","matcher","getQueryMatcher","ifMatch","ifNotMatch","crdts","hashObj","map","op","JSON","stringify","getCRDTSchemaPart","operationSchema","type","properties","items","additionalProperties","minItems","minimum","maximum","multipleOf","required","minLength","mergeCRDTFields","crdtsA","crdtsB","length","ret","row","index","mergedOps","ids","Set","add","has","rebuildFromCRDT","base","getCRDTConflictHandler","crdtField","getCRDTValue","conflictHandler","i","_context","newDocCrdt","newDocumentState","masterDocCrdt","realMasterState","Promise","resolve","isEqual","mergedCrdt","mergedDoc","documentData","RxDBcrdtPlugin","name","rxdb","prototypes","RxDocument","proto","oldRemove","remove","bind","$set","oldAtomicPatch","atomicPatch","patch","oldAtomicUpdate","fn","context","primary","args","RxCollection","hooks","preCreateRxCollection","after","data","createRxCollection","getCrdt","isDevMode","bulkWriteBefore","storageInstance","bulkWrite","writes","write","newDocState","document","rebuild","docWithoutMeta","entries","k","v","startsWith","recalculatedHash","bulkInsertBefore","bulkInsert","docsData","useDocsData","setMe","key","value","crdtOperations"],"sources":["../../../../src/plugins/crdt/index.ts"],"sourcesContent":["import { newRxError } from '../../rx-error';\nimport deepEqual from 'fast-deep-equal';\nimport objectPath from 'object-path';\nimport type {\n CRDTDocumentField,\n CRDTEntry,\n CRDTOperation,\n HashFunction,\n JsonSchema,\n RxConflictHandler,\n RxConflictHandlerInput,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n RxPlugin,\n RxStorageStatics,\n WithDeleted\n} from '../../types';\nimport {\n clone,\n ensureNotFalsy,\n now,\n objectPathMonad\n} from '../../util';\nimport modifyjs from 'modifyjs';\nimport {\n overwritable,\n RxCollection,\n RxDocumentWriteData,\n RxError\n} from '../..';\n\n\n\nexport async function updateCRDT(\n this: RxDocument,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.collection.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.collection.database.storageToken;\n\n return this.atomicUpdate((docData, rxDoc) => {\n const crdtDocField: CRDTDocumentField = clone(objectPath.get(docData as any, crdtOptions.field));\n const operation: CRDTOperation = {\n body: Array.isArray(entry) ? entry : [entry],\n creator: storageToken,\n time: now()\n };\n\n /**\n * A new write will ALWAYS be an operation in the last\n * array which was non existing before.\n */\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.collection.database.hashFunction, crdtDocField);\n\n let newDocData: WithDeleted = clone(rxDoc.toJSON()) as any;\n newDocData._deleted = rxDoc._data._deleted;\n newDocData = runOperationOnDocument(\n this.collection.database.storage.statics,\n this.collection.schema.jsonSchema,\n newDocData,\n operation\n );\n objectPath.set(newDocData, crdtOptions.field, crdtDocField);\n\n // add other internal fields\n const fullDocData: RxDocumentData = Object.assign({\n _attachments: rxDoc._data._attachments,\n _meta: rxDoc._data._meta,\n _rev: rxDoc._data._rev\n }, newDocData);\n\n return fullDocData;\n }, RX_CRDT_CONTEXT);\n}\n\n\nexport async function insertCRDT(\n this: RxCollection,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.database.storageToken;\n const operation: CRDTOperation = {\n body: Array.isArray(entry) ? entry : [entry],\n creator: storageToken,\n time: now()\n };\n\n let insertData: RxDocumentWriteData = {} as any;\n insertData = runOperationOnDocument(\n this.database.storage.statics,\n this.schema.jsonSchema,\n insertData as any,\n operation\n ) as any;\n const crdtDocField: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n objectPath.set(insertData as any, crdtOptions.field, crdtDocField);\n\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.database.hashFunction, crdtDocField);\n\n const result = await this.insert(insertData).catch(async (err: RxError) => {\n if (err.code === 'COL19') {\n // was a conflict, update document instead of inserting\n const doc = await this.findOne(err.parameters.id).exec(true);\n return doc.updateCRDT(entry);\n } else {\n throw err;\n }\n });\n return result;\n}\n\n\nexport function sortOperationComparator(a: CRDTOperation, b: CRDTOperation) {\n return a.creator > b.creator ? 1 : -1;\n}\n\n\nfunction runOperationOnDocument(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n operation: CRDTOperation\n): WithDeleted {\n const entryParts = operation.body;\n entryParts.forEach(entryPart => {\n let isMatching: boolean;\n if (entryPart.selector) {\n const preparedQuery = storageStatics.prepareQuery(schema, {\n selector: ensureNotFalsy(entryPart.selector),\n sort: [],\n skip: 0\n });\n const matcher = storageStatics.getQueryMatcher(schema, preparedQuery);\n isMatching = matcher(docData as any);\n } else {\n isMatching = true;\n }\n if (isMatching) {\n if (entryPart.ifMatch) {\n docData = modifyjs(docData, entryPart.ifMatch);\n }\n } else {\n if (entryPart.ifNotMatch) {\n docData = modifyjs(docData, entryPart.ifNotMatch);\n }\n }\n });\n return docData;\n}\n\nexport function hashCRDTOperations(\n hashFunction: HashFunction,\n crdts: CRDTDocumentField\n): string {\n const hashObj = crdts.operations.map((operations) => {\n return operations.map(op => op.creator);\n });\n const hash = hashFunction(JSON.stringify(hashObj));\n return hash;\n}\n\nexport function getCRDTSchemaPart(): JsonSchema> {\n const operationSchema: JsonSchema> = {\n type: 'object',\n properties: {\n body: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n selector: {\n type: 'object'\n },\n ifMatch: {\n type: 'object'\n },\n ifNotMatch: {\n type: 'object'\n }\n },\n additionalProperties: false\n },\n minItems: 1\n },\n creator: {\n type: 'string'\n },\n time: {\n type: 'number',\n minimum: 1,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n additionalProperties: false,\n required: [\n 'body',\n 'creator',\n 'time'\n ]\n };\n return {\n type: 'object',\n properties: {\n operations: {\n type: 'array',\n items: {\n type: 'array',\n items: operationSchema\n }\n },\n hash: {\n type: 'string',\n // set a minLength to not accidentally store an empty string\n minLength: 2\n }\n },\n additionalProperties: false,\n required: ['operations', 'hash']\n };\n}\n\n\nexport function mergeCRDTFields(\n hashFunction: HashFunction,\n crdtsA: CRDTDocumentField,\n crdtsB: CRDTDocumentField\n): CRDTDocumentField {\n\n // the value with most operations must be A to\n // ensure we not miss out rows when iterating over both fields.\n if (crdtsA.operations.length < crdtsB.operations.length) {\n [crdtsA, crdtsB] = [crdtsB, crdtsA];\n }\n\n const ret: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n crdtsA.operations.forEach((row, index) => {\n let mergedOps: CRDTOperation[] = [];\n const ids = new Set(); // used to deduplicate\n\n row.forEach(op => {\n ids.add(op.creator);\n mergedOps.push(op);\n });\n if (crdtsB.operations[index]) {\n crdtsB.operations[index].forEach(op => {\n if (!ids.has(op.creator)) {\n mergedOps.push(op);\n }\n });\n }\n mergedOps = mergedOps.sort(sortOperationComparator);\n ret.operations[index] = mergedOps;\n });\n\n\n ret.hash = hashCRDTOperations(hashFunction, ret);\n return ret;\n}\n\nexport function rebuildFromCRDT(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n crdts: CRDTDocumentField\n): WithDeleted {\n let base: WithDeleted = {\n _deleted: false\n } as any;\n objectPath.set(base, ensureNotFalsy(schema.crdt).field, crdts);\n crdts.operations.forEach(operations => {\n operations.forEach(op => {\n base = runOperationOnDocument(\n storageStatics,\n schema,\n base,\n op\n );\n });\n });\n return base;\n}\n\n\nexport function getCRDTConflictHandler(\n hashFunction: HashFunction,\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>\n): RxConflictHandler {\n const crdtOptions = ensureNotFalsy(schema.crdt);\n const crdtField = crdtOptions.field;\n const getCRDTValue = objectPathMonad, CRDTDocumentField>(crdtField);\n\n const conflictHandler: RxConflictHandler = (\n i: RxConflictHandlerInput,\n _context: string\n ) => {\n const newDocCrdt = getCRDTValue(i.newDocumentState);\n const masterDocCrdt = getCRDTValue(i.realMasterState);\n\n if (newDocCrdt.hash === masterDocCrdt.hash) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n const mergedCrdt = mergeCRDTFields(hashFunction, newDocCrdt, masterDocCrdt);\n const mergedDoc = rebuildFromCRDT(\n storageStatics,\n schema,\n i.newDocumentState,\n mergedCrdt\n );\n return Promise.resolve({\n isEqual: false,\n documentData: mergedDoc\n });\n };\n\n return conflictHandler;\n}\n\n\nexport const RX_CRDT_CONTEXT = 'rx-crdt';\n\nexport const RxDBcrdtPlugin: RxPlugin = {\n name: 'crdt',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.updateCRDT = updateCRDT;\n\n const oldRemove = proto.remove;\n proto.remove = function (this: RxDocument) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldRemove.bind(this)();\n }\n return this.updateCRDT({\n ifMatch: {\n $set: {\n _deleted: true\n }\n }\n });\n };\n\n const oldAtomicPatch = proto.atomicPatch;\n proto.atomicPatch = function (this: RxDocument, patch: any) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldAtomicPatch.bind(this)(patch);\n }\n return this.updateCRDT({\n ifMatch: {\n $set: patch\n }\n });\n };\n const oldAtomicUpdate = proto.atomicUpdate;\n proto.atomicUpdate = function (fn: any, context: string) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldAtomicUpdate.bind(this)(fn);\n }\n if (context === RX_CRDT_CONTEXT) {\n return oldAtomicUpdate.bind(this)(fn);\n } else {\n throw newRxError('CRDT2', {\n id: this.primary,\n args: { context }\n });\n }\n };\n },\n RxCollection: (proto: any) => {\n proto.insertCRDT = insertCRDT;\n }\n },\n overwritable: {},\n hooks: {\n preCreateRxCollection: {\n after: (data) => {\n if (!data.schema.crdt) {\n return;\n }\n if (data.conflictHandler) {\n throw newRxError('CRDT3', {\n collection: data.name,\n schema: data.schema\n });\n }\n data.conflictHandler = getCRDTConflictHandler(\n data.database.hashFunction,\n data.database.storage.statics,\n data.schema\n );\n }\n },\n createRxCollection: {\n after: ({ collection }) => {\n if (!collection.schema.jsonSchema.crdt) {\n return;\n }\n\n const crdtOptions = ensureNotFalsy(collection.schema.jsonSchema.crdt);\n const crdtField = crdtOptions.field;\n const getCrdt = objectPathMonad>(crdtOptions.field);\n\n /**\n * In dev-mode we have to ensure that all document writes\n * have the correct crdt state so that nothing is missed out\n * or could accidentally do non-crdt writes to the document.\n */\n if (overwritable.isDevMode()) {\n const bulkWriteBefore = collection.storageInstance.bulkWrite.bind(collection.storageInstance);\n collection.storageInstance.bulkWrite = function (writes, context) {\n\n writes.forEach(write => {\n const newDocState: typeof write.document = clone(write.document);\n const crdts = getCrdt(newDocState);\n\n const rebuild = rebuildFromCRDT(\n collection.database.storage.statics,\n collection.schema.jsonSchema,\n newDocState,\n crdts\n );\n\n function docWithoutMeta(doc: any) {\n const ret: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (!k.startsWith('_')) {\n ret[k] = v;\n }\n });\n return ret;\n }\n if (!deepEqual(docWithoutMeta(newDocState), docWithoutMeta(rebuild))) {\n throw newRxError('SNH', {\n document: newDocState\n });\n }\n const recalculatedHash = hashCRDTOperations(collection.database.hashFunction, crdts);\n if (crdts.hash !== recalculatedHash) {\n throw newRxError('SNH', {\n document: newDocState,\n args: { hash: crdts.hash, recalculatedHash }\n });\n }\n });\n\n return bulkWriteBefore(writes, context);\n };\n }\n\n\n const bulkInsertBefore = collection.bulkInsert.bind(collection);\n collection.bulkInsert = async function (docsData: any[]) {\n const storageToken = await collection.database.storageToken;\n const useDocsData = docsData.map(docData => {\n const setMe: Partial> = {};\n Object.entries(docData).forEach(([key, value]) => {\n if (\n !key.startsWith('_') &&\n key !== crdtField\n ) {\n setMe[key] = value;\n }\n });\n\n const crdtOperations: CRDTDocumentField = {\n operations: [\n [{\n creator: storageToken,\n body: [{\n ifMatch: {\n $set: setMe\n }\n }],\n time: now()\n }]\n ],\n hash: ''\n };\n crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations);\n objectPath.set(docData, crdtOptions.field, crdtOperations);\n return docData;\n });\n return bulkInsertBefore(useDocsData);\n };\n }\n }\n }\n};\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,gBAAgB;AAC3C,OAAOC,SAAS,MAAM,iBAAiB;AACvC,OAAOC,UAAU,MAAM,aAAa;AAgBpC,SACIC,KAAK,EACLC,cAAc,EACdC,GAAG,EACHC,eAAe,QACZ,YAAY;AACnB,OAAOC,QAAQ,MAAM,UAAU;AAC/B,SACIC,YAAY,QAIT,OAAO;AA0Dd,WAAsBC,UAAU,YAAVA,UAAU,CAE5BC,KAAoD;EAAA,IACtD;IAAA,aAGqB,IAAI;IAFvBA,KAAK,GAAGF,YAAY,CAACG,qBAAqB,CAACD,KAAK,CAAQ;IAExD,IAAME,UAAU,GAAG,OAAKC,MAAM,CAACD,UAAU;IACzC,IAAI,CAACA,UAAU,CAACE,IAAI,EAAE;MAClB,MAAMd,UAAU,CAAC,OAAO,EAAE;QACtBa,MAAM,EAAED,UAAU;QAClBG,QAAQ,EAAEL;MACd,CAAC,CAAC;IACN;IACA,IAAMM,WAAW,GAAGZ,cAAc,CAACQ,UAAU,CAACE,IAAI,CAAC;IAAC,uBACzB,OAAKG,QAAQ,CAACC,YAAY,iBAA/CA,YAAY;MAClB,IAAMC,SAAmC,GAAG;QACxCC,IAAI,EAAEC,KAAK,CAACC,OAAO,CAACZ,KAAK,CAAC,GAAGA,KAAK,GAAG,CAACA,KAAK,CAAC;QAC5Ca,OAAO,EAAEL,YAAY;QACrBM,IAAI,EAAEn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AAMyJ,WAAW,GAAGD,QAAQ,CAACxF,GAAG,CAAC,UAAAjC,OAAO,EAAI;gBACxC,IAAM2H,KAAmC,GAAG,CAAC,CAAC;gBAC9CnH,MAAM,CAAC0G,OAAO,CAAClH,OAAO,CAAC,CAACmB,OAAO,CAAC,iBAAkB;kBAAA,IAAhByG,GAAG;oBAAEC,KAAK;kBACxC,IACI,CAACD,GAAG,CAACP,UAAU,CAAC,GAAG,CAAC,IACpBO,GAAG,KAAK5D,SAAS,EACnB;oBACE2D,KAAK,CAACC,GAAG,CAAC,GAAGC,KAAK;kBACtB;gBACJ,CAAC,CAAC;gBAEF,IAAMC,cAAsC,GAAG;kBAC3CjJ,UAAU,EAAE,CACR,CAAC;oBACGP,OAAO,EAAEL,YAAY;oBACrBE,IAAI,EAAE,CAAC;sBACH0D,OAAO,EAAE;wBACL2D,IAAI,EAAEmC;sBACV;oBACJ,CAAC,CAAC;oBACFpJ,IAAI,EAAEnB,GAAG;kBACb,CAAC,CAAC,CACL;kBACD0B,IAAI,EAAE;gBACV,CAAC;gBACDgJ,cAAc,CAAChJ,IAAI,GAAGK,kBAAkB,CAACW,UAAU,CAAC9B,QAAQ,CAACoB,YAAY,EAAE0I,cAAc,CAAC;gBAC1F7K,UAAU,CAAC8B,GAAG,CAACiB,OAAO,EAAEjC,WAAW,CAACiB,KAAK,EAAE8I,cAAc,CAAC;gBAC1D,OAAO9H,OAAO;cAClB,CAAC,CAAC;cACF,OAAOuH,gBAAgB,CAACG,WAAW,CAAC;YAAC;UACzC,CAAC;YAAA;UAAA;QAAA;MACL;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["newRxError","deepEqual","objectPath","clone","ensureNotFalsy","now","objectPathMonad","toArray","modifyjs","overwritable","updateCRDT","entry","deepFreezeWhenDevMode","jsonSchema","collection","schema","crdt","queryObj","crdtOptions","database","storageToken","incrementalModify","docData","crdtDocField","get","field","operation","body","creator","time","lastAr","operations","push","hash","hashCRDTOperations","hashFunction","runOperationOnDocument","storage","statics","set","RX_CRDT_CONTEXT","insertCRDT","Array","isArray","insertData","insert","err","code","findOne","parameters","id","exec","doc","result","sortOperationComparator","a","b","storageStatics","entryParts","forEach","entryPart","isMatching","selector","preparedQuery","prepareQuery","sort","skip","matcher","getQueryMatcher","ifMatch","ifNotMatch","crdts","hashObj","map","op","JSON","stringify","getCRDTSchemaPart","operationSchema","type","properties","items","additionalProperties","minItems","minimum","maximum","multipleOf","required","minLength","mergeCRDTFields","crdtsA","crdtsB","length","ret","row","index","mergedOps","ids","Set","add","has","rebuildFromCRDT","base","_deleted","getCRDTConflictHandler","crdtField","getCRDTValue","conflictHandler","i","_context","newDocCrdt","newDocumentState","masterDocCrdt","realMasterState","Promise","resolve","isEqual","mergedCrdt","mergedDoc","documentData","RxDBcrdtPlugin","name","rxdb","prototypes","RxDocument","proto","oldRemove","remove","bind","$set","oldincrementalPatch","incrementalPatch","patch","oldincrementalModify","fn","context","primary","args","RxCollection","hooks","preCreateRxCollection","after","data","createRxCollection","getCrdt","isDevMode","bulkWriteBefore","storageInstance","bulkWrite","writes","write","newDocState","document","rebuild","docWithoutMeta","Object","entries","k","v","startsWith","recalculatedHash","bulkInsertBefore","bulkInsert","docsData","useDocsData","setMe","key","value","crdtOperations"],"sources":["../../../../src/plugins/crdt/index.ts"],"sourcesContent":["import { newRxError } from '../../rx-error';\nimport deepEqual from 'fast-deep-equal';\nimport objectPath from 'object-path';\nimport type {\n CRDTDocumentField,\n CRDTEntry,\n CRDTOperation,\n HashFunction,\n JsonSchema,\n RxConflictHandler,\n RxConflictHandlerInput,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n RxPlugin,\n RxStorageStatics,\n WithDeleted\n} from '../../types';\nimport {\n clone,\n ensureNotFalsy,\n now,\n objectPathMonad,\n toArray\n} from '../../plugins/utils';\nimport modifyjs from 'modifyjs';\nimport {\n overwritable,\n RxCollection,\n RxDocumentWriteData,\n RxError\n} from '../..';\n\n\n\nexport async function updateCRDT(\n this: RxDocument,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.collection.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.collection.database.storageToken;\n\n return this.incrementalModify((docData) => {\n const crdtDocField: CRDTDocumentField = clone(objectPath.get(docData as any, crdtOptions.field));\n const operation: CRDTOperation = {\n body: toArray(entry),\n creator: storageToken,\n time: now()\n };\n\n /**\n * A new write will ALWAYS be an operation in the last\n * array which was non existing before.\n */\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.collection.database.hashFunction, crdtDocField);\n\n docData = runOperationOnDocument(\n this.collection.database.storage.statics,\n this.collection.schema.jsonSchema,\n docData,\n operation\n );\n objectPath.set(docData, crdtOptions.field, crdtDocField);\n return docData;\n }, RX_CRDT_CONTEXT);\n}\n\n\nexport async function insertCRDT(\n this: RxCollection,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.database.storageToken;\n const operation: CRDTOperation = {\n body: Array.isArray(entry) ? entry : [entry],\n creator: storageToken,\n time: now()\n };\n\n let insertData: RxDocumentWriteData = {} as any;\n insertData = runOperationOnDocument(\n this.database.storage.statics,\n this.schema.jsonSchema,\n insertData as any,\n operation\n ) as any;\n const crdtDocField: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n objectPath.set(insertData as any, crdtOptions.field, crdtDocField);\n\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.database.hashFunction, crdtDocField);\n\n const result = await this.insert(insertData).catch(async (err: RxError) => {\n if (err.code === 'CONFLICT') {\n // was a conflict, update document instead of inserting\n const doc = await this.findOne(err.parameters.id).exec(true);\n return doc.updateCRDT(entry);\n } else {\n throw err;\n }\n });\n return result;\n}\n\n\nexport function sortOperationComparator(a: CRDTOperation, b: CRDTOperation) {\n return a.creator > b.creator ? 1 : -1;\n}\n\n\nfunction runOperationOnDocument(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n operation: CRDTOperation\n): WithDeleted {\n const entryParts = operation.body;\n entryParts.forEach(entryPart => {\n let isMatching: boolean;\n if (entryPart.selector) {\n const preparedQuery = storageStatics.prepareQuery(schema, {\n selector: ensureNotFalsy(entryPart.selector),\n sort: [],\n skip: 0\n });\n const matcher = storageStatics.getQueryMatcher(schema, preparedQuery);\n isMatching = matcher(docData as any);\n } else {\n isMatching = true;\n }\n if (isMatching) {\n if (entryPart.ifMatch) {\n docData = modifyjs(docData, entryPart.ifMatch);\n }\n } else {\n if (entryPart.ifNotMatch) {\n docData = modifyjs(docData, entryPart.ifNotMatch);\n }\n }\n });\n return docData;\n}\n\nexport function hashCRDTOperations(\n hashFunction: HashFunction,\n crdts: CRDTDocumentField\n): string {\n const hashObj = crdts.operations.map((operations) => {\n return operations.map(op => op.creator);\n });\n const hash = hashFunction(JSON.stringify(hashObj));\n return hash;\n}\n\nexport function getCRDTSchemaPart(): JsonSchema> {\n const operationSchema: JsonSchema> = {\n type: 'object',\n properties: {\n body: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n selector: {\n type: 'object'\n },\n ifMatch: {\n type: 'object'\n },\n ifNotMatch: {\n type: 'object'\n }\n },\n additionalProperties: false\n },\n minItems: 1\n },\n creator: {\n type: 'string'\n },\n time: {\n type: 'number',\n minimum: 1,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n additionalProperties: false,\n required: [\n 'body',\n 'creator',\n 'time'\n ]\n };\n return {\n type: 'object',\n properties: {\n operations: {\n type: 'array',\n items: {\n type: 'array',\n items: operationSchema\n }\n },\n hash: {\n type: 'string',\n // set a minLength to not accidentally store an empty string\n minLength: 2\n }\n },\n additionalProperties: false,\n required: ['operations', 'hash']\n };\n}\n\n\nexport function mergeCRDTFields(\n hashFunction: HashFunction,\n crdtsA: CRDTDocumentField,\n crdtsB: CRDTDocumentField\n): CRDTDocumentField {\n\n // the value with most operations must be A to\n // ensure we not miss out rows when iterating over both fields.\n if (crdtsA.operations.length < crdtsB.operations.length) {\n [crdtsA, crdtsB] = [crdtsB, crdtsA];\n }\n\n const ret: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n crdtsA.operations.forEach((row, index) => {\n let mergedOps: CRDTOperation[] = [];\n const ids = new Set(); // used to deduplicate\n\n row.forEach(op => {\n ids.add(op.creator);\n mergedOps.push(op);\n });\n if (crdtsB.operations[index]) {\n crdtsB.operations[index].forEach(op => {\n if (!ids.has(op.creator)) {\n mergedOps.push(op);\n }\n });\n }\n mergedOps = mergedOps.sort(sortOperationComparator);\n ret.operations[index] = mergedOps;\n });\n\n\n ret.hash = hashCRDTOperations(hashFunction, ret);\n return ret;\n}\n\nexport function rebuildFromCRDT(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n crdts: CRDTDocumentField\n): WithDeleted {\n let base: WithDeleted = {\n _deleted: false\n } as any;\n objectPath.set(base, ensureNotFalsy(schema.crdt).field, crdts);\n crdts.operations.forEach(operations => {\n operations.forEach(op => {\n base = runOperationOnDocument(\n storageStatics,\n schema,\n base,\n op\n );\n });\n });\n return base;\n}\n\n\nexport function getCRDTConflictHandler(\n hashFunction: HashFunction,\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>\n): RxConflictHandler {\n const crdtOptions = ensureNotFalsy(schema.crdt);\n const crdtField = crdtOptions.field;\n const getCRDTValue = objectPathMonad, CRDTDocumentField>(crdtField);\n\n const conflictHandler: RxConflictHandler = (\n i: RxConflictHandlerInput,\n _context: string\n ) => {\n const newDocCrdt = getCRDTValue(i.newDocumentState);\n const masterDocCrdt = getCRDTValue(i.realMasterState);\n\n if (newDocCrdt.hash === masterDocCrdt.hash) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n const mergedCrdt = mergeCRDTFields(hashFunction, newDocCrdt, masterDocCrdt);\n const mergedDoc = rebuildFromCRDT(\n storageStatics,\n schema,\n i.newDocumentState,\n mergedCrdt\n );\n return Promise.resolve({\n isEqual: false,\n documentData: mergedDoc\n });\n };\n\n return conflictHandler;\n}\n\n\nexport const RX_CRDT_CONTEXT = 'rx-crdt';\n\nexport const RxDBcrdtPlugin: RxPlugin = {\n name: 'crdt',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.updateCRDT = updateCRDT;\n\n const oldRemove = proto.remove;\n proto.remove = function (this: RxDocument) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldRemove.bind(this)();\n }\n return this.updateCRDT({\n ifMatch: {\n $set: {\n _deleted: true\n }\n }\n });\n };\n\n const oldincrementalPatch = proto.incrementalPatch;\n proto.incrementalPatch = function (this: RxDocument, patch: any) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldincrementalPatch.bind(this)(patch);\n }\n return this.updateCRDT({\n ifMatch: {\n $set: patch\n }\n });\n };\n const oldincrementalModify = proto.incrementalModify;\n proto.incrementalModify = function (fn: any, context: string) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldincrementalModify.bind(this)(fn);\n }\n if (context === RX_CRDT_CONTEXT) {\n return oldincrementalModify.bind(this)(fn);\n } else {\n throw newRxError('CRDT2', {\n id: this.primary,\n args: { context }\n });\n }\n };\n },\n RxCollection: (proto: any) => {\n proto.insertCRDT = insertCRDT;\n }\n },\n overwritable: {},\n hooks: {\n preCreateRxCollection: {\n after: (data) => {\n if (!data.schema.crdt) {\n return;\n }\n if (data.conflictHandler) {\n throw newRxError('CRDT3', {\n collection: data.name,\n schema: data.schema\n });\n }\n data.conflictHandler = getCRDTConflictHandler(\n data.database.hashFunction,\n data.database.storage.statics,\n data.schema\n );\n }\n },\n createRxCollection: {\n after: ({ collection }) => {\n if (!collection.schema.jsonSchema.crdt) {\n return;\n }\n\n const crdtOptions = ensureNotFalsy(collection.schema.jsonSchema.crdt);\n const crdtField = crdtOptions.field;\n const getCrdt = objectPathMonad>(crdtOptions.field);\n\n /**\n * In dev-mode we have to ensure that all document writes\n * have the correct crdt state so that nothing is missed out\n * or could accidentally do non-crdt writes to the document.\n */\n if (overwritable.isDevMode()) {\n const bulkWriteBefore = collection.storageInstance.bulkWrite.bind(collection.storageInstance);\n collection.storageInstance.bulkWrite = function (writes, context) {\n\n writes.forEach(write => {\n const newDocState: typeof write.document = clone(write.document);\n const crdts = getCrdt(newDocState);\n\n const rebuild = rebuildFromCRDT(\n collection.database.storage.statics,\n collection.schema.jsonSchema,\n newDocState,\n crdts\n );\n\n function docWithoutMeta(doc: any) {\n const ret: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (!k.startsWith('_')) {\n ret[k] = v;\n }\n });\n return ret;\n }\n if (!deepEqual(docWithoutMeta(newDocState), docWithoutMeta(rebuild))) {\n throw newRxError('SNH', {\n document: newDocState\n });\n }\n const recalculatedHash = hashCRDTOperations(collection.database.hashFunction, crdts);\n if (crdts.hash !== recalculatedHash) {\n throw newRxError('SNH', {\n document: newDocState,\n args: { hash: crdts.hash, recalculatedHash }\n });\n }\n });\n\n return bulkWriteBefore(writes, context);\n };\n }\n\n\n const bulkInsertBefore = collection.bulkInsert.bind(collection);\n collection.bulkInsert = async function (docsData: any[]) {\n const storageToken = await collection.database.storageToken;\n const useDocsData = docsData.map(docData => {\n const setMe: Partial> = {};\n Object.entries(docData).forEach(([key, value]) => {\n if (\n !key.startsWith('_') &&\n key !== crdtField\n ) {\n setMe[key] = value;\n }\n });\n\n const crdtOperations: CRDTDocumentField = {\n operations: [\n [{\n creator: storageToken,\n body: [{\n ifMatch: {\n $set: setMe\n }\n }],\n time: now()\n }]\n ],\n hash: ''\n };\n crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations);\n objectPath.set(docData, crdtOptions.field, crdtOperations);\n return docData;\n });\n return bulkInsertBefore(useDocsData);\n };\n }\n }\n }\n};\n"],"mappings":";;AAAA,SAASA,UAAU,QAAQ,gBAAgB;AAC3C,OAAOC,SAAS,MAAM,iBAAiB;AACvC,OAAOC,UAAU,MAAM,aAAa;AAgBpC,SACIC,KAAK,EACLC,cAAc,EACdC,GAAG,EACHC,eAAe,EACfC,OAAO,QACJ,qBAAqB;AAC5B,OAAOC,QAAQ,MAAM,UAAU;AAC/B,SACIC,YAAY,QAIT,OAAO;AAId,gBAAsBC,UAAU;EAAA;AAAA;AAyC/B;EAAA,uEAzCM,kBAEHC,KAAoD;IAAA;IAAA;IAAA;MAAA;QAAA;UAEpDA,KAAK,GAAGF,YAAY,CAACG,qBAAqB,CAACD,KAAK,CAAQ;UAElDE,UAAU,GAAG,IAAI,CAACC,UAAU,CAACC,MAAM,CAACF,UAAU;UAAA,IAC/CA,UAAU,CAACG,IAAI;YAAA;YAAA;UAAA;UAAA,MACVhB,UAAU,CAAC,OAAO,EAAE;YACtBe,MAAM,EAAEF,UAAU;YAClBI,QAAQ,EAAEN;UACd,CAAC,CAAC;QAAA;UAEAO,WAAW,GAAGd,cAAc,CAACS,UAAU,CAACG,IAAI,CAAC;UAAA;UAAA,OACxB,IAAI,CAACF,UAAU,CAACK,QAAQ,CAACC,YAAY;QAAA;UAA1DA,YAAY;UAAA,kCAEX,IAAI,CAACC,iBAAiB,CAAC,UAACC,OAAO,EAAK;YACvC,IAAMC,YAA0C,GAAGpB,KAAK,CAACD,UAAU,CAACsB,GAAG,CAACF,OAAO,EAASJ,WAAW,CAACO,KAAK,CAAC,CAAC;YAC3G,IAAMC,SAAmC,GAAG;cACxCC,IAAI,EAAEpB,OAAO,CAACI,KAAK,CAAC;cACpBiB,OAAO,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,SAAS,EACnB;wBACE4D,KAAK,CAACC,GAAG,CAAC,GAAGC,KAAK;sBACtB;oBACJ,CAAC,CAAC;oBAEF,IAAMC,cAAsC,GAAG;sBAC3CzI,UAAU,EAAE,CACR,CAAC;wBACGH,OAAO,EAAER,YAAY;wBACrBO,IAAI,EAAE,CAAC;0BACH0C,OAAO,EAAE;4BACL4D,IAAI,EAAEoC;0BACV;wBACJ,CAAC,CAAC;wBACFxI,IAAI,EAAExB,GAAG;sBACb,CAAC,CAAC,CACL;sBACD4B,IAAI,EAAE;oBACV,CAAC;oBACDuI,cAAc,CAACvI,IAAI,GAAGC,kBAAkB,CAACpB,UAAU,CAACK,QAAQ,CAACgB,YAAY,EAAEqI,cAAc,CAAC;oBAC1FtK,UAAU,CAACqC,GAAG,CAACjB,OAAO,EAAEJ,WAAW,CAACO,KAAK,EAAE+I,cAAc,CAAC;oBAC1D,OAAOlJ,OAAO;kBAClB,CAAC,CAAC;kBAAA,kCACK2I,gBAAgB,CAACG,WAAW,CAAC;gBAAA;gBAAA;kBAAA;cAAA;YAAA;UAAA,CACvC;UAAA;YAAA;UAAA;QAAA;MACL;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/check-query.js b/dist/es/plugins/dev-mode/check-query.js index 306d46f161c..a6e031c020d 100644 --- a/dist/es/plugins/dev-mode/check-query.js +++ b/dist/es/plugins/dev-mode/check-query.js @@ -1,7 +1,7 @@ import deepEqual from 'fast-deep-equal'; import { newRxError, newRxTypeError } from '../../rx-error'; import { massageSelector } from 'pouchdb-selector-core'; -import { RxStorageDexieStatics } from '../dexie'; +import { RxStorageDexieStatics } from '../storage-dexie'; /** * accidentally passing a non-valid object into the query params @@ -66,6 +66,7 @@ export function checkMangoQuery(args) { }); } }); + /** * ensure if custom index is set, * it is also defined in the schema @@ -97,6 +98,26 @@ export function checkMangoQuery(args) { }); } } + + /** + * Ensure that sort only runs on known fields + * TODO also check nested fields + */ + if (args.mangoQuery.sort) { + args.mangoQuery.sort.map(function (sortPart) { + return Object.keys(sortPart)[0]; + }).filter(function (field) { + return !field.includes('.'); + }).forEach(function (field) { + if (!schemaTopLevelFields.includes(field)) { + throw newRxError('QU13', { + schema: schema, + field: field, + query: args.mangoQuery + }); + } + }); + } } export function areSelectorsSatisfiedByIndex(schema, query) { var preparedQuery = RxStorageDexieStatics.prepareQuery(schema, query); diff --git a/dist/es/plugins/dev-mode/check-query.js.map b/dist/es/plugins/dev-mode/check-query.js.map index 2ac6c3462bb..fb4a7a01c71 100644 --- a/dist/es/plugins/dev-mode/check-query.js.map +++ b/dist/es/plugins/dev-mode/check-query.js.map @@ -1 +1 @@ -{"version":3,"file":"check-query.js","names":["deepEqual","newRxError","newRxTypeError","massageSelector","RxStorageDexieStatics","checkQuery","args","isPlainObject","Object","prototype","toString","call","queryObj","op","collection","name","validKeys","keys","forEach","key","includes","limit","skip","query","checkMangoQuery","schema","rxQuery","jsonSchema","massagedSelector","mangoQuery","selector","schemaTopLevelFields","properties","filter","fieldOrOperator","startsWith","field","schemaIndexes","indexes","index","isInSchema","find","schemaIndex","areSelectorsSatisfiedByIndex","database","allowSlowCount","preparedQuery","prepareQuery","queryPlan","selectorSatisfiedByIndex"],"sources":["../../../../src/plugins/dev-mode/check-query.ts"],"sourcesContent":["import type {\n RxPluginPreCreateRxQueryArgs,\n MangoQuery,\n RxPluginPrePrepareQueryArgs,\n DexiePreparedQuery,\n FilledMangoQuery,\n RxJsonSchema,\n RxDocumentData,\n MangoQuerySelector\n} from '../../types';\nimport deepEqual from 'fast-deep-equal';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport {\n massageSelector\n} from 'pouchdb-selector-core';\nimport { RxStorageDexieStatics } from '../dexie';\n\n/**\n * accidentally passing a non-valid object into the query params\n * is very hard to debug especially when queries are observed\n * This is why we do some checks here in dev-mode\n */\nexport function checkQuery(args: RxPluginPreCreateRxQueryArgs) {\n const isPlainObject = Object.prototype.toString.call(args.queryObj) === '[object Object]';\n if (!isPlainObject) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj\n });\n }\n\n const validKeys: (keyof MangoQuery)[] = [\n 'selector',\n 'limit',\n 'skip',\n 'sort',\n 'index'\n ];\n Object.keys(args.queryObj).forEach(key => {\n if (!(validKeys as string[]).includes(key)) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj,\n key,\n args: {\n validKeys\n }\n });\n }\n });\n\n // do not allow skip or limit for count queries\n if (\n args.op === 'count' &&\n (\n args.queryObj.limit ||\n args.queryObj.skip\n )\n ) {\n throw newRxError(\n 'QU15',\n {\n collection: args.collection.name,\n query: args.queryObj\n }\n );\n }\n}\n\n\nexport function checkMangoQuery(args: RxPluginPrePrepareQueryArgs) {\n const schema = args.rxQuery.collection.schema.jsonSchema;\n\n /**\n * Ensure that all top level fields are included in the schema.\n * TODO this check can be augmented to also check sub-fields.\n */\n const massagedSelector: MangoQuerySelector = massageSelector(args.mangoQuery.selector);\n const schemaTopLevelFields = Object.keys(schema.properties);\n Object.keys(massagedSelector)\n // do not check operators\n .filter(fieldOrOperator => !fieldOrOperator.startsWith('$'))\n // skip this check on non-top-level fields\n .filter(field => !field.includes('.'))\n .forEach(field => {\n if (!schemaTopLevelFields.includes(field)) {\n throw newRxError('QU13', {\n schema,\n field,\n query: args.mangoQuery,\n });\n }\n });\n /**\n * ensure if custom index is set,\n * it is also defined in the schema\n */\n const schemaIndexes = schema.indexes ? schema.indexes : [];\n const index = args.mangoQuery.index;\n if (index) {\n const isInSchema = schemaIndexes.find(schemaIndex => deepEqual(schemaIndex, index));\n if (!isInSchema) {\n throw newRxError(\n 'QU12',\n {\n collection: args.rxQuery.collection.name,\n query: args.mangoQuery,\n schema\n }\n );\n }\n }\n\n\n /**\n * Ensure that a count() query can only be used\n * with selectors that are fully satisfied by the used index.\n */\n if (args.rxQuery.op === 'count') {\n if (\n !areSelectorsSatisfiedByIndex(\n args.rxQuery.collection.schema.jsonSchema,\n args.mangoQuery\n ) &&\n !args.rxQuery.collection.database.allowSlowCount\n ) {\n throw newRxError('QU14', {\n collection: args.rxQuery.collection,\n query: args.mangoQuery\n });\n }\n }\n}\n\n\nexport function areSelectorsSatisfiedByIndex(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): boolean {\n const preparedQuery: DexiePreparedQuery = RxStorageDexieStatics.prepareQuery(\n schema,\n query\n );\n return preparedQuery.queryPlan.selectorSatisfiedByIndex;\n}\n"],"mappings":"AAUA,OAAOA,SAAS,MAAM,iBAAiB;AACvC,SAASC,UAAU,EAAEC,cAAc,QAAQ,gBAAgB;AAC3D,SACIC,eAAe,QACZ,uBAAuB;AAC9B,SAASC,qBAAqB,QAAQ,UAAU;;AAEhD;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,UAAU,CAACC,IAAkC,EAAE;EAC3D,IAAMC,aAAa,GAAGC,MAAM,CAACC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACL,IAAI,CAACM,QAAQ,CAAC,KAAK,iBAAiB;EACzF,IAAI,CAACL,aAAa,EAAE;IAChB,MAAML,cAAc,CAAC,MAAM,EAAE;MACzBW,EAAE,EAAEP,IAAI,CAACO,EAAE;MACXC,UAAU,EAAER,IAAI,CAACQ,UAAU,CAACC,IAAI;MAChCH,QAAQ,EAAEN,IAAI,CAACM;IACnB,CAAC,CAAC;EACN;EAEA,IAAMI,SAA+B,GAAG,CACpC,UAAU,EACV,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,CACV;EACDR,MAAM,CAACS,IAAI,CAACX,IAAI,CAACM,QAAQ,CAAC,CAACM,OAAO,CAAC,UAAAC,GAAG,EAAI;IACtC,IAAI,CAAEH,SAAS,CAAcI,QAAQ,CAACD,GAAG,CAAC,EAAE;MACxC,MAAMjB,cAAc,CAAC,MAAM,EAAE;QACzBW,EAAE,EAAEP,IAAI,CAACO,EAAE;QACXC,UAAU,EAAER,IAAI,CAACQ,UAAU,CAACC,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C3D"} \ No newline at end of file +{"version":3,"file":"check-query.js","names":["deepEqual","newRxError","newRxTypeError","massageSelector","RxStorageDexieStatics","checkQuery","args","isPlainObject","Object","prototype","toString","call","queryObj","op","collection","name","validKeys","keys","forEach","key","includes","limit","skip","query","checkMangoQuery","schema","rxQuery","jsonSchema","massagedSelector","mangoQuery","selector","schemaTopLevelFields","properties","filter","fieldOrOperator","startsWith","field","schemaIndexes","indexes","index","isInSchema","find","schemaIndex","areSelectorsSatisfiedByIndex","database","allowSlowCount","sort","map","sortPart","preparedQuery","prepareQuery","queryPlan","selectorSatisfiedByIndex"],"sources":["../../../../src/plugins/dev-mode/check-query.ts"],"sourcesContent":["import type {\n RxPluginPreCreateRxQueryArgs,\n MangoQuery,\n RxPluginPrePrepareQueryArgs,\n DexiePreparedQuery,\n FilledMangoQuery,\n RxJsonSchema,\n RxDocumentData,\n MangoQuerySelector\n} from '../../types';\nimport deepEqual from 'fast-deep-equal';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport {\n massageSelector\n} from 'pouchdb-selector-core';\nimport { RxStorageDexieStatics } from '../storage-dexie';\n\n/**\n * accidentally passing a non-valid object into the query params\n * is very hard to debug especially when queries are observed\n * This is why we do some checks here in dev-mode\n */\nexport function checkQuery(args: RxPluginPreCreateRxQueryArgs) {\n const isPlainObject = Object.prototype.toString.call(args.queryObj) === '[object Object]';\n if (!isPlainObject) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj\n });\n }\n\n const validKeys: (keyof MangoQuery)[] = [\n 'selector',\n 'limit',\n 'skip',\n 'sort',\n 'index'\n ];\n Object.keys(args.queryObj).forEach(key => {\n if (!(validKeys as string[]).includes(key)) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj,\n key,\n args: {\n validKeys\n }\n });\n }\n });\n\n // do not allow skip or limit for count queries\n if (\n args.op === 'count' &&\n (\n args.queryObj.limit ||\n args.queryObj.skip\n )\n ) {\n throw newRxError(\n 'QU15',\n {\n collection: args.collection.name,\n query: args.queryObj\n }\n );\n }\n}\n\n\nexport function checkMangoQuery(args: RxPluginPrePrepareQueryArgs) {\n const schema = args.rxQuery.collection.schema.jsonSchema;\n\n /**\n * Ensure that all top level fields are included in the schema.\n * TODO this check can be augmented to also check sub-fields.\n */\n const massagedSelector: MangoQuerySelector = massageSelector(args.mangoQuery.selector);\n const schemaTopLevelFields = Object.keys(schema.properties);\n Object.keys(massagedSelector)\n // do not check operators\n .filter(fieldOrOperator => !fieldOrOperator.startsWith('$'))\n // skip this check on non-top-level fields\n .filter(field => !field.includes('.'))\n .forEach(field => {\n if (!schemaTopLevelFields.includes(field)) {\n throw newRxError('QU13', {\n schema,\n field,\n query: args.mangoQuery,\n });\n }\n });\n\n /**\n * ensure if custom index is set,\n * it is also defined in the schema\n */\n const schemaIndexes = schema.indexes ? schema.indexes : [];\n const index = args.mangoQuery.index;\n if (index) {\n const isInSchema = schemaIndexes.find(schemaIndex => deepEqual(schemaIndex, index));\n if (!isInSchema) {\n throw newRxError(\n 'QU12',\n {\n collection: args.rxQuery.collection.name,\n query: args.mangoQuery,\n schema\n }\n );\n }\n }\n\n\n /**\n * Ensure that a count() query can only be used\n * with selectors that are fully satisfied by the used index.\n */\n if (args.rxQuery.op === 'count') {\n if (\n !areSelectorsSatisfiedByIndex(\n args.rxQuery.collection.schema.jsonSchema,\n args.mangoQuery\n ) &&\n !args.rxQuery.collection.database.allowSlowCount\n ) {\n throw newRxError('QU14', {\n collection: args.rxQuery.collection,\n query: args.mangoQuery\n });\n }\n }\n\n /**\n * Ensure that sort only runs on known fields\n * TODO also check nested fields\n */\n if (args.mangoQuery.sort) {\n args.mangoQuery.sort\n .map(sortPart => Object.keys(sortPart)[0])\n .filter(field => !field.includes('.'))\n .forEach(field => {\n if (!schemaTopLevelFields.includes(field)) {\n throw newRxError('QU13', {\n schema,\n field,\n query: args.mangoQuery,\n });\n }\n });\n }\n}\n\n\nexport function areSelectorsSatisfiedByIndex(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): boolean {\n const preparedQuery: DexiePreparedQuery = RxStorageDexieStatics.prepareQuery(\n schema,\n query\n );\n return preparedQuery.queryPlan.selectorSatisfiedByIndex;\n}\n"],"mappings":"AAUA,OAAOA,SAAS,MAAM,iBAAiB;AACvC,SAASC,UAAU,EAAEC,cAAc,QAAQ,gBAAgB;AAC3D,SACIC,eAAe,QACZ,uBAAuB;AAC9B,SAASC,qBAAqB,QAAQ,kBAAkB;;AAExD;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,UAAU,CAACC,IAAkC,EAAE;EAC3D,IAAMC,aAAa,GAAGC,MAAM,CAACC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACL,IAAI,CAACM,QAAQ,CAAC,KAAK,iBAAiB;EACzF,IAAI,CAACL,aAAa,EAAE;IAChB,MAAML,cAAc,CAAC,MAAM,EAAE;MACzBW,EAAE,EAAEP,IAAI,CAACO,EAAE;MACXC,UAAU,EAAER,IAAI,CAACQ,UAAU,CAACC,IAAI;MAChCH,QAAQ,EAAEN,IAAI,CAACM;IACnB,CAAC,CAAC;EACN;EAEA,IAAMI,SAA+B,GAAG,CACpC,UAAU,EACV,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,CACV;EACDR,MAAM,CAACS,IAAI,CAACX,IAAI,CAACM,QAAQ,CAAC,CAACM,OAAO,CAAC,UAAAC,GAAG,EAAI;IACtC,IAAI,CAAEH,SAAS,CAAcI,QAAQ,CAACD,GAAG,CAAC,EAAE;MACxC,MAAMjB,cAAc,CAAC,MAAM,EAAE;QACzBW,EAAE,EAAEP,IAAI,CAACO,EAAE;QACXC,UAAU,EAAER,IAAI,CAACQ,UAAU,CAACC,IAAI;QAChCH,QAAQ,EAAEN,IAAI,CAACM,QAAQ;QACvBO,GAAG,EAAHA,GAAG;QACHb,IAAI,EAAE;UACFU,SAAS,EAATA;QACJ;MACJ,CAAC,CAAC;IACN;EACJ,CAAC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AC,UAAAkB,KAAK,EAAI;MACd,IAAI,CAACL,oBAAoB,CAACX,QAAQ,CAACgB,KAAK,CAAC,EAAE;QACvC,MAAMnC,UAAU,CAAC,MAAM,EAAE;UACrBwB,MAAM,EAANA,MAAM;UACNW,KAAK,EAALA,KAAK;UACLb,KAAK,EAAEjB,IAAI,CAACuB;QAChB,CAAC,CAAC;MACN;IACJ,CAAC,CAAC;EACV;AACJ;AAGA,OAAO,SAASc,4BAA4B,CACxClB,MAA+C,EAC/CF,KAAkC,EAC3B;EACP,IAAM0B,aAAsC,GAAG7C,qBAAqB,CAAC8C,YAAY,CAC7EzB,MAAM,EACNF,KAAK,CACR;EACD,OAAO0B,aAAa,CAACE,SAAS,CAACC,wBAAwB;AAC3D"} \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/check-schema.js b/dist/es/plugins/dev-mode/check-schema.js index be8ba010b45..f060e0784fb 100644 --- a/dist/es/plugins/dev-mode/check-schema.js +++ b/dist/es/plugins/dev-mode/check-schema.js @@ -6,7 +6,7 @@ import objectPath from 'object-path'; import { newRxError } from '../../rx-error'; import { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper'; -import { flattenObject, isMaybeReadonlyArray, trimDots } from '../../util'; +import { flattenObject, isMaybeReadonlyArray, trimDots } from '../../plugins/utils'; import { rxDocumentProperties } from './entity-properties'; /** diff --git a/dist/es/plugins/dev-mode/check-schema.js.map b/dist/es/plugins/dev-mode/check-schema.js.map index ae622aca9a4..54e4d9a0fb5 100644 --- a/dist/es/plugins/dev-mode/check-schema.js.map +++ b/dist/es/plugins/dev-mode/check-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"check-schema.js","names":["objectPath","newRxError","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","flattenObject","isMaybeReadonlyArray","trimDots","rxDocumentProperties","checkFieldNameRegex","fieldName","includes","regexStr","regex","RegExp","match","validateFieldsDeep","rxJsonSchema","primaryPath","primaryKey","checkField","schemaObj","path","Array","isArray","hasOwnProperty","type","required","length","items","isNested","split","primary","charAt","traverse","currentObj","currentPath","Object","keys","forEach","attributeName","properties","nextPath","checkPrimaryKey","jsonSchema","schema","validatePrimarySchemaPart","schemaPart","args","key","compositePrimaryKey","keySchemaPart","fields","field","primaryPathSchemaPart","maxLength","getSchemaPropertyRealPath","shortPath","pathParts","realPath","i","concat","checkSchema","_rev","version","value","indexes","unique","encrypted","index","indexAsArray","multipleOf","maximum","minimum","parentPath","lastPathPart","partParts","pop","join","parentSchemaPart","map","filter","elem","pos","arr","indexOf","get","replace","reduce","indexPaths","currentIndex","push","indexPath","propPath"],"sources":["../../../../src/plugins/dev-mode/check-schema.ts"],"sourcesContent":["/**\n * does additional checks over the schema-json\n * to ensure nothing is broken or not supported\n */\n\nimport objectPath from 'object-path';\nimport {\n newRxError\n} from '../../rx-error';\nimport { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper';\nimport type {\n CompositePrimaryKey,\n JsonSchema,\n JsonSchemaTypes,\n RxJsonSchema,\n TopLevelProperty\n} from '../../types';\nimport {\n flattenObject, isMaybeReadonlyArray,\n trimDots\n} from '../../util';\nimport { rxDocumentProperties } from './entity-properties';\n\n/**\n * checks if the fieldname is allowed\n * this makes sure that the fieldnames can be transformed into javascript-vars\n * and does not conquer the observe$ and populate_ fields\n * @throws {Error}\n */\nexport function checkFieldNameRegex(fieldName: string) {\n if (fieldName === '_deleted') {\n return;\n }\n\n if (['properties', 'language'].includes(fieldName)) {\n throw newRxError('SC23', {\n fieldName\n });\n }\n\n const regexStr = '^[a-zA-Z](?:[[a-zA-Z0-9_]*]?[a-zA-Z0-9])?$';\n const regex = new RegExp(regexStr);\n if (\n /**\n * It must be allowed to set _id as primaryKey.\n * This makes it sometimes easier to work with RxDB+CouchDB\n * @link https://github.com/pubkey/rxdb/issues/681\n */\n fieldName !== '_id' &&\n !fieldName.match(regex)\n ) {\n throw newRxError('SC1', {\n regex: regexStr,\n fieldName\n });\n }\n}\n\n/**\n * validate that all schema-related things are ok\n */\nexport function validateFieldsDeep(rxJsonSchema: RxJsonSchema): true {\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function checkField(\n fieldName: string,\n schemaObj: any,\n path: string\n ) {\n if (\n typeof fieldName === 'string' &&\n typeof schemaObj === 'object' &&\n !Array.isArray(schemaObj)\n ) checkFieldNameRegex(fieldName);\n\n // 'item' only allowed it type=='array'\n if (schemaObj.hasOwnProperty('item') && schemaObj.type !== 'array') {\n throw newRxError('SC2', {\n fieldName\n });\n }\n\n /**\n * required fields cannot be set via 'required: true',\n * but must be set via required: []\n */\n if (schemaObj.hasOwnProperty('required') && typeof schemaObj.required === 'boolean') {\n throw newRxError('SC24', {\n fieldName\n });\n }\n\n\n // if ref given, must be type=='string', type=='array' with string-items or type==['string','null']\n if (schemaObj.hasOwnProperty('ref')) {\n if (Array.isArray(schemaObj.type)) {\n if (schemaObj.type.length > 2 || !schemaObj.type.includes('string') || !schemaObj.type.includes('null')) {\n throw newRxError('SC4', {\n fieldName\n });\n }\n } else {\n switch (schemaObj.type) {\n case 'string':\n break;\n case 'array':\n if (!schemaObj.items || !schemaObj.items.type || schemaObj.items.type !== 'string') {\n throw newRxError('SC3', {\n fieldName\n });\n }\n break;\n default:\n throw newRxError('SC4', {\n fieldName\n });\n }\n }\n }\n\n const isNested = path.split('.').length >= 2;\n\n // nested only\n if (isNested) {\n if (schemaObj.primary) {\n throw newRxError('SC6', {\n path,\n primary: schemaObj.primary\n });\n }\n\n if (schemaObj.default) {\n throw newRxError('SC7', {\n path\n });\n }\n }\n\n // first level\n if (!isNested) {\n\n // if _id is used, it must be primaryKey\n if (\n fieldName === '_id' &&\n primaryPath !== '_id'\n ) {\n throw newRxError('COL2', {\n fieldName\n });\n }\n\n // check underscore fields\n if (fieldName.charAt(0) === '_') {\n if (\n // exceptional allow underscore on these fields.\n fieldName === '_id' ||\n fieldName === '_deleted'\n ) {\n return;\n }\n throw newRxError('SC8', {\n fieldName\n });\n }\n }\n }\n\n function traverse(currentObj: any, currentPath: any) {\n if (!currentObj || typeof currentObj !== 'object') return;\n Object.keys(currentObj).forEach(attributeName => {\n const schemaObj = currentObj[attributeName];\n if (!currentObj.properties && schemaObj && typeof schemaObj === 'object') {\n checkField(\n attributeName,\n schemaObj,\n currentPath\n );\n }\n let nextPath = currentPath;\n if (attributeName !== 'properties') nextPath = nextPath + '.' + attributeName;\n traverse(schemaObj, nextPath);\n });\n }\n traverse(rxJsonSchema, '');\n return true;\n}\n\nexport function checkPrimaryKey(\n jsonSchema: RxJsonSchema\n) {\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', { schema: jsonSchema });\n }\n\n\n\n function validatePrimarySchemaPart(\n schemaPart: JsonSchema | TopLevelProperty\n ) {\n if (!schemaPart) {\n throw newRxError('SC33', { schema: jsonSchema });\n }\n\n const type: string = schemaPart.type as any;\n if (\n !type ||\n !['string', 'number', 'integer'].includes(type)\n ) {\n throw newRxError('SC32', { schema: jsonSchema, args: { schemaPart } });\n }\n }\n\n if (typeof jsonSchema.primaryKey === 'string') {\n const key = jsonSchema.primaryKey;\n const schemaPart = jsonSchema.properties[key];\n validatePrimarySchemaPart(schemaPart);\n } else {\n const compositePrimaryKey: CompositePrimaryKey = jsonSchema.primaryKey as any;\n\n const keySchemaPart = getSchemaByObjectPath(jsonSchema, compositePrimaryKey.key);\n validatePrimarySchemaPart(keySchemaPart);\n\n compositePrimaryKey.fields.forEach(field => {\n const schemaPart = getSchemaByObjectPath(jsonSchema, field);\n validatePrimarySchemaPart(schemaPart);\n });\n }\n\n\n /**\n * The primary key must have a maxLength set\n * which is required by some RxStorage implementations\n * to ensure we can craft custom index strings.\n */\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n const primaryPathSchemaPart = jsonSchema.properties[primaryPath];\n if (!primaryPathSchemaPart.maxLength) {\n throw newRxError('SC39', { schema: jsonSchema, args: { primaryPathSchemaPart } });\n }\n}\n\n/**\n * computes real path of the object path in the collection schema\n */\nfunction getSchemaPropertyRealPath(shortPath: string) {\n const pathParts = shortPath.split('.');\n let realPath = '';\n for (let i = 0; i < pathParts.length; i += 1) {\n if (pathParts[i] !== '[]') {\n realPath = realPath.concat('.properties.'.concat(pathParts[i]));\n } else {\n realPath = realPath.concat('.items');\n }\n }\n return trimDots(realPath);\n}\n\n/**\n * does the checking\n * @throws {Error} if something is not ok\n */\nexport function checkSchema(jsonSchema: RxJsonSchema) {\n\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', {\n schema: jsonSchema\n });\n }\n\n if (!jsonSchema.hasOwnProperty('properties')) {\n throw newRxError('SC29', {\n schema: jsonSchema\n });\n }\n\n // _rev MUST NOT exist, it is added by RxDB\n if (jsonSchema.properties._rev) {\n throw newRxError('SC10', {\n schema: jsonSchema\n });\n }\n\n // check version\n if (!jsonSchema.hasOwnProperty('version') ||\n typeof jsonSchema.version !== 'number' ||\n jsonSchema.version < 0\n ) {\n throw newRxError('SC11', {\n version: jsonSchema.version\n });\n }\n\n validateFieldsDeep(jsonSchema);\n checkPrimaryKey(jsonSchema);\n\n Object.keys(jsonSchema.properties).forEach(key => {\n const value: any = jsonSchema.properties[key];\n // check primary\n if (key === jsonSchema.primaryKey) {\n if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) {\n throw newRxError('SC13', {\n value,\n schema: jsonSchema\n });\n }\n if (value.unique) {\n throw newRxError('SC14', {\n value,\n schema: jsonSchema\n });\n }\n if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) {\n throw newRxError('SC15', {\n value,\n schema: jsonSchema\n });\n }\n if (value.type !== 'string') {\n throw newRxError('SC16', {\n value,\n schema: jsonSchema\n });\n }\n }\n\n // check if RxDocument-property\n if (rxDocumentProperties().includes(key)) {\n throw newRxError('SC17', {\n key,\n schema: jsonSchema\n });\n }\n });\n\n // check format of jsonSchema.indexes\n if (jsonSchema.indexes) {\n // should be an array\n if (!isMaybeReadonlyArray(jsonSchema.indexes)) {\n throw newRxError('SC18', {\n indexes: jsonSchema.indexes,\n schema: jsonSchema\n });\n }\n\n jsonSchema.indexes.forEach(index => {\n // should contain strings or array of strings\n if (!(typeof index === 'string' || Array.isArray(index))) {\n throw newRxError('SC19', { index, schema: jsonSchema });\n }\n // if is a compound index it must contain strings\n if (Array.isArray(index)) {\n for (let i = 0; i < index.length; i += 1) {\n if (typeof index[i] !== 'string') {\n throw newRxError('SC20', { index, schema: jsonSchema });\n }\n }\n }\n\n /**\n * To be able to craft custom indexable string with compound fields,\n * we need to know the maximum fieldlength of the fields values\n * when they are transformed to strings.\n * Therefore we need to enforce some properties inside of the schema.\n */\n const indexAsArray = isMaybeReadonlyArray(index) ? index : [index];\n indexAsArray.forEach(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n jsonSchema,\n fieldName\n );\n\n\n const type: JsonSchemaTypes = schemaPart.type as any;\n switch (type) {\n case 'string':\n const maxLength = schemaPart.maxLength;\n if (!maxLength) {\n throw newRxError('SC34', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'number':\n case 'integer':\n const multipleOf = schemaPart.multipleOf;\n if (!multipleOf) {\n throw newRxError('SC35', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n const maximum = schemaPart.maximum;\n const minimum = schemaPart.minimum;\n if (\n typeof maximum === 'undefined' ||\n typeof minimum === 'undefined'\n ) {\n throw newRxError('SC37', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'boolean':\n /**\n * If a boolean field is used as an index,\n * it must be required.\n */\n let parentPath = '';\n let lastPathPart = fieldName;\n if (fieldName.includes('.')) {\n const partParts = fieldName.split('.');\n lastPathPart = partParts.pop();\n parentPath = partParts.join('.');\n }\n const parentSchemaPart = parentPath === '' ? jsonSchema : getSchemaByObjectPath(\n jsonSchema,\n parentPath\n );\n\n if (\n !parentSchemaPart.required ||\n !parentSchemaPart.required.includes(lastPathPart)\n ) {\n throw newRxError('SC38', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n\n default:\n throw newRxError('SC36', {\n fieldName,\n type: schemaPart.type as any,\n schema: jsonSchema,\n });\n }\n });\n\n });\n }\n\n // remove backward-compatibility for index: true\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => { // check if this path defines an index\n const value = objectPath.get(jsonSchema, key);\n return !!value.index;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC26', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* check types of the indexes */\n (jsonSchema.indexes || [])\n .reduce((indexPaths: string[], currentIndex) => {\n if (isMaybeReadonlyArray(currentIndex)) {\n indexPaths.concat(currentIndex);\n } else {\n indexPaths.push(currentIndex);\n }\n return indexPaths;\n }, [])\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // from now on working only with unique indexes\n .map(indexPath => {\n const realPath = getSchemaPropertyRealPath(indexPath); // real path in the collection schema\n const schemaObj = objectPath.get(jsonSchema, realPath); // get the schema of the indexed property\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC21', {\n index: indexPath,\n schema: jsonSchema\n });\n }\n return { indexPath, schemaObj };\n })\n .filter(index =>\n index.schemaObj.type !== 'string' &&\n index.schemaObj.type !== 'integer' &&\n index.schemaObj.type !== 'number' &&\n index.schemaObj.type !== 'boolean'\n )\n .forEach(index => {\n throw newRxError('SC22', {\n key: index.indexPath,\n type: index.schemaObj.type,\n schema: jsonSchema\n });\n });\n\n\n /**\n * TODO\n * in 9.0.0 we changed the way encrypted fields are defined\n * This check ensures people do not oversee the breaking change\n * Remove this check in the future\n */\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '' && key !== 'attachments')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => {\n // check if this path defines an encrypted field\n const value = objectPath.get(jsonSchema, key);\n return !!value.encrypted;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC27', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* ensure encrypted fields exist in the schema */\n if (jsonSchema.encrypted) {\n jsonSchema.encrypted\n .forEach(propPath => {\n // real path in the collection schema\n const realPath = getSchemaPropertyRealPath(propPath);\n // get the schema of the indexed property\n const schemaObj = objectPath.get(jsonSchema, realPath);\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC28', {\n field: propPath,\n schema: jsonSchema\n });\n }\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAOA,UAAU,MAAM,aAAa;AACpC,SACIC,UAAU,QACP,gBAAgB;AACvB,SAASC,2BAA2B,EAAEC,qBAAqB,QAAQ,wBAAwB;AAQ3F,SACIC,aAAa,EAAEC,oBAAoB,EACnCC,QAAQ,QACL,YAAY;AACnB,SAASC,oBAAoB,QAAQ,qBAAqB;;AAE1D;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmB,CAACC,SAAiB,EAAE;EACnD,IAAIA,SAAS,KAAK,UAAU,EAAE;IAC1B;EACJ;EAEA,IAAI,CAAC,YAAY,EAAE,UAAU,CAAC,CAACC,QAAQ,CAACD,SAAS,CAAC,EAAE;IAChD,MAAMR,UAAU,CAAC,MAAM,EAAE;MACrBQ,SAAS,EAATA;IACJ,CAAC,CAAC;EACN;EAEA,IAAME,QAAQ,GAAG,4CAA4C;EAC7D,IAAMC,KAAK,GAAG,IAAIC,MAAM,CAACF,QAAQ,CAAC;EAClC;EACI;AACR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AAE,EAAE,CAAC,CAAC,CAAC;IACtCtC,GAAG,GAAGA,GAAG,CAACsC,OAAO,CAAC,iBAAiB,EAAE,GAAG,CAAC,CAAC,CAAC;IAC3C,MAAMrF,UAAU,CAAC,MAAM,EAAE;MACrBmE,KAAK,EAAE9D,QAAQ,CAAC0C,GAAG,CAAC;MACpBJ,MAAM,EAAED;IACZ,CAAC,CAAC;EACN,CAAC,CAAC;;EAEN;EACA,IAAIA,UAAU,CAACwB,SAAS,EAAE;IACtBxB,UAAU,CAACwB,SAAS,CACf7B,OAAO,CAAC,UAAAsD,QAAQ,EAAI;MACjB;MACA,IAAMlC,QAAQ,GAAGH,yBAAyB,CAACqC,QAAQ,CAAC;MACpD;MACA,IAAMxE,SAAS,GAAGpB,UAAU,CAACqF,GAAG,CAAC1C,UAAU,EAAEe,QAAQ,CAAC;MACtD,IAAI,CAACtC,SAAS,IAAI,OAAOA,SAAS,KAAK,QAAQ,EAAE;QAC7C,MAAMnB,UAAU,CAAC,MAAM,EAAE;UACrBmD,KAAK,EAAEwC,QAAQ;UACfhD,MAAM,EAAED;QACZ,CAAC,CAAC;MACN;IACJ,CAAC,CAAC;EACV;AACJ"} \ No newline at end of file +{"version":3,"file":"check-schema.js","names":["objectPath","newRxError","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","flattenObject","isMaybeReadonlyArray","trimDots","rxDocumentProperties","checkFieldNameRegex","fieldName","includes","regexStr","regex","RegExp","match","validateFieldsDeep","rxJsonSchema","primaryPath","primaryKey","checkField","schemaObj","path","Array","isArray","hasOwnProperty","type","required","length","items","isNested","split","primary","charAt","traverse","currentObj","currentPath","Object","keys","forEach","attributeName","properties","nextPath","checkPrimaryKey","jsonSchema","schema","validatePrimarySchemaPart","schemaPart","args","key","compositePrimaryKey","keySchemaPart","fields","field","primaryPathSchemaPart","maxLength","getSchemaPropertyRealPath","shortPath","pathParts","realPath","i","concat","checkSchema","_rev","version","value","indexes","unique","encrypted","index","indexAsArray","multipleOf","maximum","minimum","parentPath","lastPathPart","partParts","pop","join","parentSchemaPart","map","filter","elem","pos","arr","indexOf","get","replace","reduce","indexPaths","currentIndex","push","indexPath","propPath"],"sources":["../../../../src/plugins/dev-mode/check-schema.ts"],"sourcesContent":["/**\n * does additional checks over the schema-json\n * to ensure nothing is broken or not supported\n */\n\nimport objectPath from 'object-path';\nimport {\n newRxError\n} from '../../rx-error';\nimport { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper';\nimport type {\n CompositePrimaryKey,\n JsonSchema,\n JsonSchemaTypes,\n RxJsonSchema,\n TopLevelProperty\n} from '../../types';\nimport {\n flattenObject, isMaybeReadonlyArray,\n trimDots\n} from '../../plugins/utils';\nimport { rxDocumentProperties } from './entity-properties';\n\n/**\n * checks if the fieldname is allowed\n * this makes sure that the fieldnames can be transformed into javascript-vars\n * and does not conquer the observe$ and populate_ fields\n * @throws {Error}\n */\nexport function checkFieldNameRegex(fieldName: string) {\n if (fieldName === '_deleted') {\n return;\n }\n\n if (['properties', 'language'].includes(fieldName)) {\n throw newRxError('SC23', {\n fieldName\n });\n }\n\n const regexStr = '^[a-zA-Z](?:[[a-zA-Z0-9_]*]?[a-zA-Z0-9])?$';\n const regex = new RegExp(regexStr);\n if (\n /**\n * It must be allowed to set _id as primaryKey.\n * This makes it sometimes easier to work with RxDB+CouchDB\n * @link https://github.com/pubkey/rxdb/issues/681\n */\n fieldName !== '_id' &&\n !fieldName.match(regex)\n ) {\n throw newRxError('SC1', {\n regex: regexStr,\n fieldName\n });\n }\n}\n\n/**\n * validate that all schema-related things are ok\n */\nexport function validateFieldsDeep(rxJsonSchema: RxJsonSchema): true {\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function checkField(\n fieldName: string,\n schemaObj: any,\n path: string\n ) {\n if (\n typeof fieldName === 'string' &&\n typeof schemaObj === 'object' &&\n !Array.isArray(schemaObj)\n ) checkFieldNameRegex(fieldName);\n\n // 'item' only allowed it type=='array'\n if (schemaObj.hasOwnProperty('item') && schemaObj.type !== 'array') {\n throw newRxError('SC2', {\n fieldName\n });\n }\n\n /**\n * required fields cannot be set via 'required: true',\n * but must be set via required: []\n */\n if (schemaObj.hasOwnProperty('required') && typeof schemaObj.required === 'boolean') {\n throw newRxError('SC24', {\n fieldName\n });\n }\n\n\n // if ref given, must be type=='string', type=='array' with string-items or type==['string','null']\n if (schemaObj.hasOwnProperty('ref')) {\n if (Array.isArray(schemaObj.type)) {\n if (schemaObj.type.length > 2 || !schemaObj.type.includes('string') || !schemaObj.type.includes('null')) {\n throw newRxError('SC4', {\n fieldName\n });\n }\n } else {\n switch (schemaObj.type) {\n case 'string':\n break;\n case 'array':\n if (!schemaObj.items || !schemaObj.items.type || schemaObj.items.type !== 'string') {\n throw newRxError('SC3', {\n fieldName\n });\n }\n break;\n default:\n throw newRxError('SC4', {\n fieldName\n });\n }\n }\n }\n\n const isNested = path.split('.').length >= 2;\n\n // nested only\n if (isNested) {\n if (schemaObj.primary) {\n throw newRxError('SC6', {\n path,\n primary: schemaObj.primary\n });\n }\n\n if (schemaObj.default) {\n throw newRxError('SC7', {\n path\n });\n }\n }\n\n // first level\n if (!isNested) {\n\n // if _id is used, it must be primaryKey\n if (\n fieldName === '_id' &&\n primaryPath !== '_id'\n ) {\n throw newRxError('COL2', {\n fieldName\n });\n }\n\n // check underscore fields\n if (fieldName.charAt(0) === '_') {\n if (\n // exceptional allow underscore on these fields.\n fieldName === '_id' ||\n fieldName === '_deleted'\n ) {\n return;\n }\n throw newRxError('SC8', {\n fieldName\n });\n }\n }\n }\n\n function traverse(currentObj: any, currentPath: any) {\n if (!currentObj || typeof currentObj !== 'object') return;\n Object.keys(currentObj).forEach(attributeName => {\n const schemaObj = currentObj[attributeName];\n if (!currentObj.properties && schemaObj && typeof schemaObj === 'object') {\n checkField(\n attributeName,\n schemaObj,\n currentPath\n );\n }\n let nextPath = currentPath;\n if (attributeName !== 'properties') nextPath = nextPath + '.' + attributeName;\n traverse(schemaObj, nextPath);\n });\n }\n traverse(rxJsonSchema, '');\n return true;\n}\n\nexport function checkPrimaryKey(\n jsonSchema: RxJsonSchema\n) {\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', { schema: jsonSchema });\n }\n\n\n\n function validatePrimarySchemaPart(\n schemaPart: JsonSchema | TopLevelProperty\n ) {\n if (!schemaPart) {\n throw newRxError('SC33', { schema: jsonSchema });\n }\n\n const type: string = schemaPart.type as any;\n if (\n !type ||\n !['string', 'number', 'integer'].includes(type)\n ) {\n throw newRxError('SC32', { schema: jsonSchema, args: { schemaPart } });\n }\n }\n\n if (typeof jsonSchema.primaryKey === 'string') {\n const key = jsonSchema.primaryKey;\n const schemaPart = jsonSchema.properties[key];\n validatePrimarySchemaPart(schemaPart);\n } else {\n const compositePrimaryKey: CompositePrimaryKey = jsonSchema.primaryKey as any;\n\n const keySchemaPart = getSchemaByObjectPath(jsonSchema, compositePrimaryKey.key);\n validatePrimarySchemaPart(keySchemaPart);\n\n compositePrimaryKey.fields.forEach(field => {\n const schemaPart = getSchemaByObjectPath(jsonSchema, field);\n validatePrimarySchemaPart(schemaPart);\n });\n }\n\n\n /**\n * The primary key must have a maxLength set\n * which is required by some RxStorage implementations\n * to ensure we can craft custom index strings.\n */\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n const primaryPathSchemaPart = jsonSchema.properties[primaryPath];\n if (!primaryPathSchemaPart.maxLength) {\n throw newRxError('SC39', { schema: jsonSchema, args: { primaryPathSchemaPart } });\n }\n}\n\n/**\n * computes real path of the object path in the collection schema\n */\nfunction getSchemaPropertyRealPath(shortPath: string) {\n const pathParts = shortPath.split('.');\n let realPath = '';\n for (let i = 0; i < pathParts.length; i += 1) {\n if (pathParts[i] !== '[]') {\n realPath = realPath.concat('.properties.'.concat(pathParts[i]));\n } else {\n realPath = realPath.concat('.items');\n }\n }\n return trimDots(realPath);\n}\n\n/**\n * does the checking\n * @throws {Error} if something is not ok\n */\nexport function checkSchema(jsonSchema: RxJsonSchema) {\n\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', {\n schema: jsonSchema\n });\n }\n\n if (!jsonSchema.hasOwnProperty('properties')) {\n throw newRxError('SC29', {\n schema: jsonSchema\n });\n }\n\n // _rev MUST NOT exist, it is added by RxDB\n if (jsonSchema.properties._rev) {\n throw newRxError('SC10', {\n schema: jsonSchema\n });\n }\n\n // check version\n if (!jsonSchema.hasOwnProperty('version') ||\n typeof jsonSchema.version !== 'number' ||\n jsonSchema.version < 0\n ) {\n throw newRxError('SC11', {\n version: jsonSchema.version\n });\n }\n\n validateFieldsDeep(jsonSchema);\n checkPrimaryKey(jsonSchema);\n\n Object.keys(jsonSchema.properties).forEach(key => {\n const value: any = jsonSchema.properties[key];\n // check primary\n if (key === jsonSchema.primaryKey) {\n if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) {\n throw newRxError('SC13', {\n value,\n schema: jsonSchema\n });\n }\n if (value.unique) {\n throw newRxError('SC14', {\n value,\n schema: jsonSchema\n });\n }\n if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) {\n throw newRxError('SC15', {\n value,\n schema: jsonSchema\n });\n }\n if (value.type !== 'string') {\n throw newRxError('SC16', {\n value,\n schema: jsonSchema\n });\n }\n }\n\n // check if RxDocument-property\n if (rxDocumentProperties().includes(key)) {\n throw newRxError('SC17', {\n key,\n schema: jsonSchema\n });\n }\n });\n\n // check format of jsonSchema.indexes\n if (jsonSchema.indexes) {\n // should be an array\n if (!isMaybeReadonlyArray(jsonSchema.indexes)) {\n throw newRxError('SC18', {\n indexes: jsonSchema.indexes,\n schema: jsonSchema\n });\n }\n\n jsonSchema.indexes.forEach(index => {\n // should contain strings or array of strings\n if (!(typeof index === 'string' || Array.isArray(index))) {\n throw newRxError('SC19', { index, schema: jsonSchema });\n }\n // if is a compound index it must contain strings\n if (Array.isArray(index)) {\n for (let i = 0; i < index.length; i += 1) {\n if (typeof index[i] !== 'string') {\n throw newRxError('SC20', { index, schema: jsonSchema });\n }\n }\n }\n\n /**\n * To be able to craft custom indexable string with compound fields,\n * we need to know the maximum fieldlength of the fields values\n * when they are transformed to strings.\n * Therefore we need to enforce some properties inside of the schema.\n */\n const indexAsArray = isMaybeReadonlyArray(index) ? index : [index];\n indexAsArray.forEach(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n jsonSchema,\n fieldName\n );\n\n\n const type: JsonSchemaTypes = schemaPart.type as any;\n switch (type) {\n case 'string':\n const maxLength = schemaPart.maxLength;\n if (!maxLength) {\n throw newRxError('SC34', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'number':\n case 'integer':\n const multipleOf = schemaPart.multipleOf;\n if (!multipleOf) {\n throw newRxError('SC35', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n const maximum = schemaPart.maximum;\n const minimum = schemaPart.minimum;\n if (\n typeof maximum === 'undefined' ||\n typeof minimum === 'undefined'\n ) {\n throw newRxError('SC37', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'boolean':\n /**\n * If a boolean field is used as an index,\n * it must be required.\n */\n let parentPath = '';\n let lastPathPart = fieldName;\n if (fieldName.includes('.')) {\n const partParts = fieldName.split('.');\n lastPathPart = partParts.pop();\n parentPath = partParts.join('.');\n }\n const parentSchemaPart = parentPath === '' ? jsonSchema : getSchemaByObjectPath(\n jsonSchema,\n parentPath\n );\n\n if (\n !parentSchemaPart.required ||\n !parentSchemaPart.required.includes(lastPathPart)\n ) {\n throw newRxError('SC38', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n\n default:\n throw newRxError('SC36', {\n fieldName,\n type: schemaPart.type as any,\n schema: jsonSchema,\n });\n }\n });\n\n });\n }\n\n // remove backward-compatibility for index: true\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => { // check if this path defines an index\n const value = objectPath.get(jsonSchema, key);\n return !!value.index;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC26', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* check types of the indexes */\n (jsonSchema.indexes || [])\n .reduce((indexPaths: string[], currentIndex) => {\n if (isMaybeReadonlyArray(currentIndex)) {\n indexPaths.concat(currentIndex);\n } else {\n indexPaths.push(currentIndex);\n }\n return indexPaths;\n }, [])\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // from now on working only with unique indexes\n .map(indexPath => {\n const realPath = getSchemaPropertyRealPath(indexPath); // real path in the collection schema\n const schemaObj = objectPath.get(jsonSchema, realPath); // get the schema of the indexed property\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC21', {\n index: indexPath,\n schema: jsonSchema\n });\n }\n return { indexPath, schemaObj };\n })\n .filter(index =>\n index.schemaObj.type !== 'string' &&\n index.schemaObj.type !== 'integer' &&\n index.schemaObj.type !== 'number' &&\n index.schemaObj.type !== 'boolean'\n )\n .forEach(index => {\n throw newRxError('SC22', {\n key: index.indexPath,\n type: index.schemaObj.type,\n schema: jsonSchema\n });\n });\n\n\n /**\n * TODO\n * in 9.0.0 we changed the way encrypted fields are defined\n * This check ensures people do not oversee the breaking change\n * Remove this check in the future\n */\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '' && key !== 'attachments')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => {\n // check if this path defines an encrypted field\n const value = objectPath.get(jsonSchema, key);\n return !!value.encrypted;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC27', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* ensure encrypted fields exist in the schema */\n if (jsonSchema.encrypted) {\n jsonSchema.encrypted\n .forEach(propPath => {\n // real path in the collection schema\n const realPath = getSchemaPropertyRealPath(propPath);\n // get the schema of the indexed property\n const schemaObj = objectPath.get(jsonSchema, realPath);\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC28', {\n field: propPath,\n schema: jsonSchema\n });\n }\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAOA,UAAU,MAAM,aAAa;AACpC,SACIC,UAAU,QACP,gBAAgB;AACvB,SAASC,2BAA2B,EAAEC,qBAAqB,QAAQ,wBAAwB;AAQ3F,SACIC,aAAa,EAAEC,oBAAoB,EACnCC,QAAQ,QACL,qBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,qBAAqB;;AAE1D;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmB,CAACC,SAAiB,EAAE;EACnD,IAAIA,SAAS,KAAK,UAAU,EAAE;IAC1B;EACJ;EAEA,IAAI,CAAC,YAAY,EAAE,UAAU,CAAC,CAACC,QAAQ,CAACD,SAAS,CAAC,EAAE;IAChD,MAAMR,UAAU,CAAC,MAAM,EAAE;MACrBQ,SAAS,EAATA;IACJ,CAAC,CAAC;EACN;EAEA,IAAME,QAAQ,GAAG,4CAA4C;EAC7D,IAAMC,KAAK,GAAG,IAAIC,MAAM,CAACF,QAAQ,CAAC;EAClC;EACI;AACR;AACA;AACA;AACA;EACQF,SAAS,KAAK,KAAK,IACnB,CAACA,SAAS,CAACK,KAAK,CAACF,KAAK,CAAC,EACzB;IACE,MAAMX,UAAU,CAAC,KAAK,EAAE;MACpBW,KAAK,EAAED,QAAQ;MACfF,SAAS,EAATA;IACJ,CAAC,CAAC;EACN;AACJ;;AAEA;AACA;AACA;AACA,OAAO,SAASM,kBAAkB,CAACC,YAA+B,EAAQ;EAEtE,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AAIA,UAAU,CAACwB,SAAS,EAAE;IACtBxB,UAAU,CAACwB,SAAS,CACf7B,OAAO,CAAC,UAAAsD,QAAQ,EAAI;MACjB;MACA,IAAMlC,QAAQ,GAAGH,yBAAyB,CAACqC,QAAQ,CAAC;MACpD;MACA,IAAMxE,SAAS,GAAGpB,UAAU,CAACqF,GAAG,CAAC1C,UAAU,EAAEe,QAAQ,CAAC;MACtD,IAAI,CAACtC,SAAS,IAAI,OAAOA,SAAS,KAAK,QAAQ,EAAE;QAC7C,MAAMnB,UAAU,CAAC,MAAM,EAAE;UACrBmD,KAAK,EAAEwC,QAAQ;UACfhD,MAAM,EAAED;QACZ,CAAC,CAAC;MACN;IACJ,CAAC,CAAC;EACV;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/error-messages.js b/dist/es/plugins/dev-mode/error-messages.js index f587903cf0d..cd0f54cc3c8 100644 --- a/dist/es/plugins/dev-mode/error-messages.js +++ b/dist/es/plugins/dev-mode/error-messages.js @@ -13,8 +13,8 @@ export var ERROR_MESSAGES = { UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage', UT6: 'schema contains encrypted fields but no encryption handler is used in the storage', // plugins - PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()', - PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', + PL1: 'Given plugin is not RxDB plugin.', + // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object', // pouch-db.js // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2', @@ -55,14 +55,15 @@ export var ERROR_MESSAGES = { DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given', DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\n' + 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional', - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\'pouchdb-adapter-[adaptername]\'));', - DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\'pouchdb-adapter-leveldb\'));', + // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\'pouchdb-adapter-[adaptername]\'));', + // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\'pouchdb-adapter-leveldb\'));', DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash', + DB12: 'RxDatabase.addCollections(): could not write to internal store', // rx-collection COL1: 'RxDocument.insert() You cannot insert an existing document', COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey', COL3: 'RxCollection.upsert() does not work without primary', - COL4: 'RxCollection.atomicUpsert() does not work without primary', + COL4: 'RxCollection.incrementalUpsert() does not work without primary', COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)', COL6: 'RxCollection.findOne() needs a queryObject or string', COL7: 'hook must be a function', @@ -77,7 +78,9 @@ export var ERROR_MESSAGES = { COL16: 'given static method is not a function', COL17: 'RxCollection.ORM: statics-name not allowed', COL18: 'collection-method not allowed because fieldname is in the schema', - COL19: 'Document update conflict. When changing a document you must work on the previous revision', + // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision', + COL20: 'Storage write error', + CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision', // rx-document.js DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed', DOC2: 'cannot observe primary path', @@ -125,8 +128,8 @@ export var ERROR_MESSAGES = { LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.', // plugins/replication.js RC1: 'Replication: already added', - RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection', - RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', + RC2: 'replicateCouchDB() query must be from the same RxCollection', + // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true', RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance', RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.', @@ -179,8 +182,9 @@ export var ERROR_MESSAGES = { VD1: 'Sub-schema not found, does the schemaPath exists in your schema?', VD2: 'object does not match schema', // plugins/in-memory.js - IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', - IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', + // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', + // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', + // plugins/server.js S1: 'You cannot create collections after calling RxDatabase.server()', // plugins/replication-graphql.js @@ -191,7 +195,7 @@ export var ERROR_MESSAGES = { // plugins/crdt/ CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.', - CRDT2: 'RxDocument.atomicUpdate() cannot be used when CRDTs are activated.', + CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.', CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used', // plugins/dexie/ DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index', diff --git a/dist/es/plugins/dev-mode/error-messages.js.map b/dist/es/plugins/dev-mode/error-messages.js.map index 6d486d14ffc..a699b400021 100644 --- a/dist/es/plugins/dev-mode/error-messages.js.map +++ b/dist/es/plugins/dev-mode/error-messages.js.map @@ -1 +1 @@ -{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","PL1","PL2","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB9","DB10","DB11","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL19","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DM1","DM2","DM3","AT1","EN1","EN2","EN3","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC3","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_P2P_PEER","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","VD1","VD2","IM1","IM2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()',\n PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.atomicUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption.js\n EN1: 'password is no string',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection',\n RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_P2P_PEER: 'RxReplication P2P Peer has error',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 insated - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.atomicUpdate() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/dexie/\n DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAGA,OAAO,IAAMA,cAAc,GAAG;EAC1B;EACAC,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EAExF;EACAC,GAAG,EAAE,qFAAqF;EAC1FC,GAAG,EAAE,wEAAwE;EAC7EC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EAEA;EACAC,GAAG,EAAE,2CAA2C;EAChD;EACA;EACAC,GAAG,EAAE,+DAA+D;EACpEC,GAAG,EAAE,wEAAwE;EAC7EC,GAAG,EAAE,iDAAiD;EACtD;EACA;EACAC,GAAG,EAAE,oDAAoD;EACzDC,IAAI,EAAE,uCAAuC;EAC7CC,IAAI,EAAE,sCAAsC;EAC5CC,IAAI,EAAE,8BAA8B;EACpCC,IAAI,EAAE,8DAA8D;EACpEC,IAAI,EAAE,8HAA8H,GAChI,8DAA8D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,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,oEAAoE;EAC3EC,KAAK,EAAE,wGAAwG;EAE/G;EACAC,IAAI,EAAE,oHAAoH;EAE1H;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC"} \ No newline at end of file +{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB11","DB12","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","CONFLICT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DM1","DM2","DM3","AT1","EN1","EN2","EN3","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_P2P_PEER","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption.js\n EN1: 'password is no string',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_P2P_PEER: 'RxReplication P2P Peer has error',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 insated - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/dexie/\n DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAGA,OAAO,IAAMA,cAAc,GAAG;EAC1B;EACAC,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EAExF;EACAC,GAAG,EAAE,kCAAkC;EACvC;EACAC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EAEA;EAC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pDC,IAAI,EAAE,gHAAgH;EACtHC,IAAI,EAAE,kFAAkF;EACxFC,IAAI,EAAE,uDAAuD;EAE7D;EACA;;EAEA;EACAC,GAAG,EAAE,kEAAkE;EACvEC,GAAG,EAAE,8BAA8B;EAEnC;EACA;EACA;;EAEA;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,yEAAyE;EAChFC,KAAK,EAAE,wGAAwG;EAE/G;EACAC,IAAI,EAAE,oHAAoH;EAE1H;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/index.js b/dist/es/plugins/dev-mode/index.js index deca270a56c..77a89a6c45a 100644 --- a/dist/es/plugins/dev-mode/index.js +++ b/dist/es/plugins/dev-mode/index.js @@ -5,7 +5,7 @@ import { checkMigrationStrategies } from './check-migration-strategies'; import { ensureCollectionNameValid, ensureDatabaseNameIsValid } from './unallowed-properties'; import { checkMangoQuery, checkQuery } from './check-query'; import { newRxError } from '../../rx-error'; -import { deepFreeze } from '../../util'; +import { deepFreeze } from '../../plugins/utils'; export * from './check-schema'; export * from './unallowed-properties'; export * from './check-query'; diff --git a/dist/es/plugins/dev-mode/index.js.map b/dist/es/plugins/dev-mode/index.js.map index 118164ee5c9..74b5e913041 100644 --- a/dist/es/plugins/dev-mode/index.js.map +++ b/dist/es/plugins/dev-mode/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ERROR_MESSAGES","checkSchema","checkOrmDocumentMethods","checkOrmMethods","checkMigrationStrategies","ensureCollectionNameValid","ensureDatabaseNameIsValid","checkMangoQuery","checkQuery","newRxError","deepFreeze","deepFreezeWhenDevMode","obj","DEV_MODE_PLUGIN_NAME","RxDBDevModePlugin","name","rxdb","overwritable","isDevMode","tunnelErrorMessage","code","console","error","Error","hooks","preCreateRxSchema","after","preCreateRxDatabase","args","preCreateRxCollection","schema","methods","charAt","preCreateRxQuery","prePrepareQuery","createRxCollection","creator","statics","attachments","migrationStrategies"],"sources":["../../../../src/plugins/dev-mode/index.ts"],"sourcesContent":["import type {\n RxPlugin,\n RxCollectionCreator,\n RxDatabaseCreator,\n RxErrorKey\n} from '../../types';\n\nimport {\n ERROR_MESSAGES\n} from './error-messages';\nimport {\n checkSchema\n} from './check-schema';\nimport {\n checkOrmDocumentMethods,\n checkOrmMethods\n} from './check-orm';\nimport { checkMigrationStrategies } from './check-migration-strategies';\nimport {\n ensureCollectionNameValid,\n ensureDatabaseNameIsValid\n} from './unallowed-properties';\nimport { checkMangoQuery, checkQuery } from './check-query';\nimport { newRxError } from '../../rx-error';\nimport { DeepReadonly } from '../../types/util';\nimport { deepFreeze } from '../../util';\n\nexport * from './check-schema';\nexport * from './unallowed-properties';\nexport * from './check-query';\n\n\n/**\n * Deep freezes and object when in dev-mode.\n * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode.\n * Also we can ensure the readonly state via typescript\n * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n */\nexport function deepFreezeWhenDevMode(obj: T): DeepReadonly {\n // direct return if not suitable for deepFreeze()\n if (\n !obj ||\n typeof obj === 'string' ||\n typeof obj === 'number'\n ) {\n return obj as any;\n }\n\n return deepFreeze(obj) as any;\n}\n\n\nexport const DEV_MODE_PLUGIN_NAME = 'dev-mode';\nexport const RxDBDevModePlugin: RxPlugin = {\n name: DEV_MODE_PLUGIN_NAME,\n rxdb: true,\n overwritable: {\n isDevMode() {\n return true;\n },\n deepFreezeWhenDevMode,\n tunnelErrorMessage(code: RxErrorKey) {\n if (!ERROR_MESSAGES[code]) {\n console.error('RxDB: Error-Code not known: ' + code);\n throw new Error('Error-Code ' + code + ' not known, contact the maintainer');\n }\n return ERROR_MESSAGES[code];\n }\n },\n hooks: {\n preCreateRxSchema: {\n after: checkSchema\n },\n preCreateRxDatabase: {\n after: function (args: RxDatabaseCreator) {\n ensureDatabaseNameIsValid(args);\n }\n },\n preCreateRxCollection: {\n after: function (args: RxCollectionCreator & { name: string; }) {\n ensureCollectionNameValid(args);\n checkOrmDocumentMethods(args.schema as any, args.methods);\n if (args.name.charAt(0) === '_') {\n throw newRxError('DB2', {\n name: args.name\n });\n }\n if (!args.schema) {\n throw newRxError('DB4', {\n name: args.name,\n args\n });\n }\n }\n },\n preCreateRxQuery: {\n after: function (args) {\n checkQuery(args);\n }\n },\n prePrepareQuery: {\n after: (args) => {\n checkMangoQuery(args);\n }\n },\n createRxCollection: {\n after: (args) => {\n // check ORM-methods\n checkOrmMethods(args.creator.statics);\n checkOrmMethods(args.creator.methods);\n checkOrmMethods(args.creator.attachments);\n\n // check migration strategies\n if (args.creator.schema && args.creator.migrationStrategies) {\n checkMigrationStrategies(\n args.creator.schema,\n args.creator.migrationStrategies\n );\n }\n }\n }\n }\n};\n"],"mappings":"AAOA,SACIA,cAAc,QACX,kBAAkB;AACzB,SACIC,WAAW,QACR,gBAAgB;AACvB,SACIC,uBAAuB,EACvBC,eAAe,QACZ,aAAa;AACpB,SAASC,wBAAwB,QAAQ,8BAA8B;AACvE,SACIC,yBAAyB,EACzBC,yBAAyB,QACtB,wBAAwB;AAC/B,SAASC,eAAe,EAAEC,UAAU,QAAQ,eAAe;AAC3D,SAASC,UAAU,QAAQ,gBAAgB;AAE3C,SAASC,UAAU,QAAQ,YAAY;AAEvC,cAAc,gBAAgB;AAC9B,cAAc,wBAAwB;AACtC,cAAc,eAAe;;AAG7B;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqB,CAAIC,GAAM,EAAmB;EAC9D;EACA,IACI,CAACA,GAAG,IACJ,OAAOA,GAAG,KAAK,QAAQ,IACvB,OAAOA,GAAG,KAAK,QAAQ,EACzB;IACE,OAAOA,GAAG;EACd;EAEA,OAAOF,UAAU,CAACE,GAAG,CAAC;AAC1B;AA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MACdP,KAAK,EAAE,eAAUE,IAAI,EAAE;QACnBpB,UAAU,CAACoB,IAAI,CAAC;MACpB;IACJ,CAAC;IACDM,eAAe,EAAE;MACbR,KAAK,EAAE,eAACE,IAAI,EAAK;QACbrB,eAAe,CAACqB,IAAI,CAAC;MACzB;IACJ,CAAC;IACDO,kBAAkB,EAAE;MAChBT,KAAK,EAAE,eAACE,IAAI,EAAK;QACb;QACAzB,eAAe,CAACyB,IAAI,CAACQ,OAAO,CAACC,OAAO,CAAC;QACrClC,eAAe,CAACyB,IAAI,CAACQ,OAAO,CAACL,OAAO,CAAC;QACrC5B,eAAe,CAACyB,IAAI,CAACQ,OAAO,CAACE,WAAW,CAAC;;QAEzC;QACA,IAAIV,IAAI,CAACQ,OAAO,CAACN,MAAM,IAAIF,IAAI,CAACQ,OAAO,CAACG,mBAAmB,EAAE;UACzDnC,wBAAwB,CACpBwB,IAAI,CAACQ,OAAO,CAACN,MAAM,EACnBF,IAAI,CAACQ,OAAO,CAACG,mBAAmB,CACnC;QACL;MACJ;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ERROR_MESSAGES","checkSchema","checkOrmDocumentMethods","checkOrmMethods","checkMigrationStrategies","ensureCollectionNameValid","ensureDatabaseNameIsValid","checkMangoQuery","checkQuery","newRxError","deepFreeze","deepFreezeWhenDevMode","obj","DEV_MODE_PLUGIN_NAME","RxDBDevModePlugin","name","rxdb","overwritable","isDevMode","tunnelErrorMessage","code","console","error","Error","hooks","preCreateRxSchema","after","preCreateRxDatabase","args","preCreateRxCollection","schema","methods","charAt","preCreateRxQuery","prePrepareQuery","createRxCollection","creator","statics","attachments","migrationStrategies"],"sources":["../../../../src/plugins/dev-mode/index.ts"],"sourcesContent":["import type {\n RxPlugin,\n RxCollectionCreator,\n RxDatabaseCreator,\n RxErrorKey\n} from '../../types';\n\nimport {\n ERROR_MESSAGES\n} from './error-messages';\nimport {\n checkSchema\n} from './check-schema';\nimport {\n checkOrmDocumentMethods,\n checkOrmMethods\n} from './check-orm';\nimport { checkMigrationStrategies } from './check-migration-strategies';\nimport {\n ensureCollectionNameValid,\n ensureDatabaseNameIsValid\n} from './unallowed-properties';\nimport { checkMangoQuery, checkQuery } from './check-query';\nimport { newRxError } from '../../rx-error';\nimport { DeepReadonly } from '../../types/util';\nimport { deepFreeze } from '../../plugins/utils';\n\nexport * from './check-schema';\nexport * from './unallowed-properties';\nexport * from './check-query';\n\n\n/**\n * Deep freezes and object when in dev-mode.\n * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode.\n * Also we can ensure the readonly state via typescript\n * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n */\nexport function deepFreezeWhenDevMode(obj: T): DeepReadonly {\n // direct return if not suitable for deepFreeze()\n if (\n !obj ||\n typeof obj === 'string' ||\n typeof obj === 'number'\n ) {\n return obj as any;\n }\n\n return deepFreeze(obj) as any;\n}\n\n\nexport const DEV_MODE_PLUGIN_NAME = 'dev-mode';\nexport const RxDBDevModePlugin: RxPlugin = {\n name: DEV_MODE_PLUGIN_NAME,\n rxdb: true,\n overwritable: {\n isDevMode() {\n return true;\n },\n deepFreezeWhenDevMode,\n tunnelErrorMessage(code: RxErrorKey) {\n if (!ERROR_MESSAGES[code]) {\n console.error('RxDB: Error-Code not known: ' + code);\n throw new Error('Error-Code ' + code + ' not known, contact the maintainer');\n }\n return ERROR_MESSAGES[code];\n }\n },\n hooks: {\n preCreateRxSchema: {\n after: checkSchema\n },\n preCreateRxDatabase: {\n after: function (args: RxDatabaseCreator) {\n ensureDatabaseNameIsValid(args);\n }\n },\n preCreateRxCollection: {\n after: function (args: RxCollectionCreator & { name: string; }) {\n ensureCollectionNameValid(args);\n checkOrmDocumentMethods(args.schema as any, args.methods);\n if (args.name.charAt(0) === '_') {\n throw newRxError('DB2', {\n name: args.name\n });\n }\n if (!args.schema) {\n throw newRxError('DB4', {\n name: args.name,\n args\n });\n }\n }\n },\n preCreateRxQuery: {\n after: function (args) {\n checkQuery(args);\n }\n },\n prePrepareQuery: {\n after: (args) => {\n checkMangoQuery(args);\n }\n },\n createRxCollection: {\n after: (args) => {\n // check ORM-methods\n checkOrmMethods(args.creator.statics);\n checkOrmMethods(args.creator.methods);\n checkOrmMethods(args.creator.attachments);\n\n // check migration strategies\n if (args.creator.schema && args.creator.migrationStrategies) {\n checkMigrationStrategies(\n args.creator.schema,\n args.creator.migrationStrategies\n );\n }\n }\n }\n }\n};\n"],"mappings":"AAOA,SACIA,cAAc,QACX,kBAAkB;AACzB,SACIC,WAAW,QACR,gBAAgB;AACvB,SACIC,uBAAuB,EACvBC,eAAe,QACZ,aAAa;AACpB,SAASC,wBAAwB,QAAQ,8BAA8B;AACvE,SACIC,yBAAyB,EACzBC,yBAAyB,QACtB,wBAAwB;AAC/B,SAASC,eAAe,EAAEC,UAAU,QAAQ,eAAe;AAC3D,SAASC,UAAU,QAAQ,gBAAgB;AAE3C,SAASC,UAAU,QAAQ,qBAAqB;AAEhD,cAAc,gBAAgB;AAC9B,cAAc,wBAAwB;AACtC,cAAc,eAAe;;AAG7B;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqB,CAAIC,GAAM,EAAmB;EAC9D;EACA,IACI,CAACA,GAAG,IACJ,OAAOA,GAAG,KAAK,QAAQ,IACvB,OAAOA,GAAG,KAAK,QAAQ,EACzB;IACE,OAAOA,GAAG;EACd;EAEA,OAAOF,UAAU,CAACE,GAAG,CAAC;AAC1B;AAGA,OAAO,IAAMC,oBAAoB,GAAG,UAAU;AAC9C,OAAO,IAAMC,iBAA2B,GAAG;EACvCC,IAAI,EAAEF,oBAAoB;EAC1BG,IAAI,EAAE,IAAI;EACVC,YAAY,EAAE;IACVC,SAAS,uBAAG;MACR,OAAO,IAAI;IACf,CAAC;IACDP,qBAAqB,EAArBA,qBAAqB;IACrBQ,kBAAkB,8BAACC,IAAgB,EAAE;MACjC,IAAI,CAACpB,cAAc,CAACoB,IAAI,C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C,OAAO,CAAC;QACrClC,eAAe,CAACyB,IAAI,CAACQ,OAAO,CAACL,OAAO,CAAC;QACrC5B,eAAe,CAACyB,IAAI,CAACQ,OAAO,CAACE,WAAW,CAAC;;QAEzC;QACA,IAAIV,IAAI,CAACQ,OAAO,CAACN,MAAM,IAAIF,IAAI,CAACQ,OAAO,CAACG,mBAAmB,EAAE;UACzDnC,wBAAwB,CACpBwB,IAAI,CAACQ,OAAO,CAACN,MAAM,EACnBF,IAAI,CAACQ,OAAO,CAACG,mBAAmB,CACnC;QACL;MACJ;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/dev-mode/unallowed-properties.js b/dist/es/plugins/dev-mode/unallowed-properties.js index 60cd22e23d1..1a51871eb39 100644 --- a/dist/es/plugins/dev-mode/unallowed-properties.js +++ b/dist/es/plugins/dev-mode/unallowed-properties.js @@ -1,6 +1,6 @@ import { newRxError, newRxTypeError } from '../../rx-error'; import { rxDatabaseProperties } from './entity-properties'; -import { isFolderPath } from '../../util'; +import { isFolderPath } from '../../plugins/utils'; /** * if the name of a collection diff --git a/dist/es/plugins/dev-mode/unallowed-properties.js.map b/dist/es/plugins/dev-mode/unallowed-properties.js.map index c6e510c96c2..9b5ecf467d1 100644 --- a/dist/es/plugins/dev-mode/unallowed-properties.js.map +++ b/dist/es/plugins/dev-mode/unallowed-properties.js.map @@ -1 +1 @@ -{"version":3,"file":"unallowed-properties.js","names":["newRxError","newRxTypeError","rxDatabaseProperties","isFolderPath","ensureCollectionNameValid","args","includes","name","validateDatabaseName","ensureDatabaseNameIsValid","endsWith","validCouchDBStringRegexStr","validCouchDBStringRegex","RegExp","length","match","regex","givenName"],"sources":["../../../../src/plugins/dev-mode/unallowed-properties.ts"],"sourcesContent":["import type { RxCollectionCreator, RxDatabaseCreator } from '../../types';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { rxDatabaseProperties } from './entity-properties';\nimport { isFolderPath } from '../../util';\n\n/**\n * if the name of a collection\n * clashes with a property of RxDatabase,\n * we get problems so this function prohibits this\n */\nexport function ensureCollectionNameValid(\n args: RxCollectionCreator & { name: string; }\n) {\n if (rxDatabaseProperties().includes(args.name)) {\n throw newRxError('DB5', {\n name: args.name\n });\n }\n validateDatabaseName(args.name);\n}\n\nexport function ensureDatabaseNameIsValid(args: RxDatabaseCreator) {\n\n validateDatabaseName(args.name);\n\n /**\n * The server-plugin has problems when a path with and ending slash is given\n * So we do not allow this.\n * @link https://github.com/pubkey/rxdb/issues/2251\n */\n if (isFolderPath(args.name)) {\n if (args.name.endsWith('/') || args.name.endsWith('\\\\')) {\n throw newRxError('DB11', {\n name: args.name,\n });\n }\n }\n}\n\n\n\nconst validCouchDBStringRegexStr = '^[a-z][_$a-z0-9\\\\-]*$';\nconst validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr);\n\n/**\n * Validates that a given string is ok to be used with couchdb-collection-names.\n * We only allow these strings as database- or collection names because it ensures\n * that you later do not get in troubble when you want to use the database together witch couchdb.\n *\n * @link https://docs.couchdb.org/en/stable/api/database/common.html\n * @link https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n * @throws {RxError}\n */\nexport function validateDatabaseName(name: string): true {\n if (\n typeof name !== 'string' ||\n name.length === 0\n ) {\n throw newRxTypeError('UT1', {\n name\n });\n }\n\n\n // do not check, if foldername is given\n if (isFolderPath(name)) {\n return true;\n }\n\n if (!name.match(validCouchDBStringRegex)) {\n throw newRxError('UT2', {\n regex: validCouchDBStringRegexStr,\n givenName: name,\n });\n }\n\n return true;\n}\n"],"mappings":"AACA,SAASA,UAAU,EAAEC,cAAc,QAAQ,gBAAgB;AAC3D,SAASC,oBAAoB,QAAQ,qBAAqB;AAC1D,SAASC,YAAY,QAAQ,YAAY;;AAEzC;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,yBAAyB,CACrCC,IAA6C,EAC/C;EACE,IAAIH,oBAAoB,EAAE,CAACI,QAAQ,CAACD,IAA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js","names":["newRxError","newRxTypeError","rxDatabaseProperties","isFolderPath","ensureCollectionNameValid","args","includes","name","validateDatabaseName","ensureDatabaseNameIsValid","endsWith","validCouchDBStringRegexStr","validCouchDBStringRegex","RegExp","length","match","regex","givenName"],"sources":["../../../../src/plugins/dev-mode/unallowed-properties.ts"],"sourcesContent":["import type { RxCollectionCreator, RxDatabaseCreator } from '../../types';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { rxDatabaseProperties } from './entity-properties';\nimport { isFolderPath } from '../../plugins/utils';\n\n/**\n * if the name of a collection\n * clashes with a property of RxDatabase,\n * we get problems so this function prohibits this\n */\nexport function ensureCollectionNameValid(\n args: RxCollectionCreator & { name: string; }\n) {\n if (rxDatabaseProperties().includes(args.name)) {\n throw newRxError('DB5', {\n name: args.name\n });\n }\n validateDatabaseName(args.name);\n}\n\nexport function ensureDatabaseNameIsValid(args: RxDatabaseCreator) {\n\n validateDatabaseName(args.name);\n\n /**\n * The server-plugin has problems when a path with and ending slash is given\n * So we do not allow this.\n * @link https://github.com/pubkey/rxdb/issues/2251\n */\n if (isFolderPath(args.name)) {\n if (args.name.endsWith('/') || args.name.endsWith('\\\\')) {\n throw newRxError('DB11', {\n name: args.name,\n });\n }\n }\n}\n\n\n\nconst validCouchDBStringRegexStr = '^[a-z][_$a-z0-9\\\\-]*$';\nconst validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr);\n\n/**\n * Validates that a given string is ok to be used with couchdb-collection-names.\n * We only allow these strings as database- or collection names because it ensures\n * that you later do not get in troubble when you want to use the database together witch couchdb.\n *\n * @link https://docs.couchdb.org/en/stable/api/database/common.html\n * @link https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n * @throws {RxError}\n */\nexport function validateDatabaseName(name: string): true {\n if (\n typeof name !== 'string' ||\n name.length === 0\n ) {\n throw newRxTypeError('UT1', {\n name\n });\n }\n\n\n // do not check, if foldername is given\n if (isFolderPath(name)) {\n return true;\n }\n\n if (!name.match(validCouchDBStringRegex)) {\n throw newRxError('UT2', {\n regex: validCouchDBStringRegexStr,\n givenName: name,\n });\n }\n\n return true;\n}\n"],"mappings":"AACA,SAASA,UAAU,EAAEC,cAAc,QAAQ,gBAAgB;AAC3D,SAASC,oBAAoB,QAAQ,qBAAqB;AAC1D,SAASC,YAAY,QAAQ,qBAAqB;;AAElD;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,yBAAyB,CACrCC,IAA6C,EAC/C;EACE,IAAIH,oBAAoB,EAAE,CAACI,QAAQ,CAACD,IAAI,CAACE,IAAI,CAAC,EAAE;IAC5C,MAAMP,UAAU,CAAC,KAAK,EAAE;MACpBO,IAAI,EAAEF,IAAI,CAACE;IACf,CAAC,CAAC;EACN;EACAC,oBAAoB,CAACH,IAAI,CAACE,IAAI,CAAC;AACnC;AAEA,OAAO,SAASE,yBAAyB,CAACJ,IAAiC,EAAE;EAEzEG,oBAAoB,CAACH,IAAI,CAACE,IAAI,CAAC;;EAE/B;AACJ;AACA;AACA;AACA;EACI,IAAIJ,YAAY,CAACE,IAAI,CAACE,IAAI,CAAC,EAAE;IACzB,IAAIF,IAAI,CAACE,IAAI,CAACG,QAAQ,CAAC,GAAG,CAAC,IAAIL,IAAI,CAACE,IAAI,CAACG,QAAQ,CAAC,IAAI,CAAC,EAAE;MACrD,MAAMV,UAAU,CAAC,MAAM,EAAE;QACrBO,IAAI,EAAEF,IAAI,CAACE;MACf,CAAC,CAAC;IACN;EACJ;AACJ;AAIA,IAAMI,0BAA0B,GAAG,uBAAuB;AAC1D,IAAMC,uBAAuB,GAAG,IAAIC,MAAM,CAACF,0BAA0B,CAAC;;AAEtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASH,oBAAoB,CAACD,IAAY,EAAQ;EACrD,IACI,OAAOA,IAAI,KAAK,QAAQ,IACxBA,IAAI,CAACO,MAAM,KAAK,CAAC,EACnB;IACE,MAAMb,cAAc,CAAC,KAAK,EAAE;MACxBM,IAAI,EAAJA;IACJ,CAAC,CAAC;EACN;;EAGA;EACA,IAAIJ,YAAY,CAACI,IAAI,CAAC,EAAE;IACpB,OAAO,IAAI;EACf;EAEA,IAAI,CAACA,IAAI,CAACQ,KAAK,CAACH,uBAAuB,CAAC,EAAE;IACtC,MAAMZ,UAAU,CAAC,KAAK,EAAE;MACpBgB,KAAK,EAAEL,0BAA0B;MACjCM,SAAS,EAAEV;IACf,CAAC,CAAC;EACN;EAEA,OAAO,IAAI;AACf"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/dexie-helper.js.map b/dist/es/plugins/dexie/dexie-helper.js.map deleted file mode 100644 index 1b757c4f261..00000000000 --- a/dist/es/plugins/dexie/dexie-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-helper.js","names":["Dexie","flatClone","newRxError","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","getMingoQuery","getDocsInDb","internals","docIds","state","Promise","all","dexieTable","bulkGet","dexieDeletedTable","nonDeletedDocsInDb","deletedDocsInDb","docsInDb","slice","forEach","doc","idx","closeDexieDb","statePromise","prevCount","REF_COUNT_PER_DEXIE_DB","get","newCount","dexieDb","close","set","DEXIE_DOCS_TABLE_NAME","DEXIE_DELETED_DOCS_TABLE_NAME","DEXIE_CHANGES_TABLE_NAME","RX_STORAGE_NAME_DEXIE","DEXIE_STATE_DB_BY_NAME","Map","getDexieDbWithTables","databaseName","collectionName","settings","schema","primaryPath","primaryKey","dexieDbName","version","useSettings","autoOpen","dexieStoresSettings","getDexieStoreSchema","stores","open","sortDirectionToMingo","direction","getDexieSortComparator","_schema","query","mingoSortObject","sort","sortBlock","key","Object","keys","values","fun","a","b","sorted","find","first","next","ensureNoBooleanIndex","indexes","checkedFields","Set","index","fields","Array","isArray","field","has","add","schemaObj","type","DEXIE_PIPE_SUBSTITUTE","dexieReplaceIfStartsWithPipe","str","split","length","map","part","join","startsWith","withoutFirst","substring","dexieReplaceIfStartsWithPipeRevert","fromStorageToDexie","documentData","row","ret","entries","value","fromDexieToStorage","rxJsonSchema","parts","push","arIndex"],"sources":["../../../../src/plugins/dexie/dexie-helper.ts"],"sourcesContent":["import type {\n DeterministicSortComparator\n} from 'event-reduce-js';\nimport type {\n DexieStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { Dexie } from 'dexie';\nimport { DexieSettings } from '../../types';\nimport { flatClone } from '../../util';\nimport { newRxError } from '../../rx-error';\nimport {\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath\n} from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const DEXIE_DOCS_TABLE_NAME = 'docs';\nexport const DEXIE_DELETED_DOCS_TABLE_NAME = 'deleted-docs';\nexport const DEXIE_CHANGES_TABLE_NAME = 'changes';\n\nexport const RX_STORAGE_NAME_DEXIE = 'dexie';\n\nconst DEXIE_STATE_DB_BY_NAME: Map = new Map();\nconst REF_COUNT_PER_DEXIE_DB: Map = new Map();\nexport function getDexieDbWithTables(\n databaseName: string,\n collectionName: string,\n settings: DexieSettings,\n schema: RxJsonSchema\n): DexieStorageInternals {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const dexieDbName = 'rxdb-dexie-' + databaseName + '--' + schema.version + '--' + collectionName;\n let state = DEXIE_STATE_DB_BY_NAME.get(dexieDbName);\n if (!state) {\n state = (async () => {\n /**\n * IndexedDB was not designed for dynamically adding tables on the fly,\n * so we create one dexie database per RxDB storage instance.\n * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696\n */\n const useSettings = flatClone(settings);\n useSettings.autoOpen = false;\n const dexieDb = new Dexie(dexieDbName, useSettings);\n const dexieStoresSettings = {\n [DEXIE_DOCS_TABLE_NAME]: getDexieStoreSchema(schema),\n [DEXIE_CHANGES_TABLE_NAME]: '++sequence, id',\n /**\n * Instead of adding {deleted: false} to every query we run over the document store,\n * we move deleted documents into a separate store where they can only be queried\n * by primary key.\n * This increases performance because it is way easier for the query planner to select\n * a good index and we also do not have to add the _deleted field to every index.\n *\n * We also need the [_meta.lwt+' + primaryPath + '] index for getChangedDocumentsSince()\n */\n [DEXIE_DELETED_DOCS_TABLE_NAME]: primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']'\n };\n\n dexieDb.version(1).stores(dexieStoresSettings);\n await dexieDb.open();\n return {\n dexieDb,\n dexieTable: (dexieDb as any)[DEXIE_DOCS_TABLE_NAME],\n dexieDeletedTable: (dexieDb as any)[DEXIE_DELETED_DOCS_TABLE_NAME]\n };\n })();\n\n DEXIE_STATE_DB_BY_NAME.set(dexieDbName, state);\n REF_COUNT_PER_DEXIE_DB.set(state, 0);\n }\n\n return state;\n}\n\nexport async function closeDexieDb(statePromise: DexieStorageInternals) {\n const state = await statePromise;\n const prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise);\n const newCount = (prevCount as any) - 1;\n if (newCount === 0) {\n state.dexieDb.close();\n REF_COUNT_PER_DEXIE_DB.delete(statePromise);\n } else {\n REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount);\n }\n}\n\n\nfunction sortDirectionToMingo(direction: 'asc' | 'desc'): 1 | -1 {\n if (direction === 'asc') {\n return 1;\n } else {\n return -1;\n }\n}\n\n/**\n * This function is at dexie-helper\n * because we need it in multiple places.\n */\nexport function getDexieSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n const mingoSortObject: {\n [fieldName: string]: 1 | -1;\n } = {};\n\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n\n query.sort.forEach(sortBlock => {\n const key = Object.keys(sortBlock)[0];\n const direction = Object.values(sortBlock)[0];\n mingoSortObject[key] = sortDirectionToMingo(direction);\n });\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n const sorted = getMingoQuery({}).find([a, b], {}).sort(mingoSortObject);\n const first = sorted.next();\n if (first === a) {\n return -1;\n } else {\n return 1;\n }\n };\n\n return fun;\n}\n\n\nexport function ensureNoBooleanIndex(schema: RxJsonSchema) {\n if (!schema.indexes) {\n return;\n }\n const checkedFields = new Set();\n schema.indexes.forEach(index => {\n const fields = Array.isArray(index) ? index : [];\n fields.forEach(field => {\n if (checkedFields.has(field)) {\n return;\n }\n checkedFields.add(field);\n const schemaObj = getSchemaByObjectPath(schema, field);\n if (schemaObj.type === 'boolean') {\n throw newRxError('DXE1', {\n schema,\n index,\n field\n });\n }\n });\n });\n}\n\n\n\n/**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\nexport const DEXIE_PIPE_SUBSTITUTE = '__';\nexport function dexieReplaceIfStartsWithPipe(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipe(part)).join('.');\n }\n\n if (str.startsWith('|')) {\n const withoutFirst = str.substring(1);\n return DEXIE_PIPE_SUBSTITUTE + withoutFirst;\n } else {\n return str;\n }\n}\n\nexport function dexieReplaceIfStartsWithPipeRevert(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipeRevert(part)).join('.');\n }\n\n if (str.startsWith(DEXIE_PIPE_SUBSTITUTE)) {\n const withoutFirst = str.substring(DEXIE_PIPE_SUBSTITUTE.length);\n return '|' + withoutFirst;\n } else {\n return str;\n }\n}\n\n/**\n * @recursive\n */\nexport function fromStorageToDexie(documentData: RxDocumentData): any {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromStorageToDexie(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object') {\n value = fromStorageToDexie(value);\n }\n ret[dexieReplaceIfStartsWithPipe(key)] = value;\n });\n return ret;\n }\n}\n\nexport function fromDexieToStorage(documentData: any): RxDocumentData {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromDexieToStorage(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object' || Array.isArray(documentData)) {\n value = fromDexieToStorage(value);\n }\n ret[dexieReplaceIfStartsWithPipeRevert(key)] = value;\n });\n return ret;\n }\n}\n\n\n/**\n * Creates a string that can be used to create the dexie store.\n * @link https://dexie.org/docs/API-Reference#quick-reference\n */\nexport function getDexieStoreSchema(\n rxJsonSchema: RxJsonSchema\n): string {\n let parts: string[][] = [];\n\n /**\n * First part must be the primary key\n * @link https://github.com/dexie/Dexie.js/issues/1307#issuecomment-846590912\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n parts.push([primaryKey]);\n\n // add other indexes\n if (rxJsonSchema.indexes) {\n rxJsonSchema.indexes.forEach(index => {\n const arIndex = Array.isArray(index) ? index : [index];\n parts.push(arIndex);\n });\n }\n\n // we also need the _meta.lwt+primaryKey index for the getChangedDocumentsSince() method.\n parts.push(['_meta.lwt', primaryKey]);\n\n /**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\n parts = parts.map(part => {\n return part.map(str => dexieReplaceIfStartsWithPipe(str));\n });\n\n return parts.map(part => {\n if (part.length === 1) {\n return part[0];\n } else {\n return '[' + part.join('+') + ']';\n }\n }).join(', ');\n}\n\n/**\n * Returns all documents in the database.\n * Non-deleted plus deleted ones.\n */\nexport async function getDocsInDb(\n internals: DexieStorageInternals,\n docIds: string[]\n): Promise[]> {\n const state = await internals;\n const [\n nonDeletedDocsInDb,\n deletedDocsInDb\n ] = await Promise.all([\n state.dexieTable.bulkGet(docIds),\n state.dexieDeletedTable.bulkGet(docIds)\n ]);\n const docsInDb = de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;;AAGA;AACA;AACA;AACA;AACA,OAAO,SAASlD,mBAAmB,CAC/BsD,YAA+B,EACzB;EACN,IAAIC,KAAiB,GAAG,EAAE;;EAE1B;AACJ;AACA;AACA;EACI,IAAM7D,UAAU,GAAGxC,2BAA2B,CAACoG,YAAY,CAAC5D,UAAU,CAAC;EACvE6D,KAAK,CAACC,IAAI,CAAC,CAAC9D,UAAU,CAAC,CAAC;;EAExB;EACA,IAAI4D,YAAY,CAAC/B,OAAO,EAAE;IACtB+B,YAAY,CAAC/B,OAAO,CAACrD,OAAO,CAAC,UAAAwD,KAAK,EAAI;MAClC,IAAM+B,OAAO,GAAG7B,KAAK,CAACC,OAAO,CAACH,KAAK,CAAC,GAAGA,KAAK,GAAG,CAACA,KAAK,CAAC;MACtD6B,KAAK,CAACC,IAAI,CAACC,OAAO,CAAC;IACvB,CAAC,CAAC;EACN;;EAEA;EACAF,KAAK,CAACC,IAAI,CAAC,CAAC,WAAW,EAAE9D,UAAU,CAAC,CAAC;;EAErC;AACJ;AACA;AACA;AACA;EACI6D,KAAK,GAAGA,KAAK,CAACf,GAAG,CAAC,UAAAC,IAAI,EAAI;IACtB,OAAOA,IAAI,CAACD,GAAG,CAAC,UAAAH,GAAG;MAAA,OAAID,4BAA4B,CAACC,GAAG,CAAC;IAAA,EAAC;EAC7D,CAAC,CAAC;EAEF,OAAOkB,KAAK,CAACf,GAAG,CAAC,UAAAC,IAAI,EAAI;IACrB,IAAIA,IAAI,CAACF,MAAM,KAAK,CAAC,EAAE;MACnB,OAAOE,IAAI,CAAC,CAAC,CAAC;IAClB,CAAC,MAAM;MACH,OAAO,GAAG,GAAGA,IAAI,CAACC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG;IACrC;EACJ,CAAC,CAAC,CAACA,IAAI,CAAC,IAAI,CAAC;AACjB"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/dexie-query.js b/dist/es/plugins/dexie/dexie-query.js deleted file mode 100644 index 443de84b47f..00000000000 --- a/dist/es/plugins/dexie/dexie-query.js +++ /dev/null @@ -1,179 +0,0 @@ -import { dexieReplaceIfStartsWithPipe, DEXIE_DOCS_TABLE_NAME, fromDexieToStorage } from './dexie-helper'; -import { RxStorageDexieStatics } from './dexie-statics'; -export var dexieCount = function dexieCount(instance, preparedQuery) { - try { - return Promise.resolve(instance.internals).then(function (state) { - var queryPlan = preparedQuery.queryPlan; - var queryPlanFields = queryPlan.index; - var keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); - var count = -1; - return Promise.resolve(state.dexieDb.transaction('r', state.dexieTable, function (dexieTx) { - try { - var tx = dexieTx.idbtrans; - var store = tx.objectStore(DEXIE_DOCS_TABLE_NAME); - var index; - if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { - index = store; - } else { - var indexName; - if (queryPlanFields.length === 1) { - indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]); - } else { - indexName = '[' + queryPlanFields.map(function (field) { - return dexieReplaceIfStartsWithPipe(field); - }).join('+') + ']'; - } - index = store.index(indexName); - } - var request = index.count(keyRange); - return Promise.resolve(new Promise(function (res, rej) { - request.onsuccess = function () { - res(request.result); - }; - request.onerror = function (err) { - return rej(err); - }; - })).then(function (_Promise) { - count = _Promise; - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return count; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Runs mango queries over the Dexie.js database. - */ -export var dexieQuery = function dexieQuery(instance, preparedQuery) { - try { - return Promise.resolve(instance.internals).then(function (state) { - var query = preparedQuery.query; - var skip = query.skip ? query.skip : 0; - var limit = query.limit ? query.limit : Infinity; - var skipPlusLimit = skip + limit; - var queryPlan = preparedQuery.queryPlan; - var queryMatcher = false; - if (!queryPlan.selectorSatisfiedByIndex) { - queryMatcher = RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); - } - var keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); - var queryPlanFields = queryPlan.index; - var rows = []; - return Promise.resolve(state.dexieDb.transaction('r', state.dexieTable, function (dexieTx) { - try { - /** - * TODO here we use the native IndexedDB transaction - * to get the cursor. - * Instead we should not leave Dexie.js API and find - * a way to create the cursor with Dexie.js. - */ - var tx = dexieTx.idbtrans; - - // const nativeIndexedDB = state.dexieDb.backendDB(); - // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly'); - - var store = tx.objectStore(DEXIE_DOCS_TABLE_NAME); - var index; - if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { - index = store; - } else { - var indexName; - if (queryPlanFields.length === 1) { - indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]); - } else { - indexName = '[' + queryPlanFields.map(function (field) { - return dexieReplaceIfStartsWithPipe(field); - }).join('+') + ']'; - } - index = store.index(indexName); - } - var cursorReq = index.openCursor(keyRange); - return Promise.resolve(new Promise(function (res) { - cursorReq.onsuccess = function (e) { - var cursor = e.target.result; - if (cursor) { - // We have a record in cursor.value - var docData = fromDexieToStorage(cursor.value); - if (!docData._deleted && (!queryMatcher || queryMatcher(docData))) { - rows.push(docData); - } - - /** - * If we do not have to manually sort - * and have enough documents, - * we can abort iterating over the cursor - * because we already have every relevant document. - */ - if (queryPlan.sortFieldsSameAsIndexFields && rows.length === skipPlusLimit) { - res(); - } else { - cursor["continue"](); - } - } else { - // Iteration complete - res(); - } - }; - })).then(function () {}); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - if (!queryPlan.sortFieldsSameAsIndexFields) { - var sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); - rows = rows.sort(sortComparator); - } - - // apply skip and limit boundaries. - rows = rows.slice(skip, skipPlusLimit); - - /** - * Comment this in for debugging to check all fields in the database. - */ - // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray(); - // let documents = docsInDb - // .map(docData => stripDexieKey(docData)) - // .sort(sortComparator); - // if (preparedQuery.skip) { - // documents = documents.slice(preparedQuery.skip); - // } - // if (preparedQuery.limit && documents.length > preparedQuery.limit) { - // documents = documents.slice(0, preparedQuery.limit); - // } - - return { - documents: rows - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -export function getKeyRangeByQueryPlan(queryPlan, IDBKeyRange) { - if (!IDBKeyRange) { - if (typeof window === 'undefined') { - throw new Error('IDBKeyRange missing'); - } else { - IDBKeyRange = window.IDBKeyRange; - } - } - var ret; - /** - * If index has only one field, - * we have to pass the keys directly, not the key arrays. - */ - if (queryPlan.index.length === 1) { - ret = IDBKeyRange.bound(queryPlan.startKeys[0], queryPlan.endKeys[0], queryPlan.inclusiveStart, queryPlan.inclusiveEnd); - } else { - ret = IDBKeyRange.bound(queryPlan.startKeys, queryPlan.endKeys, queryPlan.inclusiveStart, queryPlan.inclusiveEnd); - } - return ret; -} -//# sourceMappingURL=dexie-query.js.map \ No newline at end of file diff --git a/dist/es/plugins/dexie/dexie-query.js.map b/dist/es/plugins/dexie/dexie-query.js.map deleted file mode 100644 index d7be5502fb4..00000000000 --- a/dist/es/plugins/dexie/dexie-query.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-query.js","names":["dexieReplaceIfStartsWithPipe","DEXIE_DOCS_TABLE_NAME","fromDexieToStorage","RxStorageDexieStatics","dexieCount","instance","preparedQuery","internals","state","queryPlan","queryPlanFields","index","keyRange","getKeyRangeByQueryPlan","dexieDb","_options","IDBKeyRange","count","transaction","dexieTable","dexieTx","tx","idbtrans","store","objectStore","length","primaryPath","indexName","map","field","join","request","Promise","res","rej","onsuccess","result","onerror","err","dexieQuery","query","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","schema","rows","cursorReq","openCursor","e","cursor","target","docData","value","_deleted","push","sortFieldsSameAsIndexFields","sortComparator","getSortComparator","sort","slice","documents","window","Error","ret","bound","startKeys","endKeys","inclusiveStart","inclusiveEnd"],"sources":["../../../../src/plugins/dexie/dexie-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport type {\n DexiePreparedQuery,\n RxDocumentData,\n RxQueryPlan,\n RxStorageQueryResult\n} from '../../types';\nimport {\n dexieReplaceIfStartsWithPipe,\n DEXIE_DOCS_TABLE_NAME,\n fromDexieToStorage\n} from './dexie-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\nimport type { RxStorageInstanceDexie } from './rx-storage-instance-dexie';\n\n\nexport function getKeyRangeByQueryPlan(\n queryPlan: RxQueryPlan,\n IDBKeyRange?: any\n) {\n if (!IDBKeyRange) {\n if (typeof window === 'undefined') {\n throw new Error('IDBKeyRange missing');\n } else {\n IDBKeyRange = window.IDBKeyRange;\n }\n }\n\n let ret: any;\n /**\n * If index has only one field,\n * we have to pass the keys directly, not the key arrays.\n */\n if (queryPlan.index.length === 1) {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys[0],\n queryPlan.endKeys[0],\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n } else {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys,\n queryPlan.endKeys,\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n }\n return ret;\n}\n\n\n/**\n * Runs mango queries over the Dexie.js database.\n */\nexport async function dexieQuery(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise> {\n const state = await instance.internals;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlan = preparedQuery.queryPlan;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n\n const queryPlanFields: string[] = queryPlan.index;\n\n let rows: any[] = [];\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n /**\n * TODO here we use the native IndexedDB transaction\n * to get the cursor.\n * Instead we should not leave Dexie.js API and find\n * a way to create the cursor with Dexie.js.\n */\n const tx = (dexieTx as any).idbtrans;\n\n // const nativeIndexedDB = state.dexieDb.backendDB();\n // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly');\n\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n const cursorReq = index.openCursor(keyRange);\n await new Promise(res => {\n cursorReq.onsuccess = function (e: any) {\n const cursor = e.target.result;\n if (cursor) {\n // We have a record in cursor.value\n const docData = fromDexieToStorage(cursor.value);\n if (\n !docData._deleted &&\n (!queryMatcher || queryMatcher(docData))\n ) {\n rows.push(docData);\n }\n\n /**\n * If we do not have to manually sort\n * and have enough documents,\n * we can abort iterating over the cursor\n * because we already have every relevant document.\n */\n if (\n queryPlan.sortFieldsSameAsIndexFields &&\n rows.length === skipPlusLimit\n ) {\n res();\n } else {\n cursor.continue();\n }\n } else {\n // Iteration complete\n res();\n }\n };\n });\n\n\n }\n );\n\n\n if (!queryPlan.sortFieldsSameAsIndexFields) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n\n /**\n * Comment this in for debugging to check all fields in the database.\n */\n // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray();\n // let documents = docsInDb\n // .map(docData => stripDexieKey(docData))\n // .sort(sortComparator);\n // if (preparedQuery.skip) {\n // documents = documents.slice(preparedQuery.skip);\n // }\n // if (preparedQuery.limit && documents.length > preparedQuery.limit) {\n // documents = documents.slice(0, preparedQuery.limit);\n // }\n\n\n\n return {\n documents: rows\n };\n}\n\n\nexport async function dexieCount(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise {\n const state = await instance.internals;\n const queryPlan = preparedQuery.queryPlan;\n const queryPlanFields: string[] = queryPlan.index;\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n let count: number = -1;\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n const tx = (dexieTx as any).idbtrans;\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n\n const request = index.count(keyRange);\n count = await new Promise((res, rej) => {\n request.onsuccess = function () {\n res(request.result);\n };\n request.onerror = (err: any) => rej(err);\n });\n }\n );\n return count;\n}\n"],"mappings":"AAOA,SACIA,4BAA4B,EAC5BC,qBAAqB,EACrBC,kBAAkB,QACf,gBAAgB;AACvB,SAASC,qBAAqB,QAAQ,iBAAiB;AAgLvD,WAAsBC,UAAU,YAAVA,UAAU,CAC5BC,QAA2C,EAC3CC,aAA4C;EAAA,IAC7B;IAAA,uBACKD,QAAQ,CAACE,SAAS,iBAAhCC,KAAK;MACX,IAAMC,SAAS,GAAGH,aAAa,CAACG,SAAS;MACzC,IAAMC,eAAyB,GAAGD,SAAS,CAACE,KAAK;MAEjD,IAAMC,QAAQ,GAAGC,sBAAsB,CACnCJ,SAAS,EACRD,KAAK,C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ACA,OAAOL,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/dexie-statics.js.map b/dist/es/plugins/dexie/dexie-statics.js.map deleted file mode 100644 index ad92677cf64..00000000000 --- a/dist/es/plugins/dexie/dexie-statics.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-statics.js","names":["getDexieSortComparator","newRxError","getQueryPlan","DEFAULT_CHECKPOINT_SCHEMA","getMingoQuery","RxStorageDexieStatics","prepareQuery","schema","mutateableQuery","sort","query","queryPlan","getSortComparator","preparedQuery","getQueryMatcher","_schema","mingoQuery","selector","fun","doc","_deleted","cursor","find","next","checkpointSchema"],"sources":["../../../../src/plugins/dexie/dexie-statics.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n RxDocumentData,\n RxJsonSchema,\n RxStorageStatics,\n DexiePreparedQuery,\n FilledMangoQuery\n} from '../../types';\nimport {\n getDexieSortComparator\n} from './dexie-helper';\nimport { newRxError } from '../../rx-error';\nimport { getQueryPlan } from '../../query-planner';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const RxStorageDexieStatics: RxStorageStatics = {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): DexiePreparedQuery {\n\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n },\n\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: DexiePreparedQuery\n ): DeterministicSortComparator {\n return getDexieSortComparator(schema, preparedQuery.query);\n },\n\n getQueryMatcher(\n _schema: RxJsonSchema,\n preparedQuery: DexiePreparedQuery\n ): QueryMatcher> {\n const query = preparedQuery.query;\n const mingoQuery = getMingoQuery(query.selector);\n const fun: QueryMatcher> = (doc: RxDocumentData) => {\n if (doc._deleted) {\n return false;\n }\n const cursor = mingoQuery.find([doc]);\n const next = cursor.next();\n if (next) {\n return true;\n } else {\n return false;\n }\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n\n};\n"],"mappings":"AAWA,SACIA,sBAAsB,QACnB,gBAAgB;AACvB,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,yBAAyB,QAAQ,wBAAwB;AAClE,SAASC,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,IAAMC,qBAAuC,GAAG;EACnDC,YAAY,wBACRC,MAA+C,EAC/CC,eAA4C,EACf;IAE7B,IAAI,CAACA,eAAe,CAACC,IAAI,EAAE;MACvB,MAAMR,UAAU,CAAC,KAAK,EAAE;QACpBS,KAAK,EAAEF;MACX,CAAC,CAAC;IACN;;IAEA;AACR;AACA;AACA;IACQ,IAAMG,SAAS,GAAGT,YAAY,CAC1BK,MAAM,EACNC,eAAe,CAClB;IAED,OAAO;MACHE,KAAK,EAAEF,eAAe;MACtBG,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAEDC,iBAAiB,6BACbL,MAA+C,EAC/CM,aAA4C,EACN;IACtC,OAAOb,sBAAsB,CAACO,MAAM,EAAEM,aAAa,CAACH,KAAK,CAAC;EAC9D,CAAC;EAEDI,eAAe,2BACXC,OAAgC,EAChCF,aAA4C,EACL;IACvC,IAAMH,KAAK,GAAGG,aAAa,CAACH,KAAK;IACjC,IAAMM,UAAU,GAAGZ,aAAa,CAACM,KAAK,CAACO,QAAQ,CAAC;IAChD,IAAMC,GAA4C,GAAG,SAA/CA,GAA4C,CAAIC,GAA8B,EAAK;MACrF,IAAIA,GAAG,CAACC,QAAQ,EAAE;QACd,OAAO,KAAK;MAChB;MACA,IAAMC,MAAM,GAAGL,UAAU,CAACM,IAAI,CAAC,CAACH,GAAG,CAAC,CAAC;MACrC,IAAMI,IAAI,GAAGF,MAAM,CAACE,IAAI,EAAE;MAC1B,IAAIA,IAAI,EAAE;QACN,OAAO,IAAI;MACf,CAAC,MAAM;QACH,OAAO,KAAK;MAChB;IACJ,CAAC;IACD,OAAOL,GAAG;EACd,CAAC;EAEDM,gBAAgB,EAAErB;AAEtB,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/index.js.map b/dist/es/plugins/dexie/index.js.map deleted file mode 100644 index ee86d16d53d..00000000000 --- a/dist/es/plugins/dexie/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/dexie/index.ts"],"sourcesContent":["export * from './rx-storage-dexie';\nexport * from './rx-storage-instance-dexie';\nexport * from './dexie-helper';\nexport * from './dexie-query';\nexport * from './dexie-statics';\n"],"mappings":"AAAA,cAAc,oBAAoB;AAClC,cAAc,6BAA6B;AAC3C,cAAc,gBAAgB;AAC9B,cAAc,eAAe;AAC7B,cAAc,iBAAiB"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/rx-storage-dexie.js.map b/dist/es/plugins/dexie/rx-storage-dexie.js.map deleted file mode 100644 index 6e59e246525..00000000000 --- a/dist/es/plugins/dexie/rx-storage-dexie.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-dexie.js","names":["ensureNoBooleanIndex","RX_STORAGE_NAME_DEXIE","createDexieStorageInstance","ensureRxStorageInstanceParamsAreCorrect","RxStorageDexieStatics","RxStorageDexie","settings","name","statics","createStorageInstance","params","schema","getRxStorageDexie","storage"],"sources":["../../../../src/plugins/dexie/rx-storage-dexie.ts"],"sourcesContent":["import type {\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNoBooleanIndex,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport type {\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport {\n createDexieStorageInstance,\n RxStorageInstanceDexie\n} from './rx-storage-instance-dexie';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\n\n\n\nexport class RxStorageDexie implements RxStorage {\n public name = RX_STORAGE_NAME_DEXIE;\n public statics = RxStorageDexieStatics;\n\n constructor(\n public settings: DexieSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n ensureNoBooleanIndex(params.schema);\n return createDexieStorageInstance(this, params, this.settings);\n }\n}\n\n\nexport function getRxStorageDexie(\n settings: DexieSettings = {}\n): RxStorageDexie {\n const storage = new RxStorageDexie(settings);\n return storage;\n}\n"],"mappings":"AAIA,SACIA,oBAAoB,EACpBC,qBAAqB,QAClB,gBAAgB;AAKvB,SACIC,0BAA0B,QAEvB,6BAA6B;AACpC,SAASC,uCAAuC,QAAQ,yBAAyB;AACjF,SAASC,qBAAqB,QAAQ,iBAAiB;AAIvD,WAAaC,cAAc;EAIvB,wBACWC,QAAuB,EAChC;IAAA,KALKC,IAAI,GAAGN,qBAAqB;IAAA,KAC5BO,OAAO,GAAGJ,qBAAqB;IAAA,KAG3BE,QAAuB,GAAvBA,QAAuB;EAC9B;EAAC;EAAA,OAEEG,qBAAqB,GAA5B,+BACIC,MAAiE,EACvB;IAC1CP,uCAAuC,CAACO,MAAM,CAAC;IAC/CV,oBAAoB,CAACU,MAAM,CAACC,MAAM,CAAC;IACnC,OAAOT,0BAA0B,CAAC,IAAI,EAAEQ,MAAM,EAAE,IAAI,CAACJ,QAAQ,CAAC;EAClE,CAAC;EAAA;AAAA;AAIL,OAAO,SAASM,iBAAiB,GAEf;EAAA,IADdN,QAAuB,uEAAG,CAAC,CAAC;EAE5B,IAAMO,OAAO,GAAG,IAAIR,cAAc,CAACC,QAAQ,CAAC;EAC5C,OAAOO,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/rx-storage-instance-dexie.js b/dist/es/plugins/dexie/rx-storage-instance-dexie.js deleted file mode 100644 index 7af9a17de63..00000000000 --- a/dist/es/plugins/dexie/rx-storage-instance-dexie.js +++ /dev/null @@ -1,291 +0,0 @@ -import { Subject } from 'rxjs'; -import { now, PROMISE_RESOLVE_VOID, RX_META_LWT_MINIMUM, sortDocumentsByLastWriteTime, lastOfArray, ensureNotFalsy } from '../../util'; -import { closeDexieDb, fromDexieToStorage, fromStorageToDexie, getDexieDbWithTables, getDocsInDb, RX_STORAGE_NAME_DEXIE } from './dexie-helper'; -import { dexieCount, dexieQuery } from './dexie-query'; -import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; -import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; -import { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance'; -import { newRxError } from '../../rx-error'; -var instanceId = now(); -export var RxStorageInstanceDexie = /*#__PURE__*/function () { - function RxStorageInstanceDexie(storage, databaseName, collectionName, schema, internals, options, settings) { - this.changes$ = new Subject(); - this.instanceId = instanceId++; - this.closed = false; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - this.settings = settings; - this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); - } - var _proto = RxStorageInstanceDexie.prototype; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this = this; - ensureNotClosed(_this); - return Promise.resolve(_this.internals).then(function (state) { - var ret = { - success: {}, - error: {} - }; - var documentKeys = documentWrites.map(function (writeRow) { - return writeRow.document[_this.primaryPath]; - }); - var categorized = null; - return Promise.resolve(state.dexieDb.transaction('rw', state.dexieTable, state.dexieDeletedTable, function () { - try { - var docsInDbMap = new Map(); - return Promise.resolve(getDocsInDb(_this.internals, documentKeys)).then(function (docsInDbWithInternals) { - docsInDbWithInternals.forEach(function (docWithDexieInternals) { - var doc = docWithDexieInternals ? fromDexieToStorage(docWithDexieInternals) : docWithDexieInternals; - if (doc) { - docsInDbMap.set(doc[_this.primaryPath], doc); - } - return doc; - }); - categorized = categorizeBulkWriteRows(_this, _this.primaryPath, docsInDbMap, documentWrites, context); - ret.error = categorized.errors; - - /** - * Batch up the database operations - * so we can later run them in bulk. - */ - var bulkPutDocs = []; - var bulkRemoveDocs = []; - var bulkPutDeletedDocs = []; - var bulkRemoveDeletedDocs = []; - categorized.bulkInsertDocs.forEach(function (row) { - var docId = row.document[_this.primaryPath]; - ret.success[docId] = row.document; - bulkPutDocs.push(row.document); - }); - categorized.bulkUpdateDocs.forEach(function (row) { - var docId = row.document[_this.primaryPath]; - ret.success[docId] = row.document; - if (row.document._deleted && row.previous && !row.previous._deleted) { - // newly deleted - bulkRemoveDocs.push(docId); - bulkPutDeletedDocs.push(row.document); - } else if (row.document._deleted && row.previous && row.previous._deleted) { - // deleted was modified but is still deleted - bulkPutDeletedDocs.push(row.document); - } else if (!row.document._deleted) { - // non-deleted was changed - bulkPutDocs.push(row.document); - } else { - throw newRxError('SNH', { - args: { - row: row - } - }); - } - }); - return Promise.resolve(Promise.all([bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(function (d) { - return fromStorageToDexie(d); - })) : PROMISE_RESOLVE_VOID, bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : PROMISE_RESOLVE_VOID, bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(function (d) { - return fromStorageToDexie(d); - })) : PROMISE_RESOLVE_VOID, bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : PROMISE_RESOLVE_VOID])).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - if (ensureNotFalsy(categorized).eventBulk.events.length > 0) { - var lastState = getNewestOfDocumentStates(_this.primaryPath, Object.values(ret.success)); - ensureNotFalsy(categorized).eventBulk.checkpoint = { - id: lastState[_this.primaryPath], - lwt: lastState._meta.lwt - }; - var endTime = now(); - ensureNotFalsy(categorized).eventBulk.events.forEach(function (event) { - return event.endTime = endTime; - }); - _this.changes$.next(ensureNotFalsy(categorized).eventBulk); - } - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - try { - var _this2 = this; - ensureNotClosed(_this2); - return Promise.resolve(_this2.internals).then(function (state) { - var ret = {}; - return Promise.resolve(state.dexieDb.transaction('r', state.dexieTable, state.dexieDeletedTable, function () { - try { - var _temp2 = function _temp2() { - ids.forEach(function (id, idx) { - var documentInDb = docsInDb[idx]; - if (documentInDb && (!documentInDb._deleted || deleted)) { - ret[id] = fromDexieToStorage(documentInDb); - } - }); - }; - var docsInDb; - var _temp = function () { - if (deleted) { - return Promise.resolve(getDocsInDb(_this2.internals, ids)).then(function (_getDocsInDb) { - docsInDb = _getDocsInDb; - }); - } else { - return Promise.resolve(state.dexieTable.bulkGet(ids)).then(function (_state$dexieTable$bul) { - docsInDb = _state$dexieTable$bul; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - ensureNotClosed(this); - return dexieQuery(this, preparedQuery); - }; - _proto.count = function count(preparedQuery) { - try { - var _this3 = this; - return Promise.resolve(dexieCount(_this3, preparedQuery)).then(function (result) { - return { - count: result, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _this4 = this; - ensureNotClosed(_this4); - var sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM; - var sinceId = checkpoint ? checkpoint.id : ''; - return Promise.resolve(_this4.internals).then(function (state) { - return Promise.resolve(Promise.all([state.dexieTable, state.dexieDeletedTable].map(function (table) { - try { - var query = table.where('[_meta.lwt+' + _this4.primaryPath + ']').above([sinceLwt, sinceId]).limit(limit); - return Promise.resolve(query.toArray()).then(function (changedDocuments) { - return changedDocuments.map(function (d) { - return fromDexieToStorage(d); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function (_ref) { - var changedDocsNormal = _ref[0], - changedDocsDeleted = _ref[1]; - var changedDocs = changedDocsNormal.concat(changedDocsDeleted); - changedDocs = sortDocumentsByLastWriteTime(_this4.primaryPath, changedDocs); - changedDocs = changedDocs.slice(0, limit); - var lastDoc = lastOfArray(changedDocs); - return { - documents: changedDocs, - checkpoint: lastDoc ? { - id: lastDoc[_this4.primaryPath], - lwt: lastDoc._meta.lwt - } : checkpoint ? checkpoint : { - id: '', - lwt: 0 - } - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.remove = function remove() { - try { - var _this5 = this; - ensureNotClosed(_this5); - return Promise.resolve(_this5.internals).then(function (state) { - return Promise.resolve(Promise.all([state.dexieDeletedTable.clear(), state.dexieTable.clear()])).then(function () { - return _this5.close(); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.changeStream = function changeStream() { - ensureNotClosed(this); - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(minimumDeletedTime) { - try { - var _this6 = this; - ensureNotClosed(_this6); - return Promise.resolve(_this6.internals).then(function (state) { - return Promise.resolve(state.dexieDb.transaction('rw', state.dexieDeletedTable, function () { - try { - var maxDeletionTime = now() - minimumDeletedTime; - return Promise.resolve(state.dexieDeletedTable.where('_meta.lwt').below(maxDeletionTime).toArray()).then(function (toRemove) { - var removeIds = toRemove.map(function (doc) { - return doc[_this6.primaryPath]; - }); - return Promise.resolve(state.dexieDeletedTable.bulkDelete(removeIds)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - /** - * TODO instead of deleting all deleted docs at once, - * only clean up some of them and return false if there are more documents to clean up. - * This ensures that when many documents have to be purged, - * we do not block the more important tasks too long. - */ - return true; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { - ensureNotClosed(this); - throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.'); - }; - _proto.close = function close() { - ensureNotClosed(this); - this.closed = true; - this.changes$.complete(); - closeDexieDb(this.internals); - return PROMISE_RESOLVE_VOID; - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstanceDexie; -}(); -export function createDexieStorageInstance(storage, params, settings) { - var internals = getDexieDbWithTables(params.databaseName, params.collectionName, settings, params.schema); - var instance = new RxStorageInstanceDexie(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); - addRxStorageMultiInstanceSupport(RX_STORAGE_NAME_DEXIE, params, instance); - return Promise.resolve(instance); -} -function ensureNotClosed(instance) { - if (instance.closed) { - throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName); - } -} -//# sourceMappingURL=rx-storage-instance-dexie.js.map \ No newline at end of file diff --git a/dist/es/plugins/dexie/rx-storage-instance-dexie.js.map b/dist/es/plugins/dexie/rx-storage-instance-dexie.js.map deleted file mode 100644 index f28903ba17f..00000000000 --- a/dist/es/plugins/dexie/rx-storage-instance-dexie.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-dexie.js","names":["Subject","now","PROMISE_RESOLVE_VOID","RX_META_LWT_MINIMUM","sortDocumentsByLastWriteTime","lastOfArray","ensureNotFalsy","closeDexieDb","fromDexieToStorage","fromStorageToDexie","getDexieDbWithTables","getDocsInDb","RX_STORAGE_NAME_DEXIE","dexieCount","dexieQuery","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","addRxStorageMultiInstanceSupport","newRxError","instanceId","RxStorageInstanceDexie","storage","databaseName","collectionName","schema","internals","options","settings","changes$","closed","primaryPath","primaryKey","bulkWrite","documentWrites","context","ensureNotClosed","state","ret","success","error","documentKeys","map","writeRow","document","categorized","dexieDb","transaction","dexieTable","dexieDeletedTable","docsInDbMap","Map","docsInDbWithInternals","forEach","docWithDexieInternals","doc","set","errors","bulkPutDocs","bulkRemoveDocs","bulkPutDeletedDocs","bulkRemoveDeletedDocs","bulkInsertDocs","row","docId","push","bulkUpdateDocs","_deleted","previous","args","Promise","all","length","bulkPut","d","bulkDelete","eventBulk","events","lastState","Object","values","checkpoint","id","lwt","_meta","endTime","event","next","findDocumentsById","ids","deleted","idx","documentInDb","docsInDb","bulkGet","query","preparedQuery","count","result","mode","getChangedDocumentsSince","limit","sinceLwt","sinceId","table","where","above","toArray","changedDocuments","changedDocsNormal","changedDocsDeleted","changedDocs","concat","slice","lastDoc","documents","remove","clear","close","changeStream","asObservable","cleanup","minimumDeletedTime","maxDeletionTime","below","toRemove","removeIds","getAttachmentData","_documentId","_attachmentId","Error","complete","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","createDexieStorageInstance","params","instance","resolve"],"sources":["../../../../src/plugins/dexie/rx-storage-instance-dexie.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n now,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM,\n sortDocumentsByLastWriteTime,\n lastOfArray,\n ensureNotFalsy\n} from '../../util';\nimport type {\n RxStorageInstance,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n RxStorageInstanceCreationParams,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n RxStorageCountResult\n} from '../../types';\nimport {\n DexiePreparedQuery,\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport { RxStorageDexie } from './rx-storage-dexie';\nimport {\n closeDexieDb,\n fromDexieToStorage,\n fromStorageToDexie,\n getDexieDbWithTables,\n getDocsInDb,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport { dexieCount, dexieQuery } from './dexie-query';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance';\nimport { newRxError } from '../../rx-error';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceDexie implements RxStorageInstance<\nRxDocType,\nDexieStorageInternals,\nDexieSettings,\nRxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageDexie,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: DexieStorageInternals,\n public readonly options: Readonly,\n public readonly settings: DexieSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const documentKeys: string[] = documentWrites.map(writeRow => writeRow.document[this.primaryPath] as any);\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n const docsInDbMap = new Map>();\n const docsInDbWithInternals = await getDocsInDb(this.internals, documentKeys);\n docsInDbWithInternals.forEach(docWithDexieInternals => {\n const doc = docWithDexieInternals ? fromDexieToStorage(docWithDexieInternals) : docWithDexieInternals;\n if (doc) {\n docsInDbMap.set(doc[this.primaryPath], doc);\n }\n return doc;\n });\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDbMap,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Batch up the database operations\n * so we can later run them in bulk.\n */\n const bulkPutDocs: any[] = [];\n const bulkRemoveDocs: string[] = [];\n const bulkPutDeletedDocs: any[] = [];\n const bulkRemoveDeletedDocs: string[] = [];\n\n categorized.bulkInsertDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n bulkPutDocs.push(row.document);\n });\n categorized.bulkUpdateDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n if (\n row.document._deleted &&\n (row.previous && !row.previous._deleted)\n ) {\n // newly deleted\n bulkRemoveDocs.push(docId);\n bulkPutDeletedDocs.push(row.document);\n } else if (\n row.document._deleted &&\n row.previous && row.previous._deleted\n ) {\n // deleted was modified but is still deleted\n bulkPutDeletedDocs.push(row.document);\n } else if (!row.document._deleted) {\n // non-deleted was changed\n bulkPutDocs.push(row.document);\n } else {\n throw newRxError('SNH', { args: { row } });\n }\n });\n\n await Promise.all([\n bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : PROMISE_RESOLVE_VOID,\n bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : PROMISE_RESOLVE_VOID\n ]);\n });\n\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n const endTime = now();\n ensureNotFalsy(categorized).eventBulk.events.forEach(event => (event as any).endTime = endTime);\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n\n return ret;\n }\n\n async findDocumentsById(\n ids: string[],\n deleted: boolean\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxDocumentDataById = {};\n\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n let docsInDb: RxDocumentData[];\n if (deleted) {\n docsInDb = await getDocsInDb(this.internals, ids);\n } else {\n docsInDb = await state.dexieTable.bulkGet(ids);\n }\n ids.forEach((id, idx) => {\n const documentInDb = docsInDb[idx];\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = fromDexieToStorage(documentInDb);\n }\n });\n });\n return ret;\n }\n\n query(preparedQuery: DexiePreparedQuery): Promise> {\n ensureNotClosed(this);\n return dexieQuery(\n this,\n preparedQuery\n );\n }\n async count(\n preparedQuery: DexiePreparedQuery\n ): Promise {\n const result = await dexieCount(this, preparedQuery);\n return {\n count: result,\n mode: 'fast'\n };\n }\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n ensureNotClosed(this);\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n const state = await this.internals;\n\n\n const [changedDocsNormal, changedDocsDeleted] = await Promise.all(\n [\n state.dexieTable,\n state.dexieDeletedTable\n ].map(async (table) => {\n const query = table\n .where('[_meta.lwt+' + this.primaryPath + ']')\n .above([sinceLwt, sinceId])\n .limit(limit);\n const changedDocuments: RxDocumentData[] = await query.toArray();\n return changedDocuments.map(d => fromDexieToStorage(d));\n })\n );\n let changedDocs = changedDocsNormal.concat(changedDocsDeleted);\n\n changedDocs = sortDocumentsByLastWriteTime(this.primaryPath as any, changedDocs);\n changedDocs = changedDocs.slice(0, limit);\n\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n async remove(): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await Promise.all([\n state.dexieDeletedTable.clear(),\n state.dexieTable.clear()\n ]);\n return this.close();\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotClosed(this);\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieDeletedTable,\n async () => {\n const maxDeletionTime = now() - minimumDeletedTime;\n const toRemove = await state.dexieDeletedTable\n .where('_meta.lwt')\n .below(maxDeletionTime)\n .toArray();\n const removeIds: string[] = toRemove.map(doc => doc[this.primaryPath]);\n await state.dexieDeletedTable.bulkDelete(removeIds);\n }\n );\n\n /**\n * TODO instead of deleting all deleted docs at once,\n * only clean up some of them and return false if there are more documents to clean up.\n * This ensures that when many documents have to be purged,\n * we do not block the more important tasks too long.\n */\n return true;\n }\n\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n ensureNotClosed(this);\n throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.');\n }\n\n close(): Promise {\n ensureNotClosed(this);\n this.closed = true;\n this.changes$.complete();\n closeDexieDb(this.internals);\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\n\nexport function createDexieStorageInstance(\n storage: RxStorageDexie,\n params: RxStorageInstanceCreationParams,\n settings: DexieSettings\n): Promise> {\n const internals = getDexieDbWithTables(\n params.databaseName,\n params.collectionName,\n settings,\n params.schema\n );\n\n const instance = new RxStorageInstanceDexie(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_DEXIE,\n params,\n instance\n );\n\n return Promise.resolve(instance);\n}\n\n\n\nfunction ensureNotClosed(\n instance: RxStorageInstanceDexie\n) {\n if (instance.closed) {\n throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName);\n }\n}\n"],"mappings":"AAAA,SACIA,OAAO,QAEJ,MAAM;AACb,SACIC,GAAG,EACHC,oBAAoB,EACpBC,mBAAmB,EACnBC,4BAA4B,EAC5BC,WAAW,EACXC,cAAc,QACX,YAAY;AAyBnB,SACIC,YAAY,EACZC,kBAAkB,EAClBC,kBAAkB,EAClBC,oBAAoB,EACpBC,WAAW,EACXC,qBAAqB,QAClB,gBAAgB;AACvB,SAASC,UAAU,EAAEC,UAAU,QAAQ,eAAe;AACtD,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SAASC,uBAAuB,EAAEC,yBAAyB,QAAQ,yBAAyB;AAC5F,SAASC,gCAAgC,QAAQ,gCAAgC;AACjF,SAASC,UAAU,QAAQ,gBAAgB;AAE3C,IAAIC,UAAU,GAAGnB,GAAG,EAAE;AAEtB,WAAaoB,sBAAsB;EAW/B,gCACoBC,OAAuB,EACvBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAAgC,EAChCC,OAAgC,EAChCC,QAAuB,EACzC;IAAA,KAZMC,QAAQ,GAAoG,IAAI7B,OAAO,EAAE;IAAA,KACjHoB,UAAU,GAAGA,UAAU,EAAE;IAAA,KAClCU,MAAM,GAAG,KAAK;IAAA,KAGDR,OAAuB,GAAvBA,OAAuB;IAAA,KACvBC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAAgC,GAAhCA,SAAgC;IAAA,KAChCC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AA4B,yCAACC,aAAyD,EAAiB;IAAA;EAAE,CAAC;EAAA;AAAA;AAKpH,OAAO,SAASC,0BAA0B,CACtCjH,OAAuB,EACvBkH,MAAiE,EACjE5G,QAAuB,EACmB;EAC1C,IAAMF,SAAS,GAAGhB,oBAAoB,CAClC8H,MAAM,CAACjH,YAAY,EACnBiH,MAAM,CAAChH,cAAc,EACrBI,QAAQ,EACR4G,MAAM,CAAC/G,MAAM,CAChB;EAED,IAAMgH,QAAQ,GAAG,IAAIpH,sBAAsB,CACvCC,OAAO,EACPkH,MAAM,CAACjH,YAAY,EACnBiH,MAAM,CAAChH,cAAc,EACrBgH,MAAM,CAAC/G,MAAM,EACbC,SAAS,EACT8G,MAAM,CAAC7G,OAAO,EACdC,QAAQ,CACX;EAEDV,gCAAgC,CAC5BN,qBAAqB,EACrB4H,MAAM,EACNC,QAAQ,CACX;EAED,OAAOnE,OAAO,CAACoE,OAAO,CAACD,QAAQ,CAAC;AACpC;AAIA,SAASrG,eAAe,CACpBqG,QAAqC,EACvC;EACE,IAAIA,QAAQ,CAAC3G,MAAM,EAAE;IACjB,MAAM,IAAIoG,KAAK,CAAC,mCAAmC,GAAGO,QAAQ,CAAClH,YAAY,GAAG,GAAG,GAAGkH,QAAQ,CAACjH,cAAc,CAAC;EAChH;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/encryption/index.js b/dist/es/plugins/encryption/index.js index 8b04dd518b3..1cdd2912490 100644 --- a/dist/es/plugins/encryption/index.js +++ b/dist/es/plugins/encryption/index.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * this plugin adds the encryption-capabilities to rxdb * It's using crypto-js/aes for password-encryption @@ -10,18 +12,7 @@ import { wrapRxStorageInstance } from '../../plugin-helpers'; import { INTERNAL_STORE_SCHEMA_TITLE } from '../../rx-database-internal-store'; import { newRxError, newRxTypeError } from '../../rx-error'; import { hasEncryption } from '../../rx-storage-helper'; -import { b64DecodeUnicode, b64EncodeUnicode, clone, ensureNotFalsy, flatClone } from '../../util'; -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} +import { b64DecodeUnicode, b64EncodeUnicode, clone, ensureNotFalsy, flatClone } from '../../plugins/utils'; export var MINIMUM_PASSWORD_LENGTH = 8; export function encryptString(value, password) { var encrypted = AES.encrypt(value, password); @@ -46,113 +37,122 @@ export function decryptString(cipherText, password) { } export function wrappedKeyEncryptionStorage(args) { return Object.assign({}, args.storage, { - createStorageInstance: function createStorageInstance(params) { - try { - var _temp4 = function _temp4(_result) { - if (_exit) return _result; - if (!params.password) { - throw newRxError('EN3', { - database: params.databaseName, - collection: params.collectionName, - schema: params.schema - }); - } - var password = params.password; - var schemaWithoutEncrypted = clone(params.schema); - delete schemaWithoutEncrypted.encrypted; - if (schemaWithoutEncrypted.attachments) { - schemaWithoutEncrypted.attachments.encrypted = false; - } - function modifyToStorage(docData) { - docData = cloneWithoutAttachments(docData); - ensureNotFalsy(params.schema.encrypted).forEach(function (path) { - var value = objectPath.get(docData, path); - if (typeof value === 'undefined') { - return; - } - var stringValue = JSON.stringify(value); - var encrypted = encryptString(stringValue, password); - objectPath.set(docData, path, encrypted); - }); + createStorageInstance: function () { + var _createStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(params) { + var retInstance, password, schemaWithoutEncrypted, instance, modifyToStorage, modifyFromStorage, modifyAttachmentFromStorage; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + modifyAttachmentFromStorage = function _modifyAttachmentFrom(attachmentData) { + if (params.schema.attachments && params.schema.attachments.encrypted) { + var decrypted = decryptString(b64DecodeUnicode(attachmentData), password); + return decrypted; + } else { + return attachmentData; + } + }; + modifyFromStorage = function _modifyFromStorage(docData) { + docData = cloneWithoutAttachments(docData); + ensureNotFalsy(params.schema.encrypted).forEach(function (path) { + var value = objectPath.get(docData, path); + if (typeof value === 'undefined') { + return; + } + var decrypted = decryptString(value, password); + var decryptedParsed = JSON.parse(decrypted); + objectPath.set(docData, path, decryptedParsed); + }); + return docData; + }; + modifyToStorage = function _modifyToStorage(docData) { + docData = cloneWithoutAttachments(docData); + ensureNotFalsy(params.schema.encrypted).forEach(function (path) { + var value = objectPath.get(docData, path); + if (typeof value === 'undefined') { + return; + } + var stringValue = JSON.stringify(value); + var encrypted = encryptString(stringValue, password); + objectPath.set(docData, path, encrypted); + }); - // handle attachments - if (params.schema.attachments && params.schema.attachments.encrypted) { - var newAttachments = {}; - Object.entries(docData._attachments).forEach(function (_ref) { - var id = _ref[0], - attachment = _ref[1]; - var useAttachment = flatClone(attachment); - if (useAttachment.data) { - var dataString = useAttachment.data; - useAttachment.data = b64EncodeUnicode(encryptString(dataString, password)); + // handle attachments + if (params.schema.attachments && params.schema.attachments.encrypted) { + var newAttachments = {}; + Object.entries(docData._attachments).forEach(function (_ref) { + var id = _ref[0], + attachment = _ref[1]; + var useAttachment = flatClone(attachment); + if (useAttachment.data) { + var dataString = useAttachment.data; + useAttachment.data = b64EncodeUnicode(encryptString(dataString, password)); + } + newAttachments[id] = useAttachment; + }); + docData._attachments = newAttachments; } - newAttachments[id] = useAttachment; - }); - docData._attachments = newAttachments; - } - return docData; - } - function modifyFromStorage(docData) { - docData = cloneWithoutAttachments(docData); - ensureNotFalsy(params.schema.encrypted).forEach(function (path) { - var value = objectPath.get(docData, path); - if (typeof value === 'undefined') { - return; + return docData; + }; + if (hasEncryption(params.schema)) { + _context.next = 18; + break; } - var decrypted = decryptString(value, password); - var decryptedParsed = JSON.parse(decrypted); - objectPath.set(docData, path, decryptedParsed); - }); - return docData; - } - function modifyAttachmentFromStorage(attachmentData) { - if (params.schema.attachments && params.schema.attachments.encrypted) { - var decrypted = decryptString(b64DecodeUnicode(attachmentData), password); - return decrypted; - } else { - return attachmentData; - } - } - return Promise.resolve(args.storage.createStorageInstance(Object.assign({}, params, { - schema: schemaWithoutEncrypted - }))).then(function (instance) { - return wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage, modifyAttachmentFromStorage); - }); - }; - var _exit = false; - var _temp3 = function () { - if (!hasEncryption(params.schema)) { - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (retInstance) { - var _exit2 = false; - function _temp2(_result3) { - if (_exit2) return _result3; - _exit = true; - return retInstance; + _context.next = 6; + return args.storage.createStorageInstance(params); + case 6: + retInstance = _context.sent; + if (!(params.schema.title === INTERNAL_STORE_SCHEMA_TITLE && params.password)) { + _context.next = 17; + break; } - var _temp = function () { - if (params.schema.title === INTERNAL_STORE_SCHEMA_TITLE && params.password) { - return _catch(function () { - validatePassword(params.password); - }, function (err) { - /** - * Even if the checks fail, - * we have to clean up. - */ - return Promise.resolve(retInstance.close()).then(function () { - throw err; - }); - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); + _context.prev = 8; + validatePassword(params.password); + _context.next = 17; + break; + case 12: + _context.prev = 12; + _context.t0 = _context["catch"](8); + _context.next = 16; + return retInstance.close(); + case 16: + throw _context.t0; + case 17: + return _context.abrupt("return", retInstance); + case 18: + if (params.password) { + _context.next = 20; + break; + } + throw newRxError('EN3', { + database: params.databaseName, + collection: params.collectionName, + schema: params.schema + }); + case 20: + password = params.password; + schemaWithoutEncrypted = clone(params.schema); + delete schemaWithoutEncrypted.encrypted; + if (schemaWithoutEncrypted.attachments) { + schemaWithoutEncrypted.attachments.encrypted = false; + } + _context.next = 26; + return args.storage.createStorageInstance(Object.assign({}, params, { + schema: schemaWithoutEncrypted + })); + case 26: + instance = _context.sent; + return _context.abrupt("return", wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage, modifyAttachmentFromStorage)); + case 28: + case "end": + return _context.stop(); } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); + }, _callee, null, [[8, 12]]); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); } function cloneWithoutAttachments(data) { diff --git a/dist/es/plugins/encryption/index.js.map b/dist/es/plugins/encryption/index.js.map index bbd9b185094..e7e0a97a13f 100644 --- a/dist/es/plugins/encryption/index.js.map +++ b/dist/es/plugins/encryption/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["AES","cryptoEnc","objectPath","wrapRxStorageInstance","INTERNAL_STORE_SCHEMA_TITLE","newRxError","newRxTypeError","hasEncryption","b64DecodeUnicode","b64EncodeUnicode","clone","ensureNotFalsy","flatClone","body","recover","result","e","then","MINIMUM_PASSWORD_LENGTH","encryptString","value","password","encrypted","encrypt","toString","decryptString","cipherText","args","decrypted","decrypt","ret","wrappedKeyEncryptionStorage","Object","assign","storage","createStorageInstance","params","database","databaseName","collection","collectionName","schema","schemaWithoutEncrypted","attachments","modifyToStorage","docData","cloneWithoutAttachments","forEach","path","get","stringValue","JSON","stringify","set","newAttachments","entries","_attachments","id","attachment","useAttachment","data","dataString","modifyFromStorage","decryptedParsed","parse","modifyAttachmentFromStorage","attachmentData","instance","retInstance","title","validatePassword","err","close","length","minPassLength"],"sources":["../../../../src/plugins/encryption/index.ts"],"sourcesContent":["/**\n * this plugin adds the encryption-capabilities to rxdb\n * It's using crypto-js/aes for password-encryption\n * @link https://github.com/brix/crypto-js\n */\nimport AES from 'crypto-js/aes';\nimport * as cryptoEnc from 'crypto-js/enc-utf8';\nimport objectPath from 'object-path';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport {\n INTERNAL_STORE_SCHEMA_TITLE\n} from '../../rx-database-internal-store';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { hasEncryption } from '../../rx-storage-helper';\nimport type {\n InternalStoreDocType,\n RxAttachmentWriteData,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n b64DecodeUnicode,\n b64EncodeUnicode,\n clone,\n ensureNotFalsy,\n flatClone\n} from '../../util';\n\nexport const MINIMUM_PASSWORD_LENGTH: 8 = 8;\n\n\nexport function encryptString(value: string, password: string): string {\n const encrypted = AES.encrypt(value, password);\n return encrypted.toString();\n}\n\nexport function decryptString(cipherText: string, password: any): string {\n /**\n * Trying to decrypt non-strings\n * will cause no errors and will be hard to debug.\n * So instead we do this check here.\n */\n if (typeof cipherText !== 'string') {\n throw newRxError('SNH', {\n args: {\n cipherText\n }\n });\n }\n\n const decrypted = AES.decrypt(cipherText, password);\n const ret = decrypted.toString(cryptoEnc);\n return ret;\n}\n\nexport type InternalStorePasswordDocType = InternalStoreDocType<{\n hash: string;\n}>;\n\nexport function wrappedKeyEncryptionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!hasEncryption(params.schema)) {\n const retInstance = await args.storage.createStorageInstance(params);\n if (\n params.schema.title === INTERNAL_STORE_SCHEMA_TITLE &&\n params.password\n ) {\n try {\n validatePassword(params.password);\n } catch (err) {\n /**\n * Even if the checks fail,\n * we have to clean up.\n */\n await retInstance.close();\n throw err;\n }\n }\n return retInstance;\n }\n\n if (!params.password) {\n throw newRxError('EN3', {\n database: params.databaseName,\n collection: params.collectionName,\n schema: params.schema\n });\n }\n const password = params.password;\n\n const schemaWithoutEncrypted: RxJsonSchema> = clone(params.schema);\n delete schemaWithoutEncrypted.encrypted;\n if (schemaWithoutEncrypted.attachments) {\n schemaWithoutEncrypted.attachments.encrypted = false;\n }\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: schemaWithoutEncrypted\n }\n )\n );\n\n function modifyToStorage(docData: RxDocumentWriteData) {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n\n const stringValue = JSON.stringify(value);\n const encrypted = encryptString(stringValue, password);\n objectPath.set(docData, path, encrypted);\n });\n\n // handle attachments\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const newAttachments: typeof docData._attachments = {};\n Object.entries(docData._attachments).forEach(([id, attachment]) => {\n const useAttachment: RxAttachmentWriteData = flatClone(attachment) as any;\n if (useAttachment.data) {\n const dataString = useAttachment.data;\n useAttachment.data = b64EncodeUnicode(encryptString(dataString, password));\n }\n newAttachments[id] = useAttachment;\n });\n docData._attachments = newAttachments;\n }\n return docData;\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n const decrypted = decryptString(value, password);\n const decryptedParsed = JSON.parse(decrypted);\n objectPath.set(docData, path, decryptedParsed);\n });\n return docData;\n }\n\n function modifyAttachmentFromStorage(attachmentData: string): string {\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const decrypted = decryptString(b64DecodeUnicode(attachmentData), password);\n return decrypted;\n } else {\n return attachmentData;\n }\n }\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage,\n modifyAttachmentFromStorage\n );\n }\n }\n );\n}\n\n\n\n\n\nfunction cloneWithoutAttachments(data: RxDocumentWriteData): RxDocumentData {\n const attachments = data._attachments;\n data = flatClone(data);\n delete (data as any)._attachments;\n data = clone(data);\n data._attachments = attachments;\n return data as any;\n}\n\nfunction validatePassword(password: any) {\n if (password && typeof password !== 'string') {\n throw newRxTypeError('EN1', {\n password\n });\n }\n if (password && password.length < MINIMUM_PASSWORD_LENGTH) {\n throw newRxError('EN2', {\n minPassLength: MINIMUM_PASSWORD_LENGTH,\n password\n });\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,GAAG,MAAM,eAAe;AAC/B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IAAI,CAACJ,YAAY;EACrCI,IAAI,GAAGhD,SAAS,CAACgD,IAAI,CAAC;EACtB,OAAQA,IAAI,CAASJ,YAAY;EACjCI,IAAI,GAAGlD,KAAK,CAACkD,IAAI,CAAC;EAClBA,IAAI,CAACJ,YAAY,GAAGb,WAAW;EAC/B,OAAOiB,IAAI;AACf;AAEA,SAASU,gBAAgB,CAACjD,QAAa,EAAE;EACrC,IAAIA,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;IAC1C,MAAMf,cAAc,CAAC,KAAK,EAAE;MACxBe,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;EACA,IAAIA,QAAQ,IAAIA,QAAQ,CAACoD,MAAM,GAAGvD,uBAAuB,EAAE;IACvD,MAAMb,UAAU,CAAC,KAAK,EAAE;MACpBqE,aAAa,EAAExD,uBAAuB;MACtCG,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;AACJ"} \ No newline at end of file +{"version":3,"file":"index.js","names":["AES","cryptoEnc","objectPath","wrapRxStorageInstance","INTERNAL_STORE_SCHEMA_TITLE","newRxError","newRxTypeError","hasEncryption","b64DecodeUnicode","b64EncodeUnicode","clone","ensureNotFalsy","flatClone","MINIMUM_PASSWORD_LENGTH","encryptString","value","password","encrypted","encrypt","toString","decryptString","cipherText","args","decrypted","decrypt","ret","wrappedKeyEncryptionStorage","Object","assign","storage","createStorageInstance","params","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","attachmentData","schema","attachments","docData","cloneWithoutAttachments","forEach","path","get","decryptedParsed","JSON","parse","set","stringValue","stringify","newAttachments","entries","_attachments","id","attachment","useAttachment","data","dataString","retInstance","title","validatePassword","close","database","databaseName","collection","collectionName","schemaWithoutEncrypted","instance","length","minPassLength"],"sources":["../../../../src/plugins/encryption/index.ts"],"sourcesContent":["/**\n * this plugin adds the encryption-capabilities to rxdb\n * It's using crypto-js/aes for password-encryption\n * @link https://github.com/brix/crypto-js\n */\nimport AES from 'crypto-js/aes';\nimport * as cryptoEnc from 'crypto-js/enc-utf8';\nimport objectPath from 'object-path';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport {\n INTERNAL_STORE_SCHEMA_TITLE\n} from '../../rx-database-internal-store';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { hasEncryption } from '../../rx-storage-helper';\nimport type {\n InternalStoreDocType,\n RxAttachmentWriteData,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n b64DecodeUnicode,\n b64EncodeUnicode,\n clone,\n ensureNotFalsy,\n flatClone\n} from '../../plugins/utils';\n\nexport const MINIMUM_PASSWORD_LENGTH: 8 = 8;\n\n\nexport function encryptString(value: string, password: string): string {\n const encrypted = AES.encrypt(value, password);\n return encrypted.toString();\n}\n\nexport function decryptString(cipherText: string, password: any): string {\n /**\n * Trying to decrypt non-strings\n * will cause no errors and will be hard to debug.\n * So instead we do this check here.\n */\n if (typeof cipherText !== 'string') {\n throw newRxError('SNH', {\n args: {\n cipherText\n }\n });\n }\n\n const decrypted = AES.decrypt(cipherText, password);\n const ret = decrypted.toString(cryptoEnc);\n return ret;\n}\n\nexport type InternalStorePasswordDocType = InternalStoreDocType<{\n hash: string;\n}>;\n\nexport function wrappedKeyEncryptionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!hasEncryption(params.schema)) {\n const retInstance = await args.storage.createStorageInstance(params);\n if (\n params.schema.title === INTERNAL_STORE_SCHEMA_TITLE &&\n params.password\n ) {\n try {\n validatePassword(params.password);\n } catch (err) {\n /**\n * Even if the checks fail,\n * we have to clean up.\n */\n await retInstance.close();\n throw err;\n }\n }\n return retInstance;\n }\n\n if (!params.password) {\n throw newRxError('EN3', {\n database: params.databaseName,\n collection: params.collectionName,\n schema: params.schema\n });\n }\n const password = params.password;\n\n const schemaWithoutEncrypted: RxJsonSchema> = clone(params.schema);\n delete schemaWithoutEncrypted.encrypted;\n if (schemaWithoutEncrypted.attachments) {\n schemaWithoutEncrypted.attachments.encrypted = false;\n }\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: schemaWithoutEncrypted\n }\n )\n );\n\n function modifyToStorage(docData: RxDocumentWriteData) {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n\n const stringValue = JSON.stringify(value);\n const encrypted = encryptString(stringValue, password);\n objectPath.set(docData, path, encrypted);\n });\n\n // handle attachments\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const newAttachments: typeof docData._attachments = {};\n Object.entries(docData._attachments).forEach(([id, attachment]) => {\n const useAttachment: RxAttachmentWriteData = flatClone(attachment) as any;\n if (useAttachment.data) {\n const dataString = useAttachment.data;\n useAttachment.data = b64EncodeUnicode(encryptString(dataString, password));\n }\n newAttachments[id] = useAttachment;\n });\n docData._attachments = newAttachments;\n }\n return docData;\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n const decrypted = decryptString(value, password);\n const decryptedParsed = JSON.parse(decrypted);\n objectPath.set(docData, path, decryptedParsed);\n });\n return docData;\n }\n\n function modifyAttachmentFromStorage(attachmentData: string): string {\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const decrypted = decryptString(b64DecodeUnicode(attachmentData), password);\n return decrypted;\n } else {\n return attachmentData;\n }\n }\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage,\n modifyAttachmentFromStorage\n );\n }\n }\n );\n}\n\n\n\n\n\nfunction cloneWithoutAttachments(data: RxDocumentWriteData): RxDocumentData {\n const attachments = data._attachments;\n data = flatClone(data);\n delete (data as any)._attachments;\n data = clone(data);\n data._attachments = attachments;\n return data as any;\n}\n\nfunction validatePassword(password: any) {\n if (password && typeof password !== 'string') {\n throw newRxTypeError('EN1', {\n password\n });\n }\n if (password && password.length < MINIMUM_PASSWORD_LENGTH) {\n throw newRxError('EN2', {\n minPassLength: MINIMUM_PASSWORD_LENGTH,\n password\n });\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,GAAG,MAAM,eAAe;AAC/B,OAAO,KAAKC,SAAS,MAAM,oBAAoB;AAC/C,OAAOC,UAAU,MAAM,aAAa;AACpC,SAASC,qBAAqB,QAAQ,sBAAsB;AAC5D,SACIC,2BAA2B,QACxB,kCAAkC;AACzC,SAASC,UAAU,EAAEC,cAAc,QAAQ,gBAAgB;AAC3D,SAASC,aAAa,QAAQ,yBAAyB;AAUvD,SACIC,gBAAgB,EAChBC,gBAAgB,EAChBC,KAAK,EACLC,cAAc,EACdC,SAAS,QACN,qBAAqB;AAE5B,OAAO,IAAMC,uBAA0B,GAAG,CAAC;AAG3C,OAAO,SAASC,aAAa,CAACC,KAAa,EAAEC,QAAgB,EAAU;EACnE,IAAMC,SAAS,GAAGjB,GAAG,CAACkB,OAAO,CAACH,KAAK,EAAEC,QAAQ,CAAC;EAC9C,OAAOC,SAAS,CAACE,QAAQ,EAAE;AAC/B;AAEA,OAAO,SAASC,aAAa,CAACC,UAAkB,EAAEL,QAAa,EAAU;EACrE;AACJ;AACA;AACA;AACA;EACI,IAAI,OAAOK,UAAU,KAAK,QAAQ,EAAE;IAChC,MAAMhB,UAAU,CAAC,KAAK,EAAE;MACpBiB,IAAI,EAAE;QACFD,UAAU,EAAVA;MACJ;IACJ,CAAC,CAAC;EACN;EAEA,IAAME,SAAS,GAAGvB,GAAG,CAACwB,OAAO,CAACH,UAAU,EAAEL,QAAQ,CAAC;EACnD,IAAMS,GAAG,GAAGF,SAAS,CAACJ,QA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A,SAASK,uBAAuB,CAAIgB,IAA4B,EAAqB;EACjF,IAAMlB,WAAW,GAAGkB,IAAI,CAACJ,YAAY;EACrCI,IAAI,GAAG3C,SAAS,CAAC2C,IAAI,CAAC;EACtB,OAAQA,IAAI,CAASJ,YAAY;EACjCI,IAAI,GAAG7C,KAAK,CAAC6C,IAAI,CAAC;EAClBA,IAAI,CAACJ,YAAY,GAAGd,WAAW;EAC/B,OAAOkB,IAAI;AACf;AAEA,SAASI,gBAAgB,CAAC3C,QAAa,EAAE;EACrC,IAAIA,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;IAC1C,MAAMV,cAAc,CAAC,KAAK,EAAE;MACxBU,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;EACA,IAAIA,QAAQ,IAAIA,QAAQ,CAACmD,MAAM,GAAGtD,uBAAuB,EAAE;IACvD,MAAMR,UAAU,CAAC,KAAK,EAAE;MACpB+D,aAAa,EAAEvD,uBAAuB;MACtCG,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/flutter/index.js b/dist/es/plugins/flutter/index.js index 1d75606c48d..1bb8b3eeb35 100644 --- a/dist/es/plugins/flutter/index.js +++ b/dist/es/plugins/flutter/index.js @@ -1,31 +1,45 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; export function setFlutterRxDatabaseConnector(createDB) { - process.init = function (databaseName) { - try { - return Promise.resolve(createDB(databaseName)).then(function (db) { - db.eventBulks$.subscribe(function (eventBulk) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - sendRxDBEvent(JSON.stringify(eventBulk)); - }); - process.db = db; - var collections = []; - Object.entries(db.collections).forEach(function (_ref) { - var collectionName = _ref[0], - collection = _ref[1]; - collections.push({ - name: collectionName, - primaryKey: collection.schema.primaryPath - }); - }); - return { - databaseName: databaseName, - collections: collections - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; + process.init = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(databaseName) { + var db, collections; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return createDB(databaseName); + case 2: + db = _context.sent; + db.eventBulks$.subscribe(function (eventBulk) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + sendRxDBEvent(JSON.stringify(eventBulk)); + }); + process.db = db; + collections = []; + Object.entries(db.collections).forEach(function (_ref2) { + var collectionName = _ref2[0], + collection = _ref2[1]; + collections.push({ + name: collectionName, + primaryKey: collection.schema.primaryPath + }); + }); + return _context.abrupt("return", { + databaseName: databaseName, + collections: collections + }); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); } /** @@ -34,38 +48,59 @@ export function setFlutterRxDatabaseConnector(createDB) { */ export function getLokijsAdapterFlutter() { var ret = { - loadDatabase: function loadDatabase(databaseName, callback) { - try { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - return Promise.resolve(readKeyValue(databaseName)).then(function (serializedDb) { - var success = true; - if (success) { - callback(serializedDb); - } else { - callback(new Error('There was a problem loading the database')); + loadDatabase: function () { + var _loadDatabase = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(databaseName, callback) { + var serializedDb, success; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return readKeyValue(databaseName); + case 2: + serializedDb = _context2.sent; + success = true; + if (success) { + callback(serializedDb); + } else { + callback(new Error('There was a problem loading the database')); + } + case 5: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); + }, _callee2); + })); + function loadDatabase(_x2, _x3) { + return _loadDatabase.apply(this, arguments); } - }, - saveDatabase: function saveDatabase(databaseName, dbstring, callback) { - try { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - return Promise.resolve(persistKeyValue(databaseName, dbstring)).then(function () { - var success = true; // make your own determinations - if (success) { - callback(null); - } else { - callback(new Error('An error was encountered loading " + dbname + " database.')); + return loadDatabase; + }(), + saveDatabase: function () { + var _saveDatabase = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(databaseName, dbstring, callback) { + var success; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return persistKeyValue(databaseName, dbstring); + case 2: + success = true; // make your own determinations + if (success) { + callback(null); + } else { + callback(new Error('An error was encountered loading " + dbname + " database.')); + } + case 4: + case "end": + return _context3.stop(); } - }); - } catch (e) { - return Promise.reject(e); + }, _callee3); + })); + function saveDatabase(_x4, _x5, _x6) { + return _saveDatabase.apply(this, arguments); } - } + return saveDatabase; + }() }; return ret; } diff --git a/dist/es/plugins/flutter/index.js.map b/dist/es/plugins/flutter/index.js.map index b09db57ff39..f9bc7c94b7d 100644 --- a/dist/es/plugins/flutter/index.js.map +++ b/dist/es/plugins/flutter/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["setFlutterRxDatabaseConnector","createDB","process","init","databaseName","db","eventBulks$","subscribe","eventBulk","sendRxDBEvent","JSON","stringify","collections","Object","entries","forEach","collectionName","collection","push","name","primaryKey","schema","primaryPath","getLokijsAdapterFlutter","ret","loadDatabase","callback","readKeyValue","serializedDb","success","Error","saveDatabase","dbstring","persistKeyValue"],"sources":["../../../../src/plugins/flutter/index.ts"],"sourcesContent":["import type {\n RxDatabase\n} from '../../types';\n\nexport type CreateRxDatabaseFunctionType = (databaseName: string) => Promise;\n\nexport function setFlutterRxDatabaseConnector(\n createDB: CreateRxDatabaseFunctionType\n) {\n (process as any).init = async (databaseName: string) => {\n const db = await createDB(databaseName);\n db.eventBulks$.subscribe(eventBulk => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sendRxDBEvent(JSON.stringify(eventBulk));\n });\n (process as any).db = db;\n const collections: { name: string; primaryKey: string; }[] = [];\n Object.entries(db.collections).forEach(([collectionName, collection]) => {\n collections.push({\n name: collectionName,\n primaryKey: collection.schema.primaryPath\n });\n });\n return {\n databaseName,\n collections\n };\n };\n}\n\n/**\n * Create a simple lokijs adapter so that we can persist string via flutter\n * @link https://github.com/techfort/LokiJS/blob/master/tutorials/Persistence%20Adapters.md#creating-your-own-basic-persistence-adapter\n */\nexport function getLokijsAdapterFlutter() {\n const ret = {\n async loadDatabase(databaseName: string, callback: (v: string | Error) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const serializedDb: string = await readKeyValue(databaseName);\n\n const success = true;\n if (success) {\n callback(serializedDb);\n } else {\n callback(new Error('There was a problem loading the database'));\n }\n },\n async saveDatabase(databaseName: string, dbstring: string, callback: (v: string | Error | null) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n await persistKeyValue(databaseName, dbstring);\n\n const success = true; // make your own determinations\n if (success) {\n callback(null);\n } else {\n callback(new Error('An error was encountered loading \" + dbname + \" database.'));\n }\n }\n };\n return ret;\n}\n"],"mappings":"AAMA,OAAO,SAASA,6BAA6B,CACzCC,QAAsC,EACxC;EACGC,OAAO,CAASC,IAAI,aAAUC,YAAoB;IAAA,IAAK;MAAA,uBACnCH,QAAQ,CAACG,YAAY,CAAC,iBAAjCC,EAAE;QACRA,EAAE,CAACC,WAAW,CAACC,SAAS,CAAC,UAAAC,SAAS,EAAI;UAClC;UACA;UACAC,aAAa,CAACC,IAAI,CAACC,SAAS,CAACH,SAAS,CAAC,CAAC;QAC5C,CAAC,CAAC;QACDN,OAAO,CAASG,EAAE,GAAGA,EAAE;QACxB,IAAMO,WAAoD,GAAG,EAAE;QAC/DC,MAAM,CAACC,OAAO,CAACT,EAAE,CAACO,WAAW,CAAC,CAACG,OAAO,CAAC,gBAAkC;UAAA,IAAhCC,cAAc;YAAEC,UAAU;UAC/DL,WAAW,CAACM,IAAI,CAAC;YACbC,IAAI,EAAEH,cAAc;YACpBI,UAAU,EAAEH,UAAU,CAACI,MAAM,CAACC;UAClC,CAAC,CAAC;QACN,CAAC,CAAC;QACF,OAAO;UACHlB,YAAY,EAAZA,YAAY;UACZQ,WAAW,EAAXA;QACJ,CAAC;MAAC;IACN,CAAC;MAAA;IAAA;EAAA;AACL;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASW,uBAAuB,GAAG;EACtC,IAAMC,GAAG,GAAG;IACFC,YAAY,wBAACrB,YAAoB,EAAEsB,QAAmC;MAAA,IAAE;QAC1E;QACA;QAAA,uBACmCC,YAAY,CAACvB,YAAY,CAAC,iBAAvDwB,YAAoB;UAE1B,IAAMC,OAAO,GAAG,IAAI;UAAC,IACjBA,OAAO;YACPH,QAAQ,CAACE,YAAY,CAAC;UAAC;YAEvBF,QAAQ,CAAC,IAAII,KAAK,CAAC,0CAA0C,CAAC,CAAC;UAAC;QAAA;MAExE,CAAC;QAAA;MAAA;IAAA;IACKC,YAAY,wBAAC3B,YAAoB,EAAE4B,QAAgB,EAAEN,QAA0C;MAAA,IAAE;QACnG;QACA;QAAA,uBACMO,eAAe,CAAC7B,YAAY,EAAE4B,QAAQ,CAAC;UAE7C,IAAMH,OAAO,GAAG,IAAI,CAAC,CAAE;UAAA,IACnBA,OAAO;YACPH,QAAQ,CAAC,IAAI,CAAC;UAAC;YAEfA,QAAQ,CAAC,IAAII,KAAK,CAAC,2DAA2D,CAAC,CAAC;UAAC;QAAA;MAEzF,CAAC;QAAA;MAAA;IAAA;EACL,CAAC;EACD,OAAON,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"index.js","names":["setFlutterRxDatabaseConnector","createDB","process","init","databaseName","db","eventBulks$","subscribe","eventBulk","sendRxDBEvent","JSON","stringify","collections","Object","entries","forEach","collectionName","collection","push","name","primaryKey","schema","primaryPath","getLokijsAdapterFlutter","ret","loadDatabase","callback","readKeyValue","serializedDb","success","Error","saveDatabase","dbstring","persistKeyValue"],"sources":["../../../../src/plugins/flutter/index.ts"],"sourcesContent":["import type {\n RxDatabase\n} from '../../types';\n\nexport type CreateRxDatabaseFunctionType = (databaseName: string) => Promise;\n\nexport function setFlutterRxDatabaseConnector(\n createDB: CreateRxDatabaseFunctionType\n) {\n (process as any).init = async (databaseName: string) => {\n const db = await createDB(databaseName);\n db.eventBulks$.subscribe(eventBulk => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sendRxDBEvent(JSON.stringify(eventBulk));\n });\n (process as any).db = db;\n const collections: { name: string; primaryKey: string; }[] = [];\n Object.entries(db.collections).forEach(([collectionName, collection]) => {\n collections.push({\n name: collectionName,\n primaryKey: collection.schema.primaryPath\n });\n });\n return {\n databaseName,\n collections\n };\n };\n}\n\n/**\n * Create a simple lokijs adapter so that we can persist string via flutter\n * @link https://github.com/techfort/LokiJS/blob/master/tutorials/Persistence%20Adapters.md#creating-your-own-basic-persistence-adapter\n */\nexport function getLokijsAdapterFlutter() {\n const ret = {\n async loadDatabase(databaseName: string, callback: (v: string | Error) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const serializedDb: string = await readKeyValue(databaseName);\n\n const success = true;\n if (success) {\n callback(serializedDb);\n } else {\n callback(new Error('There was a problem loading the database'));\n }\n },\n async saveDatabase(databaseName: string, dbstring: string, callback: (v: string | Error | null) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n await persistKeyValue(databaseName, dbstring);\n\n const success = true; // make your own determinations\n if (success) {\n callback(null);\n } else {\n callback(new Error('An error was encountered loading \" + dbname + \" database.'));\n }\n }\n };\n return ret;\n}\n"],"mappings":";;AAMA,OAAO,SAASA,6BAA6B,CACzCC,QAAsC,EACxC;EACGC,OAAO,CAASC,IAAI;IAAA,oEAAG,iBAAOC,YAAoB;M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AA;UAAA;YAAA;cAAA;cAAA,OAG3FO,eAAe,CAAC7B,YAAY,EAAE4B,QAAQ,CAAC;YAAA;cAEvCH,OAAO,GAAG,IAAI,EAAG;cACvB,IAAIA,OAAO,EAAE;gBACTH,QAAQ,CAAC,IAAI,CAAC;cAClB,CAAC,MAAM;gBACHA,QAAQ,CAAC,IAAII,KAAK,CAAC,2DAA2D,CAAC,CAAC;cACpF;YAAC;YAAA;cAAA;UAAA;QAAA;MAAA;MAAA;QAAA;MAAA;MAAA;IAAA;EAET,CAAC;EACD,OAAON,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/foundationdb-helpers.js.map b/dist/es/plugins/foundationdb/foundationdb-helpers.js.map deleted file mode 100644 index 69841bde3b6..00000000000 --- a/dist/es/plugins/foundationdb/foundationdb-helpers.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"foundationdb-helpers.js","names":["getFoundationDBIndexName","index","join","CLEANUP_INDEX"],"sources":["../../../../src/plugins/foundationdb/foundationdb-helpers.ts"],"sourcesContent":["export function getFoundationDBIndexName(index: string[]): string {\n return index.join('|');\n}\nexport const CLEANUP_INDEX: string[] = ['_deleted', '_meta.lwt'];\n"],"mappings":"AAAA,OAAO,SAASA,wBAAwB,CAACC,KAAe,EAAU;EAC9D,OAAOA,KAAK,CAACC,IAAI,CAAC,GAAG,CAAC;AAC1B;AACA,OAAO,IAAMC,aAAuB,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/foundationdb-query.js b/dist/es/plugins/foundationdb/foundationdb-query.js deleted file mode 100644 index 37fba4fbdd1..00000000000 --- a/dist/es/plugins/foundationdb/foundationdb-query.js +++ /dev/null @@ -1,242 +0,0 @@ -import { getStartIndexStringFromLowerBound, getStartIndexStringFromUpperBound } from '../../custom-index'; -import { ensureNotFalsy } from '../../util'; -import { RxStorageDexieStatics } from '../dexie'; -import { getFoundationDBIndexName } from './foundationdb-helpers'; -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -export var queryFoundationDB = function queryFoundationDB(instance, preparedQuery) { - try { - var queryPlan = preparedQuery.queryPlan; - var query = preparedQuery.query; - var skip = query.skip ? query.skip : 0; - var limit = query.limit ? query.limit : Infinity; - var skipPlusLimit = skip + limit; - var queryPlanFields = queryPlan.index; - var mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields; - var queryMatcher = false; - if (!queryPlan.selectorSatisfiedByIndex) { - queryMatcher = RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); - } - return Promise.resolve(instance.internals.dbsPromise).then(function (dbs) { - var indexForName = queryPlanFields.slice(0); - indexForName.unshift('_deleted'); - var indexName = getFoundationDBIndexName(indexForName); - var indexDB = ensureNotFalsy(dbs.indexes[indexName]).db; - var lowerBound = queryPlan.startKeys; - lowerBound = [false].concat(lowerBound); - var lowerBoundString = getStartIndexStringFromLowerBound(instance.schema, indexForName, lowerBound, queryPlan.inclusiveStart); - var upperBound = queryPlan.endKeys; - upperBound = [false].concat(upperBound); - var upperBoundString = getStartIndexStringFromUpperBound(instance.schema, indexForName, upperBound, queryPlan.inclusiveEnd); - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var _interrupt = false; - var innerResult = []; - var indexTx = tx.at(indexDB.subspace); - var mainTx = tx.at(dbs.main.subspace); - var range = indexTx.getRangeBatch(lowerBoundString, upperBoundString, { - // TODO these options seem to be broken in the foundationdb node bindings - // limit: instance.settings.batchSize, - // streamingMode: StreamingMode.Exact - }); - var done = false; - var _temp = _for(function () { - return !_interrupt && !done; - }, void 0, function () { - return Promise.resolve(range.next()).then(function (next) { - if (next.done) { - done = true; - _interrupt = true; - return; - } - var docIds = next.value.map(function (row) { - return row[1]; - }); - return Promise.resolve(Promise.all(docIds.map(function (docId) { - return mainTx.get(docId); - }))).then(function (docsData) { - docsData.forEach(function (docData) { - if (!done) { - if (!queryMatcher || queryMatcher(docData)) { - innerResult.push(docData); - } - } - if (!mustManuallyResort && innerResult.length === skipPlusLimit) { - done = true; - range["return"](); - } - }); - }); - }); - }); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return innerResult; - }) : innerResult); - } catch (e) { - return Promise.reject(e); - } - })).then(function (result) { - if (mustManuallyResort) { - var sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); - result = result.sort(sortComparator); - } - - // apply skip and limit boundaries. - result = result.slice(skip, skipPlusLimit); - return { - documents: result - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -//# sourceMappingURL=foundationdb-query.js.map \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/foundationdb-query.js.map b/dist/es/plugins/foundationdb/foundationdb-query.js.map deleted file mode 100644 index cd19f30825a..00000000000 --- a/dist/es/plugins/foundationdb/foundationdb-query.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"foundationdb-query.js","names":["getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","ensureNotFalsy","RxStorageDexieStatics","getFoundationDBIndexName","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","queryFoundationDB","instance","preparedQuery","queryPlan","query","skip","limit","Infinity","skipPlusLimit","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","schema","internals","dbsPromise","dbs","indexForName","slice","unshift","indexName","indexDB","indexes","db","lowerBound","startKeys","concat","lowerBoundString","inclusiveStart","upperBound","endKeys","upperBoundString","inclusiveEnd","root","doTransaction","tx","innerResult","indexTx","at","subspace","mainTx","main","range","getRangeBatch","done","next","docIds","map","row","Promise","all","docId","get","docsData","forEach","docData","push","length","sortComparator","getSortComparator","sort","documents"],"sources":["../../../../src/plugins/foundationdb/foundationdb-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport type {\n RxDocumentData,\n RxStorageQueryResult\n} from '../../types';\nimport { ensureNotFalsy } from '../../util';\nimport { RxStorageDexieStatics } from '../dexie';\nimport { getFoundationDBIndexName } from './foundationdb-helpers';\nimport type {\n FoundationDBPreparedQuery\n} from './foundationdb-types';\nimport { RxStorageInstanceFoundationDB } from './rx-storage-instance-foundationdb';\n\nexport async function queryFoundationDB(\n instance: RxStorageInstanceFoundationDB,\n preparedQuery: FoundationDBPreparedQuery\n): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const dbs = await instance.internals.dbsPromise;\n\n\n const indexForName = queryPlanFields.slice(0);\n indexForName.unshift('_deleted');\n const indexName = getFoundationDBIndexName(indexForName);\n const indexDB = ensureNotFalsy(dbs.indexes[indexName]).db;\n\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n instance.schema,\n indexForName,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n instance.schema,\n indexForName,\n upperBound,\n queryPlan.inclusiveEnd\n );\n let result = await dbs.root.doTransaction(async (tx: any) => {\n const innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexDB.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n\n const range = indexTx.getRangeBatch(\n lowerBoundString,\n upperBoundString,\n {\n // TODO these options seem to be broken in the foundationdb node bindings\n // limit: instance.settings.batchSize,\n // streamingMode: StreamingMode.Exact\n }\n );\n let done = false;\n while (!done) {\n const next = await range.next();\n if (next.done) {\n done = true;\n break;\n }\n const docIds = next.value.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n docsData.forEach((docData) => {\n if (!done) {\n if (!queryMatcher || queryMatcher(docData)) {\n innerResult.push(docData);\n }\n }\n if (\n !mustManuallyResort &&\n innerResult.length === skipPlusLimit\n ) {\n done = true;\n range.return();\n }\n });\n }\n return innerResult;\n });\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n result = result.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n result = result.slice(skip, skipPlusLimit);\n\n return {\n documents: result\n };\n}\n"],"mappings":"AACA,SACIA,iCAAiC,EACjCC,iCAAiC,QAC9B,oBAAoB;AAK3B,SAASC,cAAc,QAAQ,YAAY;AAC3C,SAASC,qBAAqB,QAAQ,UAAU;AAChD,SAASC,wBAAwB,QAAQ,wBAAwB;AA4B1D,iBAAiBC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;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AAkB,IACnB4B,WAAW,CAACqB,MAAM,KAAKpD,aAAa,EACtC;oBACEuC,IAAI,GAAG,IAAI;oBACXF,KAAK,UAAO,EAAE;kBAClB;gBACJ,CAAC,CAAC;cAAC;YAAA;UACP,CAAC;UAAA;YACD,OAAON,WAAW;UAAC,KAAZA,WAAW;QACtB,CAAC;UAAA;QAAA;MAAA,EAAC,iBAvCEtD,MAAM;QAwCV,IAAI0B,kBAAkB,EAAE;UACpB,IAAMkD,cAAc,GAAG1F,qBAAqB,CAAC2F,iBAAiB,CAAC7D,QAAQ,CAACe,MAAM,EAAEd,aAAa,CAAC;UAC9FjB,MAAM,GAAGA,MAAM,CAAC8E,IAAI,CAACF,cAAc,CAAC;QACxC;;QAEA;QACA5E,MAAM,GAAGA,MAAM,CAACoC,KAAK,CAAChB,IAAI,EAAEG,aAAa,CAAC;QAE1C,OAAO;UACHwD,SAAS,EAAE/E;QACf,CAAC;MAAC;IAAA;EACN,CAAC;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/foundationdb-types.js.map b/dist/es/plugins/foundationdb/foundationdb-types.js.map deleted file mode 100644 index 229cc5bf2ef..00000000000 --- a/dist/es/plugins/foundationdb/foundationdb-types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"foundationdb-types.js","names":[],"sources":["../../../../src/plugins/foundationdb/foundationdb-types.ts"],"sourcesContent":["/* eslint-disable no-unused-vars */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type {\n DexiePreparedQuery,\n EventBulk,\n RxAttachmentWriteData,\n RxDocumentData,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types';\nexport type RxStorageFoundationDBSettings = {\n /**\n * Version of the API of the foundationDB server.\n */\n apiVersion: number;\n /**\n * Path to the foundationDB cluster file\n * like '/path/to/fdb.cluster'\n * (optional)\n */\n clusterFile?: string;\n batchSize?: number;\n};\nexport type RxStorageFoundationDBInstanceCreationOptions = {\n // can be overwritte per instance\n batchSize?: number;\n};\n\n/**\n * TODO atm we cannot import types from 'foundationdb'\n * because 'foundationdb' is an optional peer dependency\n * this is NOT also in the devDependencies.\n * This is because it requires to install the foundationdb client cli\n * which would mean everyone that wants to develop RxDB must have this installed manually.\n */\n// import {\n// open as foundationDBOpen,\n// Database,\n// Transaction\n// } from 'foundationdb';\n\nexport type FoundationDBIndexMeta = {\n indexName: string;\n index: string[];\n getIndexableString: (doc: RxDocumentData) => string;\n db: FoundationDBDatabase;\n};\n\nexport type FoundationDBConnection = any; // ReturnType;\nexport type FoundationDBDatabase = any; // Database;\nexport type FoundationDBTransaction = any; // Transaction, any>;\nexport type FoundationDBStorageInternals = {\n connection: FoundationDBConnection;\n dbsPromise: Promise<{\n root: FoundationDBDatabase;\n main: FoundationDBDatabase;\n attachments: FoundationDBDatabase;\n events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>>;\n indexes: {\n [indexName: string]: FoundationDBIndexMeta;\n };\n }>;\n};\nexport type RxStorageFoundationDB = RxStorage, RxStorageFoundationDBInstanceCreationOptions> & {\n};\n\n\nexport type FoundationDBPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/index.js.map b/dist/es/plugins/foundationdb/index.js.map deleted file mode 100644 index dee08d7354d..00000000000 --- a/dist/es/plugins/foundationdb/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["ensureRxStorageInstanceParamsAreCorrect","RxStorageDexieStatics","createFoundationDBStorageInstance","versionSet","getRxStorageFoundationDB","settings","apiVersion","Error","require","setAPIVersion","storage","name","statics","createStorageInstance","params","useSettings","Object","assign","options","batchSize"],"sources":["../../../../src/plugins/foundationdb/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type {\n RxStorageInstanceCreationParams\n} from '../../types';\nimport { RxStorageDexieStatics } from '../dexie/dexie-statics';\nimport type {\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n\nimport {\n createFoundationDBStorageInstance,\n RxStorageInstanceFoundationDB\n} from './rx-storage-instance-foundationdb';\n\n\nlet versionSet: undefined | number;\n\nexport function getRxStorageFoundationDB(\n settings: RxStorageFoundationDBSettings\n): RxStorageFoundationDB {\n if (versionSet && versionSet !== settings.apiVersion) {\n throw new Error('foundationdb already initialized with api version ' + versionSet);\n } else if (!versionSet) {\n versionSet = settings.apiVersion;\n const { setAPIVersion } = require('foundationdb');\n setAPIVersion(settings.apiVersion);\n }\n\n\n const storage: RxStorageFoundationDB = {\n name: 'foundationdb',\n statics: RxStorageDexieStatics,\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n if (!useSettings.batchSize) {\n useSettings.batchSize = 50;\n }\n return createFoundationDBStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './foundationdb-types';\nexport * from './foundationdb-helpers';\n"],"mappings":"AAAA,SAASA,uCAAuC,QAAQ,yBAAyB;AAIjF,SAASC,qBAAqB,QAAQ,wBAAwB;AAO9D,SACIC,iCAAiC,QAE9B,oCAAoC;AAG3C,IAAIC,UAA8B;AAElC,OAAO,SAASC,wBAAwB,CACpCC,QAAuC,EAClB;EACrB,IAAIF,UAAU,IAAIA,UAAU,KAAKE,QAAQ,CAACC,UAAU,EAAE;IAClD,MAAM,IAAIC,KAAK,CAAC,oDAAoD,GAAGJ,UAAU,CAAC;EACtF,CAAC,MAAM,IAAI,CAACA,UAAU,EAAE;IACpBA,UAAU,GAAGE,QAAQ,CAACC,UAAU;IAChC,eAA0BE,OAAO,CAAC,cAAc,CAAC;MAAzCC,aAAa,YAAbA,aAAa;IACrBA,aAAa,CAACJ,QAAQ,CAACC,UAAU,CAAC;EACtC;EAGA,IAAMI,OAA8B,GAAG;IACnCC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAEX,qBAAqB;IAC9BY,qBAAqB,iCACjBC,MAAgG,EAC/C;MACjDd,uCAAuC,CAACc,MAAM,CAAC;MAC/C,IAAMC,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFZ,QAAQ,EACRS,MAAM,CAACI,OAAO,CACjB;MACD,IAAI,CAACH,WAAW,CAACI,SAAS,EAAE;QACxBJ,WAAW,CAACI,SAAS,GAAG,EAAE;MAC9B;MACA,OAAOjB,iCAAiC,CAAC,IAAI,EAAEY,MAAM,EAAEC,WAAW,CAAC;IACvE;EACJ,CAAC;EAED,OAAOL,OAAO;AAClB;AAGA,cAAc,sBAAsB;AACpC,cAAc,wBAAwB"} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/rx-storage-instance-foundationdb.js b/dist/es/plugins/foundationdb/rx-storage-instance-foundationdb.js deleted file mode 100644 index 85fc82b71b2..00000000000 --- a/dist/es/plugins/foundationdb/rx-storage-instance-foundationdb.js +++ /dev/null @@ -1,418 +0,0 @@ -import { Subject } from 'rxjs'; -import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; -// import { -// open as foundationDBOpen, -// directory as foundationDBDirectory, -// encoders as foundationDBEncoders, -// keySelector as foundationDBKeySelector, -// StreamingMode as foundationDBStreamingMode -// } from 'foundationdb'; -import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; -import { CLEANUP_INDEX, getFoundationDBIndexName } from './foundationdb-helpers'; -import { getIndexableStringMonad, getStartIndexStringFromLowerBound, getStartIndexStringFromUpperBound } from '../../custom-index'; -import { ensureNotFalsy, lastOfArray, now, PROMISE_RESOLVE_VOID } from '../../util'; -import { queryFoundationDB } from './foundationdb-query'; -import { INDEX_MAX } from '../../query-planner'; -import { attachmentMapKey } from '../memory'; -export var RxStorageInstanceFoundationDB = /*#__PURE__*/function () { - function RxStorageInstanceFoundationDB(storage, databaseName, collectionName, schema, internals, options, settings) { - this.closed = false; - this.changes$ = new Subject(); - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - this.settings = settings; - this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); - } - var _proto = RxStorageInstanceFoundationDB.prototype; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this = this; - return Promise.resolve(_this.internals.dbsPromise).then(function (dbs) { - var categorized = null; - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var ret = { - success: {}, - error: {} - }; - var ids = documentWrites.map(function (row) { - return row.document[_this.primaryPath]; - }); - var mainTx = tx.at(dbs.main.subspace); - var attachmentTx = tx.at(dbs.attachments.subspace); - var docsInDB = new Map(); - /** - * TODO this might be faster if fdb - * any time adds a bulk-fetch-by-key method. - */ - return Promise.resolve(Promise.all(ids.map(function (id) { - try { - return Promise.resolve(mainTx.get(id)).then(function (doc) { - docsInDB.set(id, doc); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - categorized = categorizeBulkWriteRows(_this, _this.primaryPath, docsInDB, documentWrites, context); - ret.error = categorized.errors; - - // INSERTS - categorized.bulkInsertDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this.primaryPath]; - ret.success[docId] = writeRow.document; - - // insert document data - mainTx.set(docId, writeRow.document); - - // insert secondary indexes - Object.values(dbs.indexes).forEach(function (indexMeta) { - var indexString = indexMeta.getIndexableString(writeRow.document); - var indexTx = tx.at(indexMeta.db.subspace); - indexTx.set(indexString, docId); - }); - }); - // UPDATES - categorized.bulkUpdateDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this.primaryPath]; - - // overwrite document data - mainTx.set(docId, writeRow.document); - - // update secondary indexes - Object.values(dbs.indexes).forEach(function (indexMeta) { - var oldIndexString = indexMeta.getIndexableString(ensureNotFalsy(writeRow.previous)); - var newIndexString = indexMeta.getIndexableString(writeRow.document); - if (oldIndexString !== newIndexString) { - var indexTx = tx.at(indexMeta.db.subspace); - indexTx["delete"](oldIndexString); - indexTx.set(newIndexString, docId); - } - }); - ret.success[docId] = writeRow.document; - }); - - // attachments - categorized.attachmentsAdd.forEach(function (attachment) { - attachmentTx.set(attachmentMapKey(attachment.documentId, attachment.attachmentId), attachment.attachmentData); - }); - categorized.attachmentsUpdate.forEach(function (attachment) { - attachmentTx.set(attachmentMapKey(attachment.documentId, attachment.attachmentId), attachment.attachmentData); - }); - categorized.attachmentsRemove.forEach(function (attachment) { - attachmentTx["delete"](attachmentMapKey(attachment.documentId, attachment.attachmentId)); - }); - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function (result) { - /** - * The events must be emitted AFTER the transaction - * has finished. - * Otherwise an observable changestream might cause a read - * to a document that does not already exist outside of the transaction. - */ - if (ensureNotFalsy(categorized).eventBulk.events.length > 0) { - var lastState = getNewestOfDocumentStates(_this.primaryPath, Object.values(result.success)); - ensureNotFalsy(categorized).eventBulk.checkpoint = { - id: lastState[_this.primaryPath], - lwt: lastState._meta.lwt - }; - _this.changes$.next(ensureNotFalsy(categorized).eventBulk); - } - return result; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, withDeleted) { - try { - var _this2 = this; - return Promise.resolve(_this2.internals.dbsPromise).then(function (dbs) { - return dbs.main.doTransaction(function (tx) { - try { - var ret = {}; - return Promise.resolve(Promise.all(ids.map(function (docId) { - try { - return Promise.resolve(tx.get(docId)).then(function (docInDb) { - if (docInDb && (!docInDb._deleted || withDeleted)) { - ret[docId] = docInDb; - } - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - return queryFoundationDB(this, preparedQuery); - }; - _proto.count = function count(preparedQuery) { - try { - var _this3 = this; - /** - * At this point in time (end 2022), FoundationDB does not support - * range counts. So we have to run a normal query and use the result set length. - * @link https://github.com/apple/foundationdb/issues/5981 - */ - return Promise.resolve(_this3.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(documentId, attachmentId) { - try { - var _this4 = this; - return Promise.resolve(_this4.internals.dbsPromise).then(function (dbs) { - return Promise.resolve(dbs.attachments.get(attachmentMapKey(documentId, attachmentId))).then(function (attachment) { - return attachment.data; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _this5 = this; - var _require = require('foundationdb'), - keySelector = _require.keySelector, - StreamingMode = _require.StreamingMode; - return Promise.resolve(_this5.internals.dbsPromise).then(function (dbs) { - var index = ['_meta.lwt', _this5.primaryPath]; - var indexName = getFoundationDBIndexName(index); - var indexMeta = dbs.indexes[indexName]; - var lowerBoundString = ''; - if (checkpoint) { - var _checkpointPartialDoc; - var checkpointPartialDoc = (_checkpointPartialDoc = {}, _checkpointPartialDoc[_this5.primaryPath] = checkpoint.id, _checkpointPartialDoc._meta = { - lwt: checkpoint.lwt - }, _checkpointPartialDoc); - lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc); - } - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var innerResult = []; - var indexTx = tx.at(indexMeta.db.subspace); - var mainTx = tx.at(dbs.main.subspace); - return Promise.resolve(indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), INDEX_MAX, { - limit: limit, - streamingMode: StreamingMode.Exact - })).then(function (range) { - var docIds = range.map(function (row) { - return row[1]; - }); - return Promise.resolve(Promise.all(docIds.map(function (docId) { - return mainTx.get(docId); - }))).then(function (docsData) { - innerResult = innerResult.concat(docsData); - return innerResult; - }); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function (result) { - var lastDoc = lastOfArray(result); - return { - documents: result, - checkpoint: lastDoc ? { - id: lastDoc[_this5.primaryPath], - lwt: lastDoc._meta.lwt - } : checkpoint ? checkpoint : { - id: '', - lwt: 0 - } - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.changeStream = function changeStream() { - return this.changes$.asObservable(); - }; - _proto.remove = function remove() { - try { - var _this6 = this; - return Promise.resolve(_this6.internals.dbsPromise).then(function (dbs) { - return Promise.resolve(dbs.root.doTransaction(function (tx) { - tx.clearRange('', INDEX_MAX); - return PROMISE_RESOLVE_VOID; - })).then(function () { - return _this6.close(); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.cleanup = function cleanup(minimumDeletedTime) { - try { - var _this7 = this; - var _require2 = require('foundationdb'), - keySelector = _require2.keySelector, - StreamingMode = _require2.StreamingMode; - var maxDeletionTime = now() - minimumDeletedTime; - return Promise.resolve(_this7.internals.dbsPromise).then(function (dbs) { - var index = CLEANUP_INDEX; - var indexName = getFoundationDBIndexName(index); - var indexMeta = dbs.indexes[indexName]; - var lowerBoundString = getStartIndexStringFromLowerBound(_this7.schema, index, [true, - /** - * Do not use 0 here, - * because 1 is the minimum value for _meta.lwt - */ - 1], false); - var upperBoundString = getStartIndexStringFromUpperBound(_this7.schema, index, [true, maxDeletionTime], true); - var noMoreUndeleted = true; - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var batchSize = ensureNotFalsy(_this7.settings.batchSize); - var indexTx = tx.at(indexMeta.db.subspace); - var mainTx = tx.at(dbs.main.subspace); - return Promise.resolve(indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), upperBoundString, { - limit: batchSize + 1, - // get one more extra to detect what to return from cleanup() - streamingMode: StreamingMode.Exact - })).then(function (range) { - if (range.length > batchSize) { - noMoreUndeleted = false; - range.pop(); - } - var docIds = range.map(function (row) { - return row[1]; - }); - return Promise.resolve(Promise.all(docIds.map(function (docId) { - return mainTx.get(docId); - }))).then(function (docsData) { - Object.values(dbs.indexes).forEach(function (indexMetaInner) { - var subIndexDB = tx.at(indexMetaInner.db.subspace); - docsData.forEach(function (docData) { - var indexString = indexMetaInner.getIndexableString(docData); - subIndexDB["delete"](indexString); - }); - }); - docIds.forEach(function (id) { - return mainTx["delete"](id); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return noMoreUndeleted; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new Subject().asObservable(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return PROMISE_RESOLVE_VOID; - }; - _proto.close = function close() { - try { - var _this8 = this; - if (_this8.closed) { - return Promise.reject(new Error('already closed')); - } - _this8.closed = true; - _this8.changes$.complete(); - return Promise.resolve(_this8.internals.dbsPromise).then(function (dbs) { - dbs.root.close(); - - // TODO shouldn't we close the index databases? - // Object.values(dbs.indexes).forEach(db => db.close()); - }); - } catch (e) { - return Promise.reject(e); - } - }; - return RxStorageInstanceFoundationDB; -}(); -export function createFoundationDBStorageInstance(storage, params, settings) { - var primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey); - var _require3 = require('foundationdb'), - open = _require3.open, - directory = _require3.directory, - encoders = _require3.encoders; - var connection = open(settings.clusterFile); - var dbsPromise = function () { - try { - return Promise.resolve(directory.createOrOpen(connection, 'rxdb')).then(function (dir) { - var root = connection.at(dir).at(params.databaseName + '.').at(params.collectionName + '.').at(params.schema.version + '.'); - var main = root.at('main.').withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples - .withValueEncoding(encoders.json); // and values using JSON - - var events = root.at('events.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); - var attachments = root.at('attachments.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); - var indexDBs = {}; - var useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : []; - useIndexes.push([primaryPath]); - var useIndexesFinal = useIndexes.map(function (index) { - var indexAr = Array.isArray(index) ? index.slice(0) : [index]; - indexAr.unshift('_deleted'); - return indexAr; - }); - // used for `getChangedDocumentsSince()` - useIndexesFinal.push(['_meta.lwt', primaryPath]); - useIndexesFinal.push(CLEANUP_INDEX); - useIndexesFinal.forEach(function (indexAr) { - var indexName = getFoundationDBIndexName(indexAr); - var indexDB = root.at(indexName + '.').withKeyEncoding(encoders.string).withValueEncoding(encoders.string); - indexDBs[indexName] = { - indexName: indexName, - db: indexDB, - getIndexableString: getIndexableStringMonad(params.schema, indexAr), - index: indexAr - }; - }); - return { - root: root, - main: main, - events: events, - attachments: attachments, - indexes: indexDBs - }; - }); - } catch (e) { - return Promise.reject(e); - } - }(); - var internals = { - connection: connection, - dbsPromise: dbsPromise - }; - var instance = new RxStorageInstanceFoundationDB(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); - return Promise.resolve(instance); -} -//# sourceMappingURL=rx-storage-instance-foundationdb.js.map \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/rx-storage-instance-foundationdb.js.map b/dist/es/plugins/foundationdb/rx-storage-instance-foundationdb.js.map deleted file mode 100644 index 90446b6041a..00000000000 --- a/dist/es/plugins/foundationdb/rx-storage-instance-foundationdb.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-foundationdb.js","names":["Subject","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","CLEANUP_INDEX","getFoundationDBIndexName","getIndexableStringMonad","getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","ensureNotFalsy","lastOfArray","now","PROMISE_RESOLVE_VOID","queryFoundationDB","INDEX_MAX","attachmentMapKey","RxStorageInstanceFoundationDB","storage","databaseName","collectionName","schema","internals","options","settings","closed","changes$","primaryPath","primaryKey","bulkWrite","documentWrites","context","dbsPromise","dbs","categorized","root","doTransaction","tx","ret","success","error","ids","map","row","document","mainTx","at","main","subspace","attachmentTx","attachments","docsInDB","Map","Promise","all","id","get","doc","set","errors","bulkInsertDocs","forEach","writeRow","docId","Object","values","indexes","indexMeta","indexString","getIndexableString","indexTx","db","bulkUpdateDocs","oldIndexString","previous","newIndexString","attachmentsAdd","attachment","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","result","eventBulk","events","length","lastState","checkpoint","lwt","_meta","next","findDocumentsById","withDeleted","docInDb","_deleted","query","preparedQuery","count","documents","mode","getAttachmentData","data","getChangedDocumentsSince","limit","require","keySelector","StreamingMode","index","indexName","lowerBoundString","checkpointPartialDoc","innerResult","getRangeAll","firstGreaterThan","streamingMode","Exact","range","docIds","docsData","concat","lastDoc","changeStream","asObservable","remove","clearRange","close","cleanup","minimumDeletedTime","maxDeletionTime","upperBoundString","noMoreUndeleted","batchSize","pop","indexMetaInner","subIndexDB","docData","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","reject","Error","complete","createFoundationDBStorageInstance","params","open","directory","encoders","connection","clusterFile","createOrOpen","dir","version","withKeyEncoding","string","withValueEncoding","json","indexDBs","useIndexes","slice","push","useIndexesFinal","indexAr","Array","isArray","unshift","indexDB","instance","resolve"],"sources":["../../../../src/plugins/foundationdb/rx-storage-instance-foundationdb.ts"],"sourcesContent":["import { Observable, Subject } from 'rxjs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type {\n BulkWriteRow,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport type {\n FoundationDBDatabase,\n FoundationDBIndexMeta,\n FoundationDBPreparedQuery,\n FoundationDBStorageInternals,\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n// import {\n// open as foundationDBOpen,\n// directory as foundationDBDirectory,\n// encoders as foundationDBEncoders,\n// keySelector as foundationDBKeySelector,\n// StreamingMode as foundationDBStreamingMode\n// } from 'foundationdb';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport {\n\n CLEANUP_INDEX,\n getFoundationDBIndexName\n} from './foundationdb-helpers';\nimport {\n getIndexableStringMonad,\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport {\n ensureNotFalsy, lastOfArray, now\n , PROMISE_RESOLVE_VOID\n} from '../../util';\nimport { queryFoundationDB } from './foundationdb-query';\nimport { INDEX_MAX } from '../../query-planner';\nimport { attachmentMapKey } from '../memory';\n\nexport class RxStorageInstanceFoundationDB implements RxStorageInstance<\n RxDocType,\n FoundationDBStorageInternals,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n\n public closed = false;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n\n constructor(\n public readonly storage: RxStorageFoundationDB,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: FoundationDBStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageFoundationDBSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n const dbs = await this.internals.dbsPromise;\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n const result = await dbs.root.doTransaction(async (tx: any) => {\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const ids = documentWrites.map(row => (row.document as any)[this.primaryPath]);\n const mainTx = tx.at(dbs.main.subspace);\n const attachmentTx = tx.at(dbs.attachments.subspace);\n const docsInDB = new Map>();\n /**\n * TODO this might be faster if fdb\n * any time adds a bulk-fetch-by-key method.\n */\n await Promise.all(\n ids.map(async (id) => {\n const doc = await mainTx.get(id);\n docsInDB.set(id, doc);\n })\n );\n\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDB,\n documentWrites,\n context\n );\n\n ret.error = categorized.errors;\n\n // INSERTS\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n ret.success[docId] = writeRow.document as any;\n\n // insert document data\n mainTx.set(docId, writeRow.document);\n\n // insert secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const indexString = indexMeta.getIndexableString(writeRow.document as any);\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.set(indexString, docId);\n });\n });\n // UPDATES\n categorized.bulkUpdateDocs.forEach((writeRow: BulkWriteRow) => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n\n // overwrite document data\n mainTx.set(docId, writeRow.document);\n\n // update secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const oldIndexString = indexMeta.getIndexableString(ensureNotFalsy(writeRow.previous));\n const newIndexString = indexMeta.getIndexableString(writeRow.document as any);\n if (oldIndexString !== newIndexString) {\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.delete(oldIndexString);\n indexTx.set(newIndexString, docId);\n }\n });\n ret.success[docId] = writeRow.document as any;\n });\n\n // attachments\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentTx.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n\n return ret;\n });\n /**\n * The events must be emitted AFTER the transaction\n * has finished.\n * Otherwise an observable changestream might cause a read\n * to a document that does not already exist outside of the transaction.\n */\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(result.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n return result;\n }\n\n async findDocumentsById(ids: string[], withDeleted: boolean): Promise> {\n const dbs = await this.internals.dbsPromise;\n return dbs.main.doTransaction(async (tx: any) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n ids.map(async (docId) => {\n const docInDb = await tx.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n })\n );\n return ret;\n });\n }\n query(preparedQuery: FoundationDBPreparedQuery): Promise> {\n return queryFoundationDB(this, preparedQuery);\n }\n async count(\n preparedQuery: FoundationDBPreparedQuery\n ): Promise {\n /**\n * At this point in time (end 2022), FoundationDB does not support\n * range counts. So we have to run a normal query and use the result set length.\n * @link https://github.com/apple/foundationdb/issues/5981\n */\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n async getAttachmentData(documentId: string, attachmentId: string): Promise {\n const dbs = await this.internals.dbsPromise;\n const attachment = await dbs.attachments.get(attachmentMapKey(documentId, attachmentId));\n return attachment.data;\n }\n async getChangedDocumentsSince(limit: number, checkpoint?: RxStorageDefaultCheckpoint): Promise<{ documents: RxDocumentData[]; checkpoint: RxStorageDefaultCheckpoint; }> {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const dbs = await this.internals.dbsPromise;\n const index = [\n '_meta.lwt',\n this.primaryPath as any\n ];\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n let lowerBoundString = '';\n if (checkpoint) {\n const checkpointPartialDoc: any = {\n [this.primaryPath]: checkpoint.id,\n _meta: {\n lwt: checkpoint.lwt\n }\n };\n lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc);\n }\n const result: RxDocumentData[] = await dbs.root.doTransaction(async (tx: any) => {\n let innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n INDEX_MAX,\n {\n limit,\n streamingMode: StreamingMode.Exact\n }\n );\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(\n docIds.map((docId: string) => mainTx.get(docId))\n );\n innerResult = innerResult.concat(docsData);\n return innerResult;\n });\n const lastDoc = lastOfArray(result);\n return {\n documents: result,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n changeStream(): Observable, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async remove(): Promise {\n const dbs = await this.internals.dbsPromise;\n await dbs.root.doTransaction((tx: any) => {\n tx.clearRange('', INDEX_MAX);\n return PROMISE_RESOLVE_VOID;\n });\n return this.close();\n }\n async cleanup(minimumDeletedTime: number): Promise {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const maxDeletionTime = now() - minimumDeletedTime;\n const dbs = await this.internals.dbsPromise;\n const index = CLEANUP_INDEX;\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n /**\n * Do not use 0 here,\n * because 1 is the minimum value for _meta.lwt\n */\n 1\n ],\n false\n );\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n [\n true,\n maxDeletionTime\n ],\n true\n );\n let noMoreUndeleted: boolean = true;\n await dbs.root.doTransaction(async (tx: any) => {\n const batchSize = ensureNotFalsy(this.settings.batchSize);\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n upperBoundString,\n {\n limit: batchSize + 1, // get one more extra to detect what to return from cleanup()\n streamingMode: StreamingMode.Exact\n }\n );\n if (range.length > batchSize) {\n noMoreUndeleted = false;\n range.pop();\n }\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n\n Object\n .values(dbs.indexes)\n .forEach(indexMetaInner => {\n const subIndexDB = tx.at(indexMetaInner.db.subspace);\n docsData.forEach(docData => {\n const indexString = indexMetaInner.getIndexableString(docData);\n subIndexDB.delete(indexString);\n });\n });\n docIds.forEach((id: string) => mainTx.delete(id));\n });\n\n return noMoreUndeleted;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject().asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n\n async close() {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n\n const dbs = await this.internals.dbsPromise;\n dbs.root.close();\n\n // TODO shouldn't we close the index databases?\n // Object.values(dbs.indexes).forEach(db => db.close());\n }\n}\n\n\nexport function createFoundationDBStorageInstance(\n storage: RxStorageFoundationDB,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageFoundationDBSettings\n): Promise> {\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n const {\n open,\n directory,\n encoders\n } = require('foundationdb');\n\n const connection = open(settings.clusterFile);\n const dbsPromise = (async () => {\n const dir = await directory.createOrOpen(connection, 'rxdb');\n\n const root = connection\n .at(dir)\n .at(params.databaseName + '.')\n .at(params.collectionName + '.')\n .at(params.schema.version + '.');\n const main: FoundationDBDatabase = root\n .at('main.')\n .withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples\n .withValueEncoding(encoders.json) as any; // and values using JSON\n\n\n const events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>> = root\n .at('events.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n const attachments: FoundationDBDatabase = root\n .at('attachments.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n\n const indexDBs: { [indexName: string]: FoundationDBIndexMeta; } = {};\n const useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : [];\n useIndexes.push([primaryPath]);\n const useIndexesFinal = useIndexes.map(index => {\n const indexAr = Array.isArray(index) ? index.slice(0) : [index];\n indexAr.unshift('_deleted');\n return indexAr;\n });\n // used for `getChangedDocumentsSince()`\n useIndexesFinal.push([\n '_meta.lwt',\n primaryPath\n ]);\n useIndexesFinal.push(CLEANUP_INDEX);\n useIndexesFinal.forEach(indexAr => {\n const indexName = getFoundationDBIndexName(indexAr);\n const indexDB = root.at(indexName + '.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.string);\n indexDBs[indexName] = {\n indexName,\n db: indexDB,\n getIndexableString: getIndexableStringMonad(params.schema, indexAr),\n index: indexAr\n };\n });\n\n return {\n root,\n main,\n events,\n attachments,\n indexes: indexDBs\n };\n })();\n\n\n const internals: FoundationDBStorageInternals = {\n connection,\n dbsPromise: dbsPromise\n };\n\n const instance = new RxStorageInstanceFoundationDB(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":"AAAA,SAAqBA,OAAO,QAAQ,MAAM;AAC1C,SAASC,2BAA2B,QAAQ,wBAAwB;AA6BpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SACIC,uBAAuB,EACvBC,yBAAyB,QACtB,yBAAyB;AAChC,SAEIC,aAAa,EACbC,wBAAwB,QACrB,wBAAwB;AAC/B,SACIC,uBAAuB,EACvBC,iCAAiC,EACjCC,iCAAiC,QAC9B,oBAAoB;AAC3B,SACIC,cAAc,EAAEC,WAAW,EAAEC,GAAG,EAC9BC,oBAAoB,QACnB,YAAY;AACnB,SAASC,iBAAiB,QAAQ,sBAAsB;AACxD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AC,GAAG;YAClBA,SAAS,EAATA,SAAS;YACTtC,EAAE,EAAE+F,OAAO;YACXjG,kBAAkB,EAAE9D,uBAAuB,CAACyI,MAAM,CAAC3H,MAAM,EAAE6I,OAAO,CAAC;YACnEtD,KAAK,EAAEsD;UACX,CAAC;QACL,CAAC,CAAC;QAEF,OAAO;UACH/H,IAAI,EAAJA,IAAI;UACJY,IAAI,EAAJA,IAAI;UACJsC,MAAM,EAANA,MAAM;UACNnC,WAAW,EAAXA,WAAW;UACXgB,OAAO,EAAE2F;QACb,CAAC;MAAC;IACN,CAAC;MAAA;IAAA;EAAA,GAAG;EAGJ,IAAMvI,SAAkD,GAAG;IACvD8H,UAAU,EAAVA,UAAU;IACVpH,UAAU,EAAEA;EAChB,CAAC;EAED,IAAMuI,QAAQ,GAAG,IAAItJ,6BAA6B,CAC9CC,OAAO,EACP8H,MAAM,CAAC7H,YAAY,EACnB6H,MAAM,CAAC5H,cAAc,EACrB4H,MAAM,CAAC3H,MAAM,EACbC,SAAS,EACT0H,MAAM,CAACzH,OAAO,EACdC,QAAQ,CACX;EACD,OAAO6B,OAAO,CAACmH,OAAO,CAACD,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/es/plugins/json-dump/index.js b/dist/es/plugins/json-dump/index.js index e5ead3d0103..4bb303d804f 100644 --- a/dist/es/plugins/json-dump/index.js +++ b/dist/es/plugins/json-dump/index.js @@ -3,7 +3,7 @@ */ import { createRxQuery, queryCollection, _getDefaultQuery } from '../../rx-query'; import { newRxError } from '../../rx-error'; -import { flatClone, getDefaultRevision, now } from '../../util'; +import { flatClone, getDefaultRevision, now } from '../../plugins/utils'; function dumpRxDatabase(collections) { var _this = this; var json = { diff --git a/dist/es/plugins/json-dump/index.js.map b/dist/es/plugins/json-dump/index.js.map index e2f39d38675..bf41a1e4dd9 100644 --- a/dist/es/plugins/json-dump/index.js.map +++ b/dist/es/plugins/json-dump/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["createRxQuery","queryCollection","_getDefaultQuery","newRxError","flatClone","getDefaultRevision","now","dumpRxDatabase","collections","json","name","instanceToken","token","useCollections","Object","keys","filter","colName","includes","charAt","map","Promise","all","col","exportJSON","then","cols","importDumpRxDatabase","dump","missingCollections","length","colDump","importJSON","dumpRxCollection","schemaHash","schema","hash","docs","query","docData","_rev","_attachments","importDumpRxCollection","exportedJSON","own","storageInstance","bulkWrite","document","assign","_meta","lwt","_deleted","RxDBJsonDumpPlugin","rxdb","prototypes","RxDatabase","proto","RxCollection","overwritable"],"sources":["../../../../src/plugins/json-dump/index.ts"],"sourcesContent":["/**\n * this plugin adds the json export/import capabilities to RxDB\n */\nimport {\n createRxQuery,\n queryCollection,\n _getDefaultQuery\n} from '../../rx-query';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDatabase,\n RxCollection,\n RxPlugin,\n RxDocumentData\n} from '../../types';\nimport {\n flatClone,\n getDefaultRevision,\n now\n} from '../../util';\n\nfunction dumpRxDatabase(\n this: RxDatabase,\n collections?: string[]\n): Promise {\n const json: any = {\n name: this.name,\n instanceToken: this.token,\n collections: []\n };\n\n const useCollections = Object.keys(this.collections)\n .filter(colName => !collections || collections.includes(colName))\n .filter(colName => colName.charAt(0) !== '_')\n .map(colName => this.collections[colName]);\n\n return Promise.all(\n useCollections\n .map(col => col.exportJSON())\n ).then(cols => {\n json.collections = cols;\n return json;\n });\n}\n\nconst importDumpRxDatabase = function (\n this: RxDatabase,\n dump: any\n) {\n /**\n * collections must be created before the import\n * because we do not know about the other collection-settings here\n */\n const missingCollections = dump.collections\n .filter((col: any) => !this.collections[col.name])\n .map((col: any) => col.name);\n if (missingCollections.length > 0) {\n throw newRxError('JD1', {\n missingCollections\n });\n }\n\n return Promise.all(\n dump.collections\n .map((colDump: any) => this.collections[colDump.name].importJSON(colDump))\n );\n};\n\nconst dumpRxCollection = function (\n this: RxCollection\n) {\n const json: any = {\n name: this.name,\n schemaHash: this.schema.hash,\n docs: []\n };\n\n const query = createRxQuery(\n 'find',\n _getDefaultQuery(),\n this\n );\n return queryCollection(query)\n .then((docs: any) => {\n json.docs = docs.map((docData: any) => {\n docData = flatClone(docData);\n delete docData._rev;\n delete docData._attachments;\n return docData;\n });\n return json;\n });\n};\n\nfunction importDumpRxCollection(\n this: RxCollection,\n exportedJSON: any\n): Promise {\n // check schemaHash\n if (exportedJSON.schemaHash !== this.schema.hash) {\n throw newRxError('JD2', {\n schemaHash: exportedJSON.schemaHash,\n own: this.schema.hash\n });\n }\n\n const docs: RxDocType[] = exportedJSON.docs;\n return this.storageInstance.bulkWrite(\n docs.map(docData => {\n const document: RxDocumentData = Object.assign(\n {},\n docData,\n {\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision(),\n _attachments: {},\n _deleted: false\n }\n );\n return {\n document\n };\n }),\n 'json-dump-import'\n );\n}\n\nexport const RxDBJsonDumpPlugin: RxPlugin = {\n name: 'json-dump',\n rxdb: true,\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.exportJSON = dumpRxDatabase;\n proto.importJSON = importDumpRxDatabase;\n },\n RxCollection: (proto: any) => {\n proto.exportJSON = dumpRxCollection;\n proto.importJSON = importDumpRxCollection;\n }\n },\n overwritable: {}\n};\n"],"mappings":"AAAA;AACA;AACA;AACA,SACIA,aAAa,EACbC,eAAe,EACfC,gBAAgB,QACb,gBAAgB;AACvB,SACIC,UAAU,QACP,gBAAgB;AAOvB,SACIC,SAAS,EACTC,kBAAkB,EAClBC,GAAG,QACA,YAAY;AAEnB,SAASC,cAAc,CAEnBC,WAAsB,EACV;EAAA;EACZ,IAAMC,IAAS,GAAG;IACdC,IAAI,EAAE,IAAI,CAACA,IAAI;IACfC,aAAa,EAAE,IAAI,CAACC,KAAK;IACzBJ,WAAW,EAAE;EACjB,CAAC;EAED,IAAMK,cAAc,GAAGC,MAAM,CAACC,IAAI,CAAC,IAAI,CAACP,WAAW,CAAC,CAC/CQ,MAAM,CAAC,UAAAC,OAAO;IAAA,OAAI,CAACT,WAAW,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,OAAO;MACHJ,QAAQ,EAARA;IACJ,CAAC;EACL,CAAC,CAAC,EACF,kBAAkB,CACrB;AACL;AAEA,OAAO,IAAMK,kBAA4B,GAAG;EACxC1C,IAAI,EAAE,WAAW;EACjB2C,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAAChC,UAAU,GAAGjB,cAAc;MACjCiD,KAAK,CAACxB,UAAU,GAAGL,oBAAoB;IAC3C,CAAC;IACD8B,YAAY,EAAE,sBAACD,KAAU,EAAK;MAC1BA,KAAK,CAAChC,UAAU,GAAGS,gBAAgB;MACnCuB,KAAK,CAACxB,UAAU,GAAGU,sBAAsB;IAC7C;EACJ,CAAC;EACDgB,YAAY,EAAE,CAAC;AACnB,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["createRxQuery","queryCollection","_getDefaultQuery","newRxError","flatClone","getDefaultRevision","now","dumpRxDatabase","collections","json","name","instanceToken","token","useCollections","Object","keys","filter","colName","includes","charAt","map","Promise","all","col","exportJSON","then","cols","importDumpRxDatabase","dump","missingCollections","length","colDump","importJSON","dumpRxCollection","schemaHash","schema","hash","docs","query","docData","_rev","_attachments","importDumpRxCollection","exportedJSON","own","storageInstance","bulkWrite","document","assign","_meta","lwt","_deleted","RxDBJsonDumpPlugin","rxdb","prototypes","RxDatabase","proto","RxCollection","overwritable"],"sources":["../../../../src/plugins/json-dump/index.ts"],"sourcesContent":["/**\n * this plugin adds the json export/import capabilities to RxDB\n */\nimport {\n createRxQuery,\n queryCollection,\n _getDefaultQuery\n} from '../../rx-query';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDatabase,\n RxCollection,\n RxPlugin,\n RxDocumentData\n} from '../../types';\nimport {\n flatClone,\n getDefaultRevision,\n now\n} from '../../plugins/utils';\n\nfunction dumpRxDatabase(\n this: RxDatabase,\n collections?: string[]\n): Promise {\n const json: any = {\n name: this.name,\n instanceToken: this.token,\n collections: []\n };\n\n const useCollections = Object.keys(this.collections)\n .filter(colName => !collections || collections.includes(colName))\n .filter(colName => colName.charAt(0) !== '_')\n .map(colName => this.collections[colName]);\n\n return Promise.all(\n useCollections\n .map(col => col.exportJSON())\n ).then(cols => {\n json.collections = cols;\n return json;\n });\n}\n\nconst importDumpRxDatabase = function (\n this: RxDatabase,\n dump: any\n) {\n /**\n * collections must be created before the import\n * because we do not know about the other collection-settings here\n */\n const missingCollections = dump.collections\n .filter((col: any) => !this.collections[col.name])\n .map((col: any) => col.name);\n if (missingCollections.length > 0) {\n throw newRxError('JD1', {\n missingCollections\n });\n }\n\n return Promise.all(\n dump.collections\n .map((colDump: any) => this.collections[colDump.name].importJSON(colDump))\n );\n};\n\nconst dumpRxCollection = function (\n this: RxCollection\n) {\n const json: any = {\n name: this.name,\n schemaHash: this.schema.hash,\n docs: []\n };\n\n const query = createRxQuery(\n 'find',\n _getDefaultQuery(),\n this\n );\n return queryCollection(query)\n .then((docs: any) => {\n json.docs = docs.map((docData: any) => {\n docData = flatClone(docData);\n delete docData._rev;\n delete docData._attachments;\n return docData;\n });\n return json;\n });\n};\n\nfunction importDumpRxCollection(\n this: RxCollection,\n exportedJSON: any\n): Promise {\n // check schemaHash\n if (exportedJSON.schemaHash !== this.schema.hash) {\n throw newRxError('JD2', {\n schemaHash: exportedJSON.schemaHash,\n own: this.schema.hash\n });\n }\n\n const docs: RxDocType[] = exportedJSON.docs;\n return this.storageInstance.bulkWrite(\n docs.map(docData => {\n const document: RxDocumentData = Object.assign(\n {},\n docData,\n {\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision(),\n _attachments: {},\n _deleted: false\n }\n );\n return {\n document\n };\n }),\n 'json-dump-import'\n );\n}\n\nexport const RxDBJsonDumpPlugin: RxPlugin = {\n name: 'json-dump',\n rxdb: true,\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.exportJSON = dumpRxDatabase;\n proto.importJSON = importDumpRxDatabase;\n },\n RxCollection: (proto: any) => {\n proto.exportJSON = dumpRxCollection;\n proto.importJSON = importDumpRxCollection;\n }\n },\n overwritable: {}\n};\n"],"mappings":"AAAA;AACA;AACA;AACA,SACIA,aAAa,EACbC,eAAe,EACfC,gBAAgB,QACb,gBAAgB;AACvB,SACIC,UAAU,QACP,gBAAgB;AAOvB,SACIC,SAAS,EACTC,kBAAkB,EAClBC,GAAG,QACA,qBAAqB;AAE5B,SAASC,cAAc,CAEnBC,WAAsB,EACV;EAAA;EACZ,IAAMC,IAAS,GAAG;IACdC,IAAI,EAAE,IAAI,CAACA,IAAI;IACfC,aAAa,EAAE,IAAI,CAACC,KAAK;IACzBJ,WAAW,EAAE;EACjB,CAAC;EAED,IAAMK,cAAc,GAAGC,MAAM,CAACC,IAAI,CAAC,IAAI,CAACP,WAAW,CAAC,CAC/CQ,MAAM,CAAC,UAAAC,OAAO;IAAA,OAAI,CAACT,WAAW,IAAIA,WAAW,CAACU,QAAQ,CAACD,OAAO,CAAC;EAAA,EAAC,CAChED,MAAM,CAAC,UAAAC,OAAO;IAAA,OAAIA,OAAO,CAACE,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG;EAAA,EAAC,CAC5CC,GAAG,CAAC,UAAAH,OAAO;IAAA,OAAI,KAAI,CAACT,WAAW,CAACS,OAAO,CAAC;EAAA,EAAC;EAE9C,OAAOI,OAAO,CAACC,GAAG,CACdT,cAAc,CACTO,GAAG,CAAC,UAAAG,GAAG;IAAA,OAAIA,GAAG,CAACC,UAAU,EAAE;EAAA,EAAC,CACpC,CAACC,IAAI,CAAC,UAAAC,IAAI,EAAI;IACXjB,IAAI,CAACD,WAAW,GAAGkB,IAAI;IACvB,OAAOjB,IAAI;EACf,CAAC,CAAC;AACN;AAEA,IAAMkB,oBAAoB,GAAG,SAAvBA,oBAAoB,CAEtBC,IAAS,EACX;EAAA;EACE;AACJ;AACA;AACA;EACI,IAAMC,kBAAkB,GAAGD,IAAI,CAACpB,WAAW,CACtCQ,MAAM,CAAC,UAACO,GAAQ;IAAA,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AI,EAAE;IAC9C,MAAMjC,UAAU,CAAC,KAAK,EAAE;MACpB+B,UAAU,EAAES,YAAY,CAACT,UAAU;MACnCU,GAAG,EAAE,IAAI,CAACT,MAAM,CAACC;IACrB,CAAC,CAAC;EACN;EAEA,IAAMC,IAAiB,GAAGM,YAAY,CAACN,IAAI;EAC3C,OAAO,IAAI,CAACQ,eAAe,CAACC,SAAS,CACjCT,IAAI,CAACjB,GAAG,CAAC,UAAAmB,OAAO,EAAI;IAChB,IAAMQ,QAAmC,GAAGjC,MAAM,CAACkC,MAAM,CACrD,CAAC,CAAC,EACFT,OAAO,EACP;MACIU,KAAK,EAAE;QACHC,GAAG,EAAE5C,GAAG;MACZ,CAAC;MACDkC,IAAI,EAAEnC,kBAAkB,EAAE;MAC1BoC,YAAY,EAAE,CAAC,CAAC;MAChBU,QAAQ,EAAE;IACd,CAAC,CACJ;IACD,OAAO;MACHJ,QAAQ,EAARA;IACJ,CAAC;EACL,CAAC,CAAC,EACF,kBAAkB,CACrB;AACL;AAEA,OAAO,IAAMK,kBAA4B,GAAG;EACxC1C,IAAI,EAAE,WAAW;EACjB2C,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAAChC,UAAU,GAAGjB,cAAc;MACjCiD,KAAK,CAACxB,UAAU,GAAGL,oBAAoB;IAC3C,CAAC;IACD8B,YAAY,EAAE,sBAACD,KAAU,EAAK;MAC1BA,KAAK,CAAChC,UAAU,GAAGS,gBAAgB;MACnCuB,KAAK,CAACxB,UAAU,GAAGU,sBAAsB;IAC7C;EACJ,CAAC;EACDgB,YAAY,EAAE,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/key-compression/index.js b/dist/es/plugins/key-compression/index.js index 4fd38100307..39c6564884e 100644 --- a/dist/es/plugins/key-compression/index.js +++ b/dist/es/plugins/key-compression/index.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * this plugin adds the keycompression-capabilities to rxdb * if you dont use this, ensure that you set disableKeyComression to false in your schema @@ -8,7 +10,7 @@ import { overwritable } from '../../overwritable'; import { wrapRxStorageInstance } from '../../plugin-helpers'; import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; import { flatCloneDocWithMeta } from '../../rx-storage-helper'; -import { flatClone, isMaybeReadonlyArray } from '../../util'; +import { flatClone, isMaybeReadonlyArray } from '../../plugins/utils'; /** * Cache the compression table and the compressed schema * by the storage instance for better performance. @@ -114,35 +116,51 @@ export function wrappedKeyCompressionStorage(args) { }); return Object.assign({}, args.storage, { statics: statics, - createStorageInstance: function createStorageInstance(params) { - try { - var modifyToStorage = function modifyToStorage(docData) { - return compressDocumentData(compressionState, docData); - }; - var modifyFromStorage = function modifyFromStorage(docData) { - return decompressDocumentData(compressionState, docData); - }; - /** - * Because this wrapper resolves the key-compression, - * we can set the flag to false - * which allows underlying storages to detect wrong conficturations - * like when keyCompression is set to false but no key-compression module is used. - */ - if (!params.schema.keyCompression) { - return Promise.resolve(args.storage.createStorageInstance(params)); - } - var compressionState = getCompressionStateByRxJsonSchema(params.schema); - var childSchema = flatClone(compressionState.compressedSchema); - childSchema.keyCompression = false; - return Promise.resolve(args.storage.createStorageInstance(Object.assign({}, params, { - schema: childSchema - }))).then(function (instance) { - return wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage); - }); - } catch (e) { - return Promise.reject(e); + createStorageInstance: function () { + var _createStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(params) { + var compressionState, modifyToStorage, modifyFromStorage, childSchema, instance; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + modifyFromStorage = function _modifyFromStorage(docData) { + return decompressDocumentData(compressionState, docData); + }; + modifyToStorage = function _modifyToStorage(docData) { + return compressDocumentData(compressionState, docData); + }; + if (params.schema.keyCompression) { + _context.next = 4; + break; + } + return _context.abrupt("return", args.storage.createStorageInstance(params)); + case 4: + compressionState = getCompressionStateByRxJsonSchema(params.schema); + /** + * Because this wrapper resolves the key-compression, + * we can set the flag to false + * which allows underlying storages to detect wrong conficturations + * like when keyCompression is set to false but no key-compression module is used. + */ + childSchema = flatClone(compressionState.compressedSchema); + childSchema.keyCompression = false; + _context.next = 9; + return args.storage.createStorageInstance(Object.assign({}, params, { + schema: childSchema + })); + case 9: + instance = _context.sent; + return _context.abrupt("return", wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage)); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); } export function compressDocumentData(compressionState, docData) { diff --git a/dist/es/plugins/key-compression/index.js.map b/dist/es/plugins/key-compression/index.js.map index fe94de986b4..835560d1fc0 100644 --- a/dist/es/plugins/key-compression/index.js.map +++ b/dist/es/plugins/key-compression/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["createCompressionTable","compressObject","decompressObject","compressedPath","DEFAULT_COMPRESSION_FLAG","createCompressedJsonSchema","compressQuery","overwritable","wrapRxStorageInstance","getPrimaryFieldOfPrimaryKey","flatCloneDocWithMeta","flatClone","isMaybeReadonlyArray","COMPRESSION_STATE_BY_SCHEMA","WeakMap","getCompressionStateByRxJsonSchema","schema","deepFreezeWhenDevMode","compressionState","get","compressionSchema","primaryKey","table","compressedSchema","composedPrimary","newComposedPrimary","key","fields","map","field","separator","indexes","newIndexes","idx","subIdx","set","wrappedKeyCompressionStorage","args","statics","Object","assign","storage","prepareQuery","mutateableQuery","keyCompression","getSortComparator","preparedQuery","comparator","a","b","compressedDocDataA","compressedDocDataB","res","getQueryMatcher","matcher","docData","compressedDocData","ret","createStorageInstance","params","modifyToStorage","compressDocumentData","modifyFromStorage","decompressDocumentData","childSchema","instance","attachments","_attachments"],"sources":["../../../../src/plugins/key-compression/index.ts"],"sourcesContent":["/**\n * this plugin adds the keycompression-capabilities to rxdb\n * if you dont use this, ensure that you set disableKeyComression to false in your schema\n */\n\nimport type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport {\n createCompressionTable,\n CompressionTable,\n JsonSchema as KeyCompressionJsonSchema,\n compressObject,\n decompressObject,\n compressedPath,\n DEFAULT_COMPRESSION_FLAG,\n createCompressedJsonSchema,\n compressQuery\n} from 'jsonschema-key-compression';\nimport {\n overwritable\n} from '../../overwritable';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../../rx-storage-helper';\n\nimport type {\n RxJsonSchema,\n CompositePrimaryKey,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxDocumentData,\n RxStorageStatics,\n FilledMangoQuery,\n PreparedQuery,\n RxDocumentWriteData\n} from '../../types';\nimport {\n flatClone,\n isMaybeReadonlyArray\n} from '../../util';\n\ndeclare type CompressionState = {\n table: CompressionTable;\n schema: RxJsonSchema;\n compressedSchema: RxJsonSchema;\n};\n\n/**\n * Cache the compression table and the compressed schema\n * by the storage instance for better performance.\n */\nconst COMPRESSION_STATE_BY_SCHEMA: WeakMap<\nRxJsonSchema,\nCompressionState\n> = new WeakMap();\n\n\nexport function getCompressionStateByRxJsonSchema(\n schema: RxJsonSchema\n): CompressionState {\n /**\n * Because we cache the state by the JsonSchema,\n * it must be ausured that the given schema object\n * is never mutated.\n */\n overwritable.deepFreezeWhenDevMode(schema);\n\n let compressionState = COMPRESSION_STATE_BY_SCHEMA.get(schema);\n if (!compressionState) {\n const compressionSchema: KeyCompressionJsonSchema = flatClone(schema) as any;\n delete (compressionSchema as any).primaryKey;\n\n const table = createCompressionTable(\n compressionSchema,\n DEFAULT_COMPRESSION_FLAG,\n [\n /**\n * Do not compress the primary field\n * for easier debugging.\n */\n getPrimaryFieldOfPrimaryKey(schema.primaryKey),\n '_rev',\n '_attachments',\n '_deleted',\n '_meta'\n ]\n );\n\n delete (compressionSchema as any).primaryKey;\n const compressedSchema: RxJsonSchema = createCompressedJsonSchema(\n table,\n compressionSchema\n ) as RxJsonSchema;\n\n // also compress primary key\n if (typeof schema.primaryKey !== 'string') {\n const composedPrimary: CompositePrimaryKey = schema.primaryKey;\n const newComposedPrimary: CompositePrimaryKey = {\n key: compressedPath(table, composedPrimary.key as string),\n fields: composedPrimary.fields.map(field => compressedPath(table, field as string)),\n separator: composedPrimary.separator\n };\n compressedSchema.primaryKey = newComposedPrimary;\n } else {\n compressedSchema.primaryKey = compressedPath(table, schema.primaryKey);\n }\n\n /**\n * the key compression module does not know about indexes\n * in the schema, so we have to also compress them here.\n */\n if (schema.indexes) {\n const newIndexes = schema.indexes.map(idx => {\n if (isMaybeReadonlyArray(idx)) {\n return idx.map(subIdx => compressedPath(table, subIdx));\n } else {\n return compressedPath(table, idx);\n }\n });\n compressedSchema.indexes = newIndexes;\n }\n\n compressionState = {\n table,\n schema,\n compressedSchema\n };\n COMPRESSION_STATE_BY_SCHEMA.set(schema, compressionState);\n }\n return compressionState;\n}\n\nexport function wrappedKeyCompressionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n const statics: RxStorageStatics = Object.assign(\n {},\n args.storage.statics,\n {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery {\n if (schema.keyCompression) {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n mutateableQuery = compressQuery(\n compressionState.table,\n mutateableQuery as any\n ) as any;\n return args.storage.statics.prepareQuery(\n compressionState.compressedSchema,\n mutateableQuery\n );\n }\n return args.storage.statics.prepareQuery(\n schema,\n mutateableQuery\n );\n },\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator {\n if (!schema.keyCompression) {\n return args.storage.statics.getSortComparator(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const comparator = args.storage.statics.getSortComparator(compressionState.schema, preparedQuery);\n return (a, b) => {\n const compressedDocDataA = compressObject(\n compressionState.table,\n a as any\n );\n const compressedDocDataB = compressObject(\n compressionState.table,\n b as any\n );\n const res = comparator(compressedDocDataA, compressedDocDataB);\n return res;\n };\n }\n },\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher> {\n if (!schema.keyCompression) {\n return args.storage.statics.getQueryMatcher(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const matcher = args.storage.statics.getQueryMatcher(compressionState.schema, preparedQuery);\n return (docData) => {\n const compressedDocData = compressObject(\n compressionState.table,\n docData\n );\n const ret = matcher(compressedDocData);\n return ret;\n };\n }\n }\n }\n );\n\n return Object.assign(\n {},\n args.storage,\n {\n statics,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!params.schema.keyCompression) {\n return args.storage.createStorageInstance(params);\n }\n\n const compressionState = getCompressionStateByRxJsonSchema(params.schema);\n function modifyToStorage(docData: RxDocumentWriteData) {\n return compressDocumentData(compressionState, docData);\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n return decompressDocumentData(compressionState, docData);\n }\n\n /**\n * Because this wrapper resolves the key-compression,\n * we can set the flag to false\n * which allows underlying storages to detect wrong conficturations\n * like when keyCompression is set to false but no key-compression module is used.\n */\n const childSchema = flatClone(compressionState.compressedSchema);\n childSchema.keyCompression = false;\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: childSchema\n }\n )\n );\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage\n );\n }\n }\n );\n}\n\nexport function compressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n /**\n * Do not send attachments to compressObject()\n * because it will deep clone which does not work on Blob or Buffer.\n */\n docData = flatCloneDocWithMeta(docData);\n const attachments = docData._attachments;\n delete docData._attachments;\n\n docData = compressObject(\n compressionState.table,\n docData\n );\n docData._attachments = attachments;\n return docData;\n}\n\nexport function decompressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n return decompressObject(\n compressionState.table,\n docData\n );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAMA,SACIA,sBAAsB,EAGtBC,cAAc,EACdC,gBAAgB,EAChBC,cAAc,EACdC,wBAAwB,EACxBC,0BAA0B,EAC1BC,aAAa,QACV,4BAA4B;AACnC,SACIC,YAAY,QACT,oBAAoB;AAC3B,SAASC,qBAAqB,QAAQ,sBAAsB;AAC5D,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SAASC,oBAAoB,QAAQ,yBAAyB;AAa9D,SACIC,SAAS,EACTC,oBAAoB,QACjB,YAAY;AAQnB;AACA;AACA;AACA;AACA,IAAMC,2BAGL,GAAG,IAAIC,OAAO,EAAE;AAGjB,OAAO,SAASC,iCAAiC,CAC7CC,MAAyB,EACT;EAChB;AACJ;AACA;AACA;AACA;EACIT,YAAY,CAACU,qBAAqB,CAACD,MAAM,CAAC;EAE1C,IAAIE,gBAAgB,GAAGL,2BAA2B,CAACM,GAAG,CAACH,MAAM,CAAC;EAC9D,IAAI,CAACE,gBAAgB,EAAE;IACnB,IAAME,iBAA2C,GAAGT,SAAS,CAACK,MAAM,CAAQ;IAC5E,OAAQI,iBAAiB,CAASC,UAAU;IAE5C,IAAMC,KAAK,GAAGtB,sBAAsB,CAChCoB,iBAAiB,EACjBhB,wBAAwB,EACxB;IACI;AAChB;AACA;AACA;IACgBK,2BAA2B,CAACO,MAAM,CAACK,UAAU,CAAC,EAC9C,MAAM,EACN,cAAc,EACd,UAAU,EACV,OAAO,CACV,CACJ;IAED,OAAQD,iBAAiB,CAASC,UAAU;IAC5C,IAAME,gBAAmC,GAAGlB,0BAA0B,CAClEiB,KAAK,EACLF,iBAAiB,CACC;;IAEtB;IACA,IAAI,OAAOJ,MAAM,CAACK,UAAU,KAAK,QAAQ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AczE,IAAMgD,WAAW,GAAGrD,SAAS,CAACO,gBAAgB,CAACK,gBAAgB,CAAC;QAChEyC,WAAW,CAACpB,cAAc,GAAG,KAAK;QAAC,uBAEZP,IAAI,CAACI,OAAO,CAACiB,qBAAqB,CACrDnB,MAAM,CAACC,MAAM,CACT,CAAC,CAAC,EACFmB,MAAM,EACN;UACI3C,MAAM,EAAEgD;QACZ,CAAC,CACJ,CACJ,iBARKC,QAAQ;UAUd,OAAOzD,qBAAqB,CACxByD,QAAQ,EACRL,eAAe,EACfE,iBAAiB,CACpB;QAAC;MACN,CAAC;QAAA;MAAA;IAAA;EACL,CAAC,CACJ;AACL;AAEA,OAAO,SAASD,oBAAoB,CAChC3C,gBAAkC,EAClCqC,OAA4B,EACT;EACnB;AACJ;AACA;AACA;EACIA,OAAO,GAAG7C,oBAAoB,CAAC6C,OAAO,CAAC;EACvC,IAAMW,WAAW,GAAGX,OAAO,CAACY,YAAY;EACxC,OAAOZ,OAAO,CAACY,YAAY;EAE3BZ,OAAO,GAAGtD,cAAc,CACpBiB,gBAAgB,CAACI,KAAK,EACtBiC,OAAO,CACV;EACDA,OAAO,CAACY,YAAY,GAAGD,WAAW;EAClC,OAAOX,OAAO;AAClB;AAEA,OAAO,SAASQ,sBAAsB,CAClC7C,gBAAkC,EAClCqC,OAA4B,EACT;EACnB,OAAOrD,gBAAgB,CACnBgB,gBAAgB,CAACI,KAAK,EACtBiC,OAAO,CACV;AACL"} \ No newline at end of file +{"version":3,"file":"index.js","names":["createCompressionTable","compressObject","decompressObject","compressedPath","DEFAULT_COMPRESSION_FLAG","createCompressedJsonSchema","compressQuery","overwritable","wrapRxStorageInstance","getPrimaryFieldOfPrimaryKey","flatCloneDocWithMeta","flatClone","isMaybeReadonlyArray","COMPRESSION_STATE_BY_SCHEMA","WeakMap","getCompressionStateByRxJsonSchema","schema","deepFreezeWhenDevMode","compressionState","get","compressionSchema","primaryKey","table","compressedSchema","composedPrimary","newComposedPrimary","key","fields","map","field","separator","indexes","newIndexes","idx","subIdx","set","wrappedKeyCompressionStorage","args","statics","Object","assign","storage","prepareQuery","mutateableQuery","keyCompression","getSortComparator","preparedQuery","comparator","a","b","compressedDocDataA","compressedDocDataB","res","getQueryMatcher","matcher","docData","compressedDocData","ret","createStorageInstance","params","modifyToStorage","modifyFromStorage","decompressDocumentData","compressDocumentData","childSchema","instance","attachments","_attachments"],"sources":["../../../../src/plugins/key-compression/index.ts"],"sourcesContent":["/**\n * this plugin adds the keycompression-capabilities to rxdb\n * if you dont use this, ensure that you set disableKeyComression to false in your schema\n */\n\nimport type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport {\n createCompressionTable,\n CompressionTable,\n JsonSchema as KeyCompressionJsonSchema,\n compressObject,\n decompressObject,\n compressedPath,\n DEFAULT_COMPRESSION_FLAG,\n createCompressedJsonSchema,\n compressQuery\n} from 'jsonschema-key-compression';\nimport {\n overwritable\n} from '../../overwritable';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../../rx-storage-helper';\n\nimport type {\n RxJsonSchema,\n CompositePrimaryKey,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxDocumentData,\n RxStorageStatics,\n FilledMangoQuery,\n PreparedQuery,\n RxDocumentWriteData\n} from '../../types';\nimport {\n flatClone,\n isMaybeReadonlyArray\n} from '../../plugins/utils';\n\ndeclare type CompressionState = {\n table: CompressionTable;\n schema: RxJsonSchema;\n compressedSchema: RxJsonSchema;\n};\n\n/**\n * Cache the compression table and the compressed schema\n * by the storage instance for better performance.\n */\nconst COMPRESSION_STATE_BY_SCHEMA: WeakMap<\nRxJsonSchema,\nCompressionState\n> = new WeakMap();\n\n\nexport function getCompressionStateByRxJsonSchema(\n schema: RxJsonSchema\n): CompressionState {\n /**\n * Because we cache the state by the JsonSchema,\n * it must be ausured that the given schema object\n * is never mutated.\n */\n overwritable.deepFreezeWhenDevMode(schema);\n\n let compressionState = COMPRESSION_STATE_BY_SCHEMA.get(schema);\n if (!compressionState) {\n const compressionSchema: KeyCompressionJsonSchema = flatClone(schema) as any;\n delete (compressionSchema as any).primaryKey;\n\n const table = createCompressionTable(\n compressionSchema,\n DEFAULT_COMPRESSION_FLAG,\n [\n /**\n * Do not compress the primary field\n * for easier debugging.\n */\n getPrimaryFieldOfPrimaryKey(schema.primaryKey),\n '_rev',\n '_attachments',\n '_deleted',\n '_meta'\n ]\n );\n\n delete (compressionSchema as any).primaryKey;\n const compressedSchema: RxJsonSchema = createCompressedJsonSchema(\n table,\n compressionSchema\n ) as RxJsonSchema;\n\n // also compress primary key\n if (typeof schema.primaryKey !== 'string') {\n const composedPrimary: CompositePrimaryKey = schema.primaryKey;\n const newComposedPrimary: CompositePrimaryKey = {\n key: compressedPath(table, composedPrimary.key as string),\n fields: composedPrimary.fields.map(field => compressedPath(table, field as string)),\n separator: composedPrimary.separator\n };\n compressedSchema.primaryKey = newComposedPrimary;\n } else {\n compressedSchema.primaryKey = compressedPath(table, schema.primaryKey);\n }\n\n /**\n * the key compression module does not know about indexes\n * in the schema, so we have to also compress them here.\n */\n if (schema.indexes) {\n const newIndexes = schema.indexes.map(idx => {\n if (isMaybeReadonlyArray(idx)) {\n return idx.map(subIdx => compressedPath(table, subIdx));\n } else {\n return compressedPath(table, idx);\n }\n });\n compressedSchema.indexes = newIndexes;\n }\n\n compressionState = {\n table,\n schema,\n compressedSchema\n };\n COMPRESSION_STATE_BY_SCHEMA.set(schema, compressionState);\n }\n return compressionState;\n}\n\nexport function wrappedKeyCompressionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n const statics: RxStorageStatics = Object.assign(\n {},\n args.storage.statics,\n {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery {\n if (schema.keyCompression) {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n mutateableQuery = compressQuery(\n compressionState.table,\n mutateableQuery as any\n ) as any;\n return args.storage.statics.prepareQuery(\n compressionState.compressedSchema,\n mutateableQuery\n );\n }\n return args.storage.statics.prepareQuery(\n schema,\n mutateableQuery\n );\n },\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator {\n if (!schema.keyCompression) {\n return args.storage.statics.getSortComparator(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const comparator = args.storage.statics.getSortComparator(compressionState.schema, preparedQuery);\n return (a, b) => {\n const compressedDocDataA = compressObject(\n compressionState.table,\n a as any\n );\n const compressedDocDataB = compressObject(\n compressionState.table,\n b as any\n );\n const res = comparator(compressedDocDataA, compressedDocDataB);\n return res;\n };\n }\n },\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher> {\n if (!schema.keyCompression) {\n return args.storage.statics.getQueryMatcher(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const matcher = args.storage.statics.getQueryMatcher(compressionState.schema, preparedQuery);\n return (docData) => {\n const compressedDocData = compressObject(\n compressionState.table,\n docData\n );\n const ret = matcher(compressedDocData);\n return ret;\n };\n }\n }\n }\n );\n\n return Object.assign(\n {},\n args.storage,\n {\n statics,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!params.schema.keyCompression) {\n return args.storage.createStorageInstance(params);\n }\n\n const compressionState = getCompressionStateByRxJsonSchema(params.schema);\n function modifyToStorage(docData: RxDocumentWriteData) {\n return compressDocumentData(compressionState, docData);\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n return decompressDocumentData(compressionState, docData);\n }\n\n /**\n * Because this wrapper resolves the key-compression,\n * we can set the flag to false\n * which allows underlying storages to detect wrong conficturations\n * like when keyCompression is set to false but no key-compression module is used.\n */\n const childSchema = flatClone(compressionState.compressedSchema);\n childSchema.keyCompression = false;\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: childSchema\n }\n )\n );\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage\n );\n }\n }\n );\n}\n\nexport function compressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n /**\n * Do not send attachments to compressObject()\n * because it will deep clone which does not work on Blob or Buffer.\n */\n docData = flatCloneDocWithMeta(docData);\n const attachments = docData._attachments;\n delete docData._attachments;\n\n docData = compressObject(\n compressionState.table,\n docData\n );\n docData._attachments = attachments;\n return docData;\n}\n\nexport function decompressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n return decompressObject(\n compressionState.table,\n docData\n );\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;;AAMA,SACIA,sBAAsB,EAGtBC,cAAc,EACdC,gBAAgB,EAChBC,cAAc,EACdC,wBAAwB,EACxBC,0BAA0B,EAC1BC,aAAa,QACV,4BAA4B;AACnC,SACIC,YAAY,QACT,oBAAoB;AAC3B,SAASC,qBAAqB,QAAQ,sBAAsB;AAC5D,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SAASC,oBAAoB,QAAQ,yBAAyB;AAa9D,SACIC,SAAS,EACTC,oBAAoB,QACjB,qBAAqB;AAQ5B;AACA;AACA;AACA;AACA,IAAMC,2BAGL,GAAG,IAAIC,OAAO,EAAE;AAGjB,OAAO,SAASC,iCAAiC,CAC7CC,MAAyB,EACT;EAChB;AACJ;AACA;AACA;AACA;EACIT,YAAY,CAACU,qBAAqB,CAACD,MAAM,CAAC;EAE1C,IAAIE,gBAAgB,GAAGL,2BAA2B,CAACM,GAAG,CAACH,MAAM,CAAC;EAC9D,IAAI,CAACE,gBAAgB,EAAE;IACnB,IAAME,iBAA2C,GAAGT,SAAS,CAACK,MAAM,CAAQ;IAC5E,OAAQI,iBAAiB,CAASC,UAAU;IAE5C,IAAMC,KAAK,GAAGtB,sBAAsB,CAChCoB,iBAAiB,EACjBhB,wBAAwB,EACxB;IACI;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--git a/dist/es/plugins/leader-election/index.js b/dist/es/plugins/leader-election/index.js index f418df225fb..9cfa366cc99 100644 --- a/dist/es/plugins/leader-election/index.js +++ b/dist/es/plugins/leader-election/index.js @@ -4,7 +4,7 @@ import { createLeaderElection } from 'broadcast-channel'; import { getBroadcastChannelReference, removeBroadcastChannelReference } from '../../rx-storage-multiinstance'; -import { PROMISE_RESOLVE_TRUE } from '../../util'; +import { PROMISE_RESOLVE_TRUE } from '../utils'; var LEADER_ELECTORS_OF_DB = new WeakMap(); var LEADER_ELECTOR_BY_BROADCAST_CHANNEL = new WeakMap(); diff --git a/dist/es/plugins/leader-election/index.js.map b/dist/es/plugins/leader-election/index.js.map index 251c9b6fe82..f09351ba543 100644 --- a/dist/es/plugins/leader-election/index.js.map +++ b/dist/es/plugins/leader-election/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["createLeaderElection","getBroadcastChannelReference","removeBroadcastChannelReference","PROMISE_RESOLVE_TRUE","LEADER_ELECTORS_OF_DB","WeakMap","LEADER_ELECTOR_BY_BROADCAST_CHANNEL","getLeaderElectorByBroadcastChannel","broadcastChannel","elector","get","set","getForDatabase","token","name","oldDestroy","destroy","bind","leaderElector","isLeader","multiInstance","waitForLeadership","awaitLeadership","then","onDestroy","db","has","die","rxdb","prototypes","RxDatabase","proto","RxDBLeaderElectionPlugin","hooks","preDestroyRxDatabase","after"],"sources":["../../../../src/plugins/leader-election/index.ts"],"sourcesContent":["/**\n * this plugin adds the leader-election-capabilities to rxdb\n */\n\nimport {\n createLeaderElection,\n LeaderElector,\n BroadcastChannel\n} from 'broadcast-channel';\nimport {\n getBroadcastChannelReference,\n removeBroadcastChannelReference\n} from '../../rx-storage-multiinstance';\n\nimport type {\n RxDatabase,\n RxPlugin\n} from '../../types';\nimport {\n PROMISE_RESOLVE_TRUE\n} from '../../util';\n\nconst LEADER_ELECTORS_OF_DB: WeakMap = new WeakMap();\nconst LEADER_ELECTOR_BY_BROADCAST_CHANNEL: WeakMap = new WeakMap();\n\n\n/**\n * Returns the leader elector of a broadcast channel.\n * Used to ensure we reuse the same elector for the channel each time.\n */\nexport function getLeaderElectorByBroadcastChannel(broadcastChannel: BroadcastChannel): LeaderElector {\n let elector = LEADER_ELECTOR_BY_BROADCAST_CHANNEL.get(broadcastChannel);\n if (!elector) {\n elector = createLeaderElection(broadcastChannel);\n LEADER_ELECTOR_BY_BROADCAST_CHANNEL.set(broadcastChannel, elector);\n }\n return elector;\n}\n\n/**\n * @overwrites RxDatabase().leaderElector for caching\n */\nexport function getForDatabase(this: RxDatabase): LeaderElector {\n\n\n const broadcastChannel = getBroadcastChannelReference(\n this.token,\n this.name,\n this\n );\n\n /**\n * Clean up the reference on RxDatabase.destroy()\n */\n const oldDestroy = this.destroy.bind(this);\n this.destroy = function () {\n removeBroadcastChannelReference(this.token, this);\n return oldDestroy();\n };\n\n\n let elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n if (!elector) {\n elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n LEADER_ELECTORS_OF_DB.set(\n this,\n elector\n );\n }\n\n /**\n * Overwrite for caching\n */\n this.leaderElector = () => elector;\n\n return elector;\n}\n\nexport function isLeader(this: RxDatabase): boolean {\n if (!this.multiInstance) {\n return true;\n }\n return this.leaderElector().isLeader;\n}\n\nexport function waitForLeadership(this: RxDatabase): Promise {\n if (!this.multiInstance) {\n return PROMISE_RESOLVE_TRUE;\n } else {\n return this.leaderElector()\n .awaitLeadership()\n .then(() => true);\n }\n}\n\n/**\n * runs when the database gets destroyed\n */\nexport function onDestroy(db: RxDatabase) {\n const has = LEADER_ELECTORS_OF_DB.get(db);\n if (has) {\n has.die();\n }\n}\n\nexport const rxdb = true;\nexport const prototypes = {\n RxDatabase: (proto: any) => {\n proto.leaderElector = getForDatabase;\n proto.isLeader = isLeader;\n proto.waitForLeadership = waitForLeadership;\n }\n};\n\nexport const RxDBLeaderElectionPlugin: RxPlugin = {\n name: 'leader-election',\n rxdb,\n prototypes,\n hooks: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AAA;EAElC,OAAOA,OAAO;AAClB;AAEA,OAAO,SAASU,QAAQ,GAA4B;EAChD,IAAI,CAAC,IAAI,CAACC,aAAa,EAAE;IACrB,OAAO,IAAI;EACf;EACA,OAAO,IAAI,CAACF,aAAa,EAAE,CAACC,QAAQ;AACxC;AAEA,OAAO,SAASE,iBAAiB,GAAqC;EAClE,IAAI,CAAC,IAAI,CAACD,aAAa,EAAE;IACrB,OAAOjB,oBAAoB;EAC/B,CAAC,MAAM;IACH,OAAO,IAAI,CAACe,aAAa,EAAE,CACtBI,eAAe,EAAE,CACjBC,IAAI,CAAC;MAAA,OAAM,IAAI;IAAA,EAAC;EACzB;AACJ;;AAEA;AACA;AACA;AACA,OAAO,SAASC,SAAS,CAACC,EAAc,EAAE;EACtC,IAAMC,GAAG,GAAGtB,qBAAqB,CAACM,GAAG,CAACe,EAAE,CAAC;EACzC,IAAIC,GAAG,EAAE;IACLA,GAAG,CAACC,GAAG,EAAE;EACb;AACJ;AAEA,OAAO,IAAMC,IAAI,GAAG,IAAI;AACxB,OAAO,IAAMC,UAAU,GAAG;EACtBC,UAAU,EAAE,oBAACC,KAAU,EAAK;IACxBA,KAAK,CAACb,aAAa,GAAGN,cAAc;IACpCmB,KAAK,CAACZ,QAAQ,GAAGA,QAAQ;IACzBY,KAAK,CAACV,iBAAiB,GAAGA,iBAAiB;EAC/C;AACJ,CAAC;AAED,OAAO,IAAMW,wBAAkC,GAAG;EAC9ClB,IAAI,EAAE,iBAAiB;EACvBc,IAAI,EAAJA,IAAI;EACJC,UAAU,EAAVA,UAAU;EACVI,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEX;IACX;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["createLeaderElection","getBroadcastChannelReference","removeBroadcastChannelReference","PROMISE_RESOLVE_TRUE","LEADER_ELECTORS_OF_DB","WeakMap","LEADER_ELECTOR_BY_BROADCAST_CHANNEL","getLeaderElectorByBroadcastChannel","broadcastChannel","elector","get","set","getForDatabase","token","name","oldDestroy","destroy","bind","leaderElector","isLeader","multiInstance","waitForLeadership","awaitLeadership","then","onDestroy","db","has","die","rxdb","prototypes","RxDatabase","proto","RxDBLeaderElectionPlugin","hooks","preDestroyRxDatabase","after"],"sources":["../../../../src/plugins/leader-election/index.ts"],"sourcesContent":["/**\n * this plugin adds the leader-election-capabilities to rxdb\n */\n\nimport {\n createLeaderElection,\n LeaderElector,\n BroadcastChannel\n} from 'broadcast-channel';\nimport {\n getBroadcastChannelReference,\n removeBroadcastChannelReference\n} from '../../rx-storage-multiinstance';\n\nimport type {\n RxDatabase,\n RxPlugin\n} from '../../types';\nimport { PROMISE_RESOLVE_TRUE } from '../utils';\n\nconst LEADER_ELECTORS_OF_DB: WeakMap = new WeakMap();\nconst LEADER_ELECTOR_BY_BROADCAST_CHANNEL: WeakMap = new WeakMap();\n\n\n/**\n * Returns the leader elector of a broadcast channel.\n * Used to ensure we reuse the same elector for the channel each time.\n */\nexport function getLeaderElectorByBroadcastChannel(broadcastChannel: BroadcastChannel): LeaderElector {\n let elector = LEADER_ELECTOR_BY_BROADCAST_CHANNEL.get(broadcastChannel);\n if (!elector) {\n elector = createLeaderElection(broadcastChannel);\n LEADER_ELECTOR_BY_BROADCAST_CHANNEL.set(broadcastChannel, elector);\n }\n return elector;\n}\n\n/**\n * @overwrites RxDatabase().leaderElector for caching\n */\nexport function getForDatabase(this: RxDatabase): LeaderElector {\n\n\n const broadcastChannel = getBroadcastChannelReference(\n this.token,\n this.name,\n this\n );\n\n /**\n * Clean up the reference on RxDatabase.destroy()\n */\n const oldDestroy = this.destroy.bind(this);\n this.destroy = function () {\n removeBroadcastChannelReference(this.token, this);\n return oldDestroy();\n };\n\n\n let elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n if (!elector) {\n elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n LEADER_ELECTORS_OF_DB.set(\n this,\n elector\n );\n }\n\n /**\n * Overwrite for caching\n */\n this.leaderElector = () => elector;\n\n return elector;\n}\n\nexport function isLeader(this: RxDatabase): boolean {\n if (!this.multiInstance) {\n return true;\n }\n return this.leaderElector().isLeader;\n}\n\nexport function waitForLeadership(this: RxDatabase): Promise {\n if (!this.multiInstance) {\n return PROMISE_RESOLVE_TRUE;\n } else {\n return this.leaderElector()\n .awaitLeadership()\n .then(() => true);\n }\n}\n\n/**\n * runs when the database gets destroyed\n */\nexport function onDestroy(db: RxDatabase) {\n const has = LEADER_ELECTORS_OF_DB.get(db);\n if (has) {\n has.die();\n }\n}\n\nexport const rxdb = true;\nexport const prototypes = {\n RxDatabase: (proto: any) => {\n proto.leaderElector = getForDatabase;\n proto.isLeader = isLeader;\n proto.waitForLeadership = waitForLeadership;\n }\n};\n\nexport const RxDBLeaderElectionPlugin: RxPlugin = {\n name: 'leader-election',\n rxdb,\n prototypes,\n hooks: {\n preDestroyRxDatabase: {\n after: onDestroy\n }\n }\n};\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SACIA,oBAAoB,QAGjB,mBAAmB;AAC1B,SACIC,4BAA4B,EAC5BC,+BAA+B,QAC5B,gCAAgC;AAMvC,SAASC,oBAAoB,QAAQ,UAAU;AAE/C,IAAMC,qBAAyD,GAAG,IAAIC,OAAO,EAAE;AAC/E,IAAMC,mCAA6E,GAAG,IAAID,OAAO,EAAE;;AAGnG;AACA;AACA;AACA;AACA,OAAO,SAASE,kCAAkC,CAACC,gBAAkC,EAAiB;EAClG,IAAIC,OAAO,GAAGH,mCAAmC,CAACI,GAAG,CAACF,gBAAgB,CAAC;EACvE,IAAI,CAACC,OAAO,EAAE;IACVA,OAAO,GAAGT,oBAAoB,CAACQ,gBAAgB,CAAC;IAChDF,mCAAmC,CAACK,GAAG,CAACH,gBAAgB,EAAEC,OAAO,CAAC;EACtE;EACA,OAAOA,OAAO;AAClB;;AAEA;AACA;AACA;AACA,OAAO,SAASG,cAAc,GAAkC;EAG5D,IAAMJ,gBAAgB,GAAGP,4BAA4B,CACjD,I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E,oBAACC,KAAU,EAAK;IACxBA,KAAK,CAACb,aAAa,GAAGN,cAAc;IACpCmB,KAAK,CAACZ,QAAQ,GAAGA,QAAQ;IACzBY,KAAK,CAACV,iBAAiB,GAAGA,iBAAiB;EAC/C;AACJ,CAAC;AAED,OAAO,IAAMW,wBAAkC,GAAG;EAC9ClB,IAAI,EAAE,iBAAiB;EACvBc,IAAI,EAAJA,IAAI;EACJC,UAAU,EAAVA,UAAU;EACVI,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEX;IACX;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/local-documents/local-documents-helper.js b/dist/es/plugins/local-documents/local-documents-helper.js index 2a527465516..2a2f5a58360 100644 --- a/dist/es/plugins/local-documents/local-documents-helper.js +++ b/dist/es/plugins/local-documents/local-documents-helper.js @@ -1,47 +1,42 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { filter } from 'rxjs/operators'; -import { DocCache } from '../../doc-cache'; +import { DocumentCache } from '../../doc-cache'; +import { IncrementalWriteQueue } from '../../incremental-write'; import { newRxError } from '../../rx-error'; import { fillWithDefaultSettings } from '../../rx-schema-helper'; import { getWrappedStorageInstance, storageChangeEventToRxChangeEvent } from '../../rx-storage-helper'; -import { randomCouchString } from '../../util'; -export var removeLocalDocumentsStorageInstance = function removeLocalDocumentsStorageInstance(storage, databaseName, collectionName) { - try { - var databaseInstanceToken = randomCouchString(10); - return Promise.resolve(createLocalDocumentStorageInstance(databaseInstanceToken, storage, databaseName, collectionName, {}, false)).then(function (storageInstance) { - return Promise.resolve(storageInstance.remove()).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } -}; -var LOCAL_DOC_STATE_BY_PARENT = new WeakMap(); +import { randomCouchString } from '../../plugins/utils'; +import { createRxLocalDocument } from './rx-local-document'; +export var LOCAL_DOC_STATE_BY_PARENT = new WeakMap(); +export var LOCAL_DOC_STATE_BY_PARENT_RESOLVED = new WeakMap(); export function createLocalDocStateByParent(parent) { var database = parent.database ? parent.database : parent; var collectionName = parent.database ? parent.name : ''; - var statePromise = function () { - try { - return Promise.resolve(createLocalDocumentStorageInstance(database.token, database.storage, database.name, collectionName, database.instanceCreationOptions, database.multiInstance)).then(function (storageInstance) { - storageInstance = getWrappedStorageInstance(database, storageInstance, RX_LOCAL_DOCUMENT_SCHEMA); - var docCache = new DocCache(); - - /** - * Update cached local documents on events. - */ - var sub = parent.$.pipe(filter(function (cE) { - return cE.isLocal; - })).subscribe(function (cE) { - var doc = docCache.get(cE.documentId); - if (doc) { - doc._handleChangeEvent(cE); - } - }); - parent._subs.push(sub); - - /** - * Emit the changestream into the collections change stream - */ - return Promise.resolve(database.storageToken).then(function (databaseStorageToken) { - var subLocalDocs = storageInstance.changeStream().subscribe(function (eventBulk) { + var statePromise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var storageInstance, docCache, incrementalWriteQueue, databaseStorageToken, subLocalDocs, state; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return createLocalDocumentStorageInstance(database.token, database.storage, database.name, collectionName, database.instanceCreationOptions, database.multiInstance); + case 2: + storageInstance = _context.sent; + storageInstance = getWrappedStorageInstance(database, storageInstance, RX_LOCAL_DOCUMENT_SCHEMA); + docCache = new DocumentCache('id', parent.$.pipe(filter(function (cE) { + return cE.isLocal; + })), function (docData) { + return createRxLocalDocument(docData, parent); + }); + incrementalWriteQueue = new IncrementalWriteQueue(storageInstance, 'id', function () {}, function () {}); + /** + * Emit the changestream into the collections change stream + */ + _context.next = 8; + return database.storageToken; + case 8: + databaseStorageToken = _context.sent; + subLocalDocs = storageInstance.changeStream().subscribe(function (eventBulk) { var changeEventBulk = { id: eventBulk.id, internal: false, @@ -57,18 +52,21 @@ export function createLocalDocStateByParent(parent) { database.$emit(changeEventBulk); }); parent._subs.push(subLocalDocs); - return { + state = { database: database, parent: parent, storageInstance: storageInstance, - docCache: docCache + docCache: docCache, + incrementalWriteQueue: incrementalWriteQueue }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }(); + LOCAL_DOC_STATE_BY_PARENT_RESOLVED.set(parent, state); + return _context.abrupt("return", state); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))(); LOCAL_DOC_STATE_BY_PARENT.set(parent, statePromise); } export function getLocalDocStateByParent(parent) { @@ -107,6 +105,30 @@ export function closeStateByParent(parent) { }); } } +export function removeLocalDocumentsStorageInstance(_x, _x2, _x3) { + return _removeLocalDocumentsStorageInstance.apply(this, arguments); +} +function _removeLocalDocumentsStorageInstance() { + _removeLocalDocumentsStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(storage, databaseName, collectionName) { + var databaseInstanceToken, storageInstance; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + databaseInstanceToken = randomCouchString(10); + _context2.next = 3; + return createLocalDocumentStorageInstance(databaseInstanceToken, storage, databaseName, collectionName, {}, false); + case 3: + storageInstance = _context2.sent; + _context2.next = 6; + return storageInstance.remove(); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _removeLocalDocumentsStorageInstance.apply(this, arguments); +} export function getCollectionLocalInstanceName(collectionName) { return 'plugin-local-documents-' + collectionName; } diff --git a/dist/es/plugins/local-documents/local-documents-helper.js.map b/dist/es/plugins/local-documents/local-documents-helper.js.map index 5029720aefc..d20adfadf82 100644 --- a/dist/es/plugins/local-documents/local-documents-helper.js.map +++ b/dist/es/plugins/local-documents/local-documents-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"local-documents-helper.js","names":["filter","DocCache","newRxError","fillWithDefaultSettings","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","randomCouchString","removeLocalDocumentsStorageInstance","storage","databaseName","collectionName","databaseInstanceToken","createLocalDocumentStorageInstance","storageInstance","remove","LOCAL_DOC_STATE_BY_PARENT","WeakMap","createLocalDocStateByParent","parent","database","name","statePromise","token","instanceCreationOptions","multiInstance","RX_LOCAL_DOCUMENT_SCHEMA","docCache","sub","$","pipe","cE","isLocal","subscribe","doc","get","documentId","_handleChangeEvent","_subs","push","storageToken","databaseStorageToken","subLocalDocs","changeStream","eventBulk","changeEventBulk","id","internal","undefined","events","map","ev","databaseToken","checkpoint","context","$emit","set","getLocalDocStateByParent","collection","createStorageInstance","getCollectionLocalInstanceName","schema","options","closeStateByParent","then","state","close","title","version","primaryKey","type","properties","maxLength","data","additionalProperties","required"],"sources":["../../../../src/plugins/local-documents/local-documents-helper.ts"],"sourcesContent":["import { filter } from 'rxjs/operators';\nimport { DocCache } from '../../doc-cache';\nimport { newRxError } from '../../rx-error';\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent\n} from '../../rx-storage-helper';\nimport type {\n LocalDocumentParent,\n LocalDocumentState,\n RxChangeEvent,\n RxChangeEventBulk,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxLocalDocument,\n RxLocalDocumentData,\n RxStorage\n} from '../../types';\nimport { randomCouchString } from '../../util';\n\nconst LOCAL_DOC_STATE_BY_PARENT: WeakMap> = new WeakMap();\n\n\nexport function createLocalDocStateByParent(parent: LocalDocumentParent): void {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n const statePromise = (async () => {\n let storageInstance = await createLocalDocumentStorageInstance(\n database.token,\n database.storage,\n database.name,\n collectionName,\n database.instanceCreationOptions,\n database.multiInstance\n );\n storageInstance = getWrappedStorageInstance(\n database,\n storageInstance,\n RX_LOCAL_DOCUMENT_SCHEMA\n );\n const docCache = new DocCache>();\n\n /**\n * Update cached local documents on events.\n */\n const sub = parent.$\n .pipe(\n filter(cE => (cE as RxChangeEvent).isLocal)\n )\n .subscribe((cE: RxChangeEvent) => {\n const doc = docCache.get(cE.documentId);\n if (doc) {\n doc._handleChangeEvent(cE);\n }\n });\n parent._subs.push(sub);\n\n /**\n * Emit the changestream into the collections change stream\n */\n const databaseStorageToken = await database.storageToken;\n const subLocalDocs = storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: parent.database ? parent.name : undefined,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n true,\n ev,\n parent.database ? parent as any : undefined\n )),\n databaseToken: database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n database.$emit(changeEventBulk);\n });\n parent._subs.push(subLocalDocs);\n\n return {\n database,\n parent,\n storageInstance,\n docCache\n };\n })();\n LOCAL_DOC_STATE_BY_PARENT.set(parent, statePromise);\n}\n\nexport function getLocalDocStateByParent(parent: LocalDocumentParent): Promise {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (!statePromise) {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n throw newRxError('LD8', {\n database: database.name,\n collection: collectionName\n });\n }\n return statePromise;\n}\n\n\nexport function createLocalDocumentStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n collectionName: string,\n instanceCreationOptions: any,\n multiInstance: boolean\n) {\n return storage.createStorageInstance({\n databaseInstanceToken,\n databaseName: databaseName,\n /**\n * Use a different collection name for the local documents instance\n * so that the local docs can be kept while deleting the normal instance\n * after migration.\n */\n collectionName: getCollectionLocalInstanceName(collectionName),\n schema: RX_LOCAL_DOCUMENT_SCHEMA,\n options: instanceCreationOptions,\n multiInstance\n });\n}\n\nexport function closeStateByParent(parent: LocalDocumentParent) {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (statePromise) {\n LOCAL_DOC_STATE_BY_PARENT.delete(parent);\n return statePromise.then(state => state.storageInstance.close());\n }\n}\n\nexport async function removeLocalDocumentsStorageInstance(\n storage: RxStorage,\n databaseName: string,\n collectionName: string\n) {\n const databaseInstanceToken = randomCouchString(10);\n const storageInstance = await createLocalDocumentStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n collectionName,\n {},\n false\n );\n await storageInstance.remove();\n}\n\n\nexport function getCollectionLocalInstanceName(collectionName: string): string {\n return 'plugin-local-documents-' + collectionName;\n}\n\nexport const RX_LOCAL_DOCUMENT_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n title: 'RxLocalDocument',\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 128\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n required: [\n 'id',\n 'data'\n ]\n});\n"],"mappings":"AAAA,SAASA,MAAM,QAAQ,gBAAgB;AACvC,SAASC,QAAQ,QAAQ,iBAAiB;AAC1C,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,uBAAuB,QAAQ,wBAAwB;AAChE,SACIC,yBAAyB,EACzBC,iCAAiC,QAC9B,yBAAyB;AAahC,SAASC,iBAAiB,QAAQ,YAAY;AAqH9C,WAAsBC,mCAAmC,YAAnCA,mCAAmC,CACrDC,OAA4B,EAC5BC,YAAoB,EACpBC,cAAsB;EAAA,IACxB;IACE,IAAMC,qBAAqB,GAAGL,iBAAiB,CAAC,EAAE,CAAC;IAAC,uBACtBM,kCAAkC,CAC5DD,qBAAqB,EACrBH,OAAO,EACPC,YAAY,EACZC,cAAc,EACd,CAAC,CAAC,EACF,KAAK,CACR,iBAPKG,eAAe;MAAA,uBAQfA,eAAe,CAACC,MAAM,EAAE;IAAA;EAClC,CAAC;IAAA;EAAA;AAAA;AAlID,IAAMC,yBAAoF,GAAG,IAAIC,OAAO,EAAE;AAG1G,OAAO,SAASC,2BAA2B,CAACC,MAA2B,EAAQ;EAC3E,IAAMC,QAAoB,GAAGD,MAAM,CAACC,QAAQ,GAAGD,MAAM,CAACC,QAAQ,GAAGD,MAAa;EA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,EACtBa,uBAA4B,EAC5BC,aAAsB,EACxB;EACE,OAAOhB,OAAO,CAACkD,qBAAqB,CAAsB;IACtD/C,qBAAqB,EAArBA,qBAAqB;IACrBF,YAAY,EAAEA,YAAY;IAC1B;AACR;AACA;AACA;AACA;IACQC,cAAc,EAAEiD,8BAA8B,CAACjD,cAAc,CAAC;IAC9DkD,MAAM,EAAEnC,wBAAwB;IAChCoC,OAAO,EAAEtC,uBAAuB;IAChCC,aAAa,EAAbA;EACJ,CAAC,CAAC;AACN;AAEA,OAAO,SAASsC,kBAAkB,CAAC5C,MAA2B,EAAE;EAC5D,IAAMG,YAAY,GAAGN,yBAAyB,CAACmB,GAAG,CAAChB,MAAM,CAAC;EAC1D,IAAIG,YAAY,EAAE;IACdN,yBAAyB,UAAO,CAACG,MAAM,CAAC;IACxC,OAAOG,YAAY,CAAC0C,IAAI,CAAC,UAAAC,KAAK;MAAA,OAAIA,KAAK,CAACnD,eAAe,CAACoD,KAAK,EAAE;IAAA,EAAC;EACpE;AACJ;AAoBA,OAAO,SAASN,8BAA8B,CAACjD,cAAsB,EAAU;EAC3E,OAAO,yBAAyB,GAAGA,cAAc;AACrD;AAEA,OAAO,IAAMe,wBAA2E,GAAGtB,uBAAuB,CAAC;EAC/G+D,KAAK,EAAE,iBAAiB;EACxBC,OAAO,EAAE,CAAC;EACVC,UAAU,EAAE,IAAI;EAChBC,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRzB,EAAE,EAAE;MACAwB,IAAI,EAAE,QAAQ;MACdE,SAAS,EAAE;IACf,CAAC;IACDC,IAAI,EAAE;MACFH,IAAI,EAAE,QAAQ;MACdI,oBAAoB,EAAE;IAC1B;EACJ,CAAC;EACDC,QAAQ,EAAE,CACN,IAAI,EACJ,MAAM;AAEd,CAAC,CAAC"} \ No newline at end of file +{"version":3,"file":"local-documents-helper.js","names":["filter","DocumentCache","IncrementalWriteQueue","newRxError","fillWithDefaultSettings","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","randomCouchString","createRxLocalDocument","LOCAL_DOC_STATE_BY_PARENT","WeakMap","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","createLocalDocStateByParent","parent","database","collectionName","name","statePromise","createLocalDocumentStorageInstance","token","storage","instanceCreationOptions","multiInstance","storageInstance","RX_LOCAL_DOCUMENT_SCHEMA","docCache","$","pipe","cE","isLocal","docData","incrementalWriteQueue","storageToken","databaseStorageToken","subLocalDocs","changeStream","subscribe","eventBulk","changeEventBulk","id","internal","undefined","events","map","ev","databaseToken","checkpoint","context","$emit","_subs","push","state","set","getLocalDocStateByParent","get","collection","databaseInstanceToken","databaseName","createStorageInstance","getCollectionLocalInstanceName","schema","options","closeStateByParent","then","close","removeLocalDocumentsStorageInstance","remove","title","version","primaryKey","type","properties","maxLength","data","additionalProperties","required"],"sources":["../../../../src/plugins/local-documents/local-documents-helper.ts"],"sourcesContent":["import { filter } from 'rxjs/operators';\nimport { DocumentCache } from '../../doc-cache';\nimport { IncrementalWriteQueue } from '../../incremental-write';\nimport { newRxError } from '../../rx-error';\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent\n} from '../../rx-storage-helper';\nimport type {\n LocalDocumentParent,\n LocalDocumentState,\n RxChangeEvent,\n RxChangeEventBulk,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxLocalDocumentData,\n RxStorage\n} from '../../types';\nimport { randomCouchString } from '../../plugins/utils';\nimport { createRxLocalDocument } from './rx-local-document';\n\nexport const LOCAL_DOC_STATE_BY_PARENT: WeakMap> = new WeakMap();\nexport const LOCAL_DOC_STATE_BY_PARENT_RESOLVED: WeakMap = new WeakMap();\n\n\nexport function createLocalDocStateByParent(parent: LocalDocumentParent): void {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n const statePromise = (async () => {\n let storageInstance = await createLocalDocumentStorageInstance(\n database.token,\n database.storage,\n database.name,\n collectionName,\n database.instanceCreationOptions,\n database.multiInstance\n );\n storageInstance = getWrappedStorageInstance(\n database,\n storageInstance,\n RX_LOCAL_DOCUMENT_SCHEMA\n );\n const docCache = new DocumentCache(\n 'id',\n parent.$.pipe(\n filter(cE => (cE as RxChangeEvent).isLocal)\n ),\n docData => createRxLocalDocument(docData, parent) as any\n );\n\n const incrementalWriteQueue = new IncrementalWriteQueue(\n storageInstance,\n 'id',\n () => { },\n () => { }\n );\n\n /**\n * Emit the changestream into the collections change stream\n */\n const databaseStorageToken = await database.storageToken;\n const subLocalDocs = storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: parent.database ? parent.name : undefined,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n true,\n ev,\n parent.database ? parent as any : undefined\n )),\n databaseToken: database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n database.$emit(changeEventBulk);\n });\n parent._subs.push(subLocalDocs);\n\n const state = {\n database,\n parent,\n storageInstance,\n docCache,\n incrementalWriteQueue\n };\n LOCAL_DOC_STATE_BY_PARENT_RESOLVED.set(parent, state);\n return state;\n })();\n LOCAL_DOC_STATE_BY_PARENT.set(parent, statePromise);\n}\n\nexport function getLocalDocStateByParent(parent: LocalDocumentParent): Promise {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (!statePromise) {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n throw newRxError('LD8', {\n database: database.name,\n collection: collectionName\n });\n }\n return statePromise;\n}\n\n\nexport function createLocalDocumentStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n collectionName: string,\n instanceCreationOptions: any,\n multiInstance: boolean\n) {\n return storage.createStorageInstance({\n databaseInstanceToken,\n databaseName: databaseName,\n /**\n * Use a different collection name for the local documents instance\n * so that the local docs can be kept while deleting the normal instance\n * after migration.\n */\n collectionName: getCollectionLocalInstanceName(collectionName),\n schema: RX_LOCAL_DOCUMENT_SCHEMA,\n options: instanceCreationOptions,\n multiInstance\n });\n}\n\nexport function closeStateByParent(parent: LocalDocumentParent) {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (statePromise) {\n LOCAL_DOC_STATE_BY_PARENT.delete(parent);\n return statePromise.then(state => state.storageInstance.close());\n }\n}\n\nexport async function removeLocalDocumentsStorageInstance(\n storage: RxStorage,\n databaseName: string,\n collectionName: string\n) {\n const databaseInstanceToken = randomCouchString(10);\n const storageInstance = await createLocalDocumentStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n collectionName,\n {},\n false\n );\n await storageInstance.remove();\n}\n\n\nexport function getCollectionLocalInstanceName(collectionName: string): string {\n return 'plugin-local-documents-' + collectionName;\n}\n\nexport const RX_LOCAL_DOCUMENT_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n title: 'RxLocalDocument',\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 128\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n required: [\n 'id',\n 'data'\n ]\n});\n"],"mappings":";;AAAA,SAASA,MAAM,QAAQ,gBAAgB;AACvC,SAASC,aAAa,QAAQ,iBAAiB;AAC/C,SAASC,qBAAqB,QAAQ,yBAAyB;AAC/D,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,uBAAuB,QAAQ,wBAAwB;AAChE,SACIC,yBAAyB,EACzBC,iCAAiC,QAC9B,yBAAyB;AAYhC,SAASC,iBAAiB,QAAQ,qBAAqB;AACvD,SAASC,qBAAqB,QAAQ,qBAAqB;AAE3D,OAAO,IAAMC,yBAAoF,GAAG,IAAIC,OAAO,EAAE;AACjH,OAAO,IAAMC,kCAAoF,GAAG,IAAID,OAAO,EAAE;AAGjH,OAAO,SAASE,2BAA2B,CAACC,MAA2B,EAAQ;EAC3E,IAAMC,QAA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AO,yBAAyB,GAAGA,cAAc;AACrD;AAEA,OAAO,IAAMS,wBAA2E,GAAGpB,uBAAuB,CAAC;EAC/G+D,KAAK,EAAE,iBAAiB;EACxBC,OAAO,EAAE,CAAC;EACVC,UAAU,EAAE,IAAI;EAChBC,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRhC,EAAE,EAAE;MACA+B,IAAI,EAAE,QAAQ;MACdE,SAAS,EAAE;IACf,CAAC;IACDC,IAAI,EAAE;MACFH,IAAI,EAAE,QAAQ;MACdI,oBAAoB,EAAE;IAC1B;EACJ,CAAC;EACDC,QAAQ,EAAE,CACN,IAAI,EACJ,MAAM;AAEd,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/local-documents/local-documents.js b/dist/es/plugins/local-documents/local-documents.js index 50915bb20d7..278114eb6d6 100644 --- a/dist/es/plugins/local-documents/local-documents.js +++ b/dist/es/plugins/local-documents/local-documents.js @@ -1,6 +1,7 @@ -import { flatClone, getDefaultRevision, getDefaultRxDocumentMeta } from '../../util'; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { getDefaultRevision, getDefaultRxDocumentMeta } from '../../plugins/utils'; import { filter, map, startWith, mergeMap } from 'rxjs/operators'; -import { createRxLocalDocument } from './rx-local-document'; import { getLocalDocStateByParent } from './local-documents-helper'; import { getSingleDocument, writeSingle } from '../../rx-storage-helper'; @@ -8,121 +9,173 @@ import { getSingleDocument, writeSingle } from '../../rx-storage-helper'; * save the local-document-data * throws if already exists */ - -export var getLocal = function getLocal(id) { - try { - var _this3 = this; - return Promise.resolve(getLocalDocStateByParent(_this3)).then(function (state) { - var docCache = state.docCache; - - // check in doc-cache - var found = docCache.get(id); - return found ? Promise.resolve(found) : getSingleDocument(state.storageInstance, id).then(function (docData) { - if (!docData) { - return null; - } - var doc = createRxLocalDocument(id, docData, _this3, state); - return doc; - })["catch"](function () { - return null; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var insertLocal = function insertLocal(id, data) { - try { - var _this = this; - return Promise.resolve(getLocalDocStateByParent(_this)).then(function (state) { - // create new one - var docData = { - id: id, - data: data, - _deleted: false, - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision(), - _attachments: {} - }; - return writeSingle(state.storageInstance, { - document: docData - }, 'local-document-insert').then(function (res) { - docData = flatClone(docData); - docData._rev = res._rev; - var newDoc = createRxLocalDocument(id, docData, _this, state); - return newDoc; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; +export function insertLocal(_x, _x2) { + return _insertLocal.apply(this, arguments); +} /** * save the local-document-data * overwrites existing if exists */ +function _insertLocal() { + _insertLocal = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(id, data) { + var state, docData; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getLocalDocStateByParent(this); + case 2: + state = _context3.sent; + // create new one + docData = { + id: id, + data: data, + _deleted: false, + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision(), + _attachments: {} + }; + return _context3.abrupt("return", writeSingle(state.storageInstance, { + document: docData + }, 'local-document-insert').then(function (newDocData) { + return state.docCache.getCachedRxDocument(newDocData); + })); + case 5: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + return _insertLocal.apply(this, arguments); +} export function upsertLocal(id, data) { - var _this2 = this; + var _this = this; return this.getLocal(id).then(function (existing) { if (!existing) { // create new one - var docPromise = _this2.insertLocal(id, data); + var docPromise = _this.insertLocal(id, data); return docPromise; } else { // update existing - return existing.atomicUpdate(function () { + return existing.incrementalModify(function () { return data; - }).then(function () { - return existing; }); } }); } -export function getLocal$(id) { - var _this4 = this; - return this.$.pipe(startWith(null), mergeMap(function (cE) { - try { - if (cE) { - return Promise.resolve({ - changeEvent: cE - }); - } else { - return Promise.resolve(_this4.getLocal(id)).then(function (doc) { - return { - doc: doc - }; - }); +export function getLocal(_x3) { + return _getLocal.apply(this, arguments); +} +function _getLocal() { + _getLocal = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(id) { + var state, docCache, found; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return getLocalDocStateByParent(this); + case 2: + state = _context4.sent; + docCache = state.docCache; // check in doc-cache + found = docCache.getLatestDocumentDataIfExists(id); + if (!found) { + _context4.next = 7; + break; + } + return _context4.abrupt("return", Promise.resolve(docCache.getCachedRxDocument(found))); + case 7: + return _context4.abrupt("return", getSingleDocument(state.storageInstance, id).then(function (docData) { + if (!docData) { + return null; + } + return state.docCache.getCachedRxDocument(docData); + })); + case 8: + case "end": + return _context4.stop(); } - } catch (e) { - return Promise.reject(e); - } - }), mergeMap(function (changeEventOrDoc) { - try { - if (changeEventOrDoc.changeEvent) { - var cE = changeEventOrDoc.changeEvent; - if (!cE.isLocal || cE.documentId !== id) { - return Promise.resolve({ - use: false - }); - } else { - return Promise.resolve(_this4.getLocal(id)).then(function (doc) { - return { + }, _callee4, this); + })); + return _getLocal.apply(this, arguments); +} +export function getLocal$(id) { + var _this2 = this; + return this.$.pipe(startWith(null), mergeMap( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(cE) { + var doc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!cE) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + changeEvent: cE + }); + case 4: + _context.next = 6; + return _this2.getLocal(id); + case 6: + doc = _context.sent; + return _context.abrupt("return", { + doc: doc + }); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref.apply(this, arguments); + }; + }()), mergeMap( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(changeEventOrDoc) { + var cE, doc; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!changeEventOrDoc.changeEvent) { + _context2.next = 12; + break; + } + cE = changeEventOrDoc.changeEvent; + if (!(!cE.isLocal || cE.documentId !== id)) { + _context2.next = 6; + break; + } + return _context2.abrupt("return", { + use: false + }); + case 6: + _context2.next = 8; + return _this2.getLocal(id); + case 8: + doc = _context2.sent; + return _context2.abrupt("return", { use: true, doc: doc - }; - }); + }); + case 10: + _context2.next = 13; + break; + case 12: + return _context2.abrupt("return", { + use: true, + doc: changeEventOrDoc.doc + }); + case 13: + case "end": + return _context2.stop(); } - } else { - return Promise.resolve({ - use: true, - doc: changeEventOrDoc.doc - }); - } - } catch (e) { - return Promise.reject(e); - } - }), filter(function (filterFlagged) { + }, _callee2); + })); + return function (_x5) { + return _ref2.apply(this, arguments); + }; + }()), filter(function (filterFlagged) { return filterFlagged.use; }), map(function (filterFlagged) { return filterFlagged.doc; diff --git a/dist/es/plugins/local-documents/local-documents.js.map b/dist/es/plugins/local-documents/local-documents.js.map index 23c5bbd5521..854a2e56230 100644 --- a/dist/es/plugins/local-documents/local-documents.js.map +++ b/dist/es/plugins/local-documents/local-documents.js.map @@ -1 +1 @@ -{"version":3,"file":"local-documents.js","names":["flatClone","getDefaultRevision","getDefaultRxDocumentMeta","filter","map","startWith","mergeMap","createRxLocalDocument","getLocalDocStateByParent","getSingleDocument","writeSingle","getLocal","id","state","docCache","found","get","Promise","resolve","storageInstance","then","docData","doc","insertLocal","data","_deleted","_meta","_rev","_attachments","document","res","newDoc","upsertLocal","existing","docPromise","atomicUpdate","getLocal$","$","pipe","cE","changeEvent","changeEventOrDoc","isLocal","documentId","use","filterFlagged"],"sources":["../../../../src/plugins/local-documents/local-documents.ts"],"sourcesContent":["import {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta\n} from '../../util';\n\nimport type {\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\n\nimport {\n filter,\n map,\n startWith,\n mergeMap\n} from 'rxjs/operators';\nimport { Observable } from 'rxjs';\n\nimport { createRxLocalDocument } from './rx-local-document';\nimport { getLocalDocStateByParent } from './local-documents-helper';\nimport { getSingleDocument, writeSingle } from '../../rx-storage-helper';\n\n\n\n/**\n * save the local-document-data\n * throws if already exists\n */\nexport async function insertLocal = any>(\n this: RxDatabase | RxCollection,\n id: string,\n data: DocData\n): Promise> {\n const state = await getLocalDocStateByParent(this);\n\n // create new one\n let docData: RxDocumentWriteData> = {\n id: id,\n data,\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n return writeSingle(\n state.storageInstance,\n {\n document: docData\n },\n 'local-document-insert'\n ).then(res => {\n docData = flatClone(docData);\n docData._rev = res._rev;\n const newDoc = createRxLocalDocument(id, docData as any, this, state);\n return newDoc as any;\n });\n}\n\n/**\n * save the local-document-data\n * overwrites existing if exists\n */\nexport function upsertLocal = any>(\n this: any,\n id: string,\n data: DocData\n): Promise> {\n return this.getLocal(id)\n .then((existing: RxDocument) => {\n if (!existing) {\n // create new one\n const docPromise = this.insertLocal(id, data);\n return docPromise;\n } else {\n // update existing\n return existing.atomicUpdate(() => {\n return data;\n }).then(() => existing);\n }\n });\n}\n\nexport async function getLocal(this: any, id: string): Promise | null> {\n const state = await getLocalDocStateByParent(this);\n const docCache = state.docCache;\n\n // check in doc-cache\n const found = docCache.get(id);\n if (found) {\n return Promise.resolve(found as any);\n }\n\n // if not found, check in storage instance\n return getSingleDocument(state.storageInstance, id)\n .then((docData) => {\n if (!docData) {\n return null;\n }\n const doc = createRxLocalDocument(id, docData, this, state);\n return doc as any;\n })\n .catch(() => null);\n}\n\nexport function getLocal$(this: RxCollection, id: string): Observable | null> {\n return this.$.pipe(\n startWith(null),\n mergeMap(async (cE: RxChangeEvent | null) => {\n if (cE) {\n return {\n changeEvent: cE\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n doc: doc\n };\n }\n }),\n mergeMap(async (changeEventOrDoc) => {\n if (changeEventOrDoc.changeEvent) {\n const cE = changeEventOrDoc.changeEvent;\n if (!cE.isLocal || cE.documentId !== id) {\n return {\n use: false\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n use: true,\n doc: doc\n };\n }\n } else {\n return {\n use: true,\n doc: changeEventOrDoc.doc\n };\n }\n }),\n filter(filterFlagged => filterFlagged.use),\n map(filterFlagged => {\n return filterFlagged.doc as any;\n })\n );\n}\n"],"mappings":"AAAA,SACIA,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,QACrB,YAAY;AAYnB,SACIC,MAAM,EACNC,GAAG,EACHC,SAAS,EACTC,QAAQ,QACL,gBAAgB;AAGvB,SAASC,qBAAqB,QAAQ,qBAAqB;AAC3D,SAASC,wBAAwB,QAAQ,0BAA0B;AACnE,SAASC,iBAAiB,EAAEC,WAAW,QAAQ,yBAAyB;;AAIxE;AACA;AACA;AACA;;AAwDA,WAAsBC,QAAQ,YAARA,QAAQ,CAA2BC,EAAU;EAAA,IAA4C;IAAA,aAC9D,IAAI;IAAA,uBAA7BJ,wBAAwB,QAAM,iBAA5CK,KAAK;MACX,IAAMC,QAAQ,GAAGD,KAAK,CAACC,QAAQ;;MAE/B;MACA,IAAMC,KAAK,GAAGD,QAAQ,CAACE,GAAG,CAACJ,EAAE,CAAC;MAAC,OAC3BG,KAAK,GACEE,OAAO,CAACC,OAAO,CAACH,KAAK,CAAQ,GAIjCN,iBAAiB,CAACI,KAAK,CAACM,eAAe,EAAEP,EAAE,CAAC,CAC9CQ,IAAI,CAAC,UAACC,OAAO,EAAK;QACf,IAAI,CAACA,OAAO,EAAE;UACV,OAAO,IAAI;QACf;QACA,IAAMC,GAAG,GAAGf,qBAAqB,CAACK,EAAE,EAAES,OAAO,UAAQR,KAAK,CAAC;QAC3D,OAAOS,GAAG;MACd,CAAC,CAAC,SACI,CAAC;QAAA,OAAM,IAAI;MA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-documents.js","names":["getDefaultRevision","getDefaultRxDocumentMeta","filter","map","startWith","mergeMap","getLocalDocStateByParent","getSingleDocument","writeSingle","insertLocal","id","data","state","docData","_deleted","_meta","_rev","_attachments","storageInstance","document","then","newDocData","docCache","getCachedRxDocument","upsertLocal","getLocal","existing","docPromise","incrementalModify","found","getLatestDocumentDataIfExists","Promise","resolve","getLocal$","$","pipe","cE","changeEvent","doc","changeEventOrDoc","isLocal","documentId","use","filterFlagged"],"sources":["../../../../src/plugins/local-documents/local-documents.ts"],"sourcesContent":["import {\n getDefaultRevision,\n getDefaultRxDocumentMeta\n} from '../../plugins/utils';\n\nimport type {\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\n\nimport {\n filter,\n map,\n startWith,\n mergeMap\n} from 'rxjs/operators';\nimport { Observable } from 'rxjs';\n\nimport { getLocalDocStateByParent } from './local-documents-helper';\nimport { getSingleDocument, writeSingle } from '../../rx-storage-helper';\n\n\n\n/**\n * save the local-document-data\n * throws if already exists\n */\nexport async function insertLocal = any>(\n this: RxDatabase | RxCollection,\n id: string,\n data: DocData\n): Promise> {\n const state = await getLocalDocStateByParent(this);\n\n // create new one\n const docData: RxDocumentWriteData> = {\n id: id,\n data,\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n return writeSingle(\n state.storageInstance,\n {\n document: docData\n },\n 'local-document-insert'\n ).then(newDocData => state.docCache.getCachedRxDocument(newDocData) as any);\n}\n\n/**\n * save the local-document-data\n * overwrites existing if exists\n */\nexport function upsertLocal = any>(\n this: any,\n id: string,\n data: DocData\n): Promise> {\n return this.getLocal(id)\n .then((existing: RxDocument) => {\n if (!existing) {\n // create new one\n const docPromise = this.insertLocal(id, data);\n return docPromise;\n } else {\n // update existing\n return existing.incrementalModify(() => {\n return data;\n });\n }\n });\n}\n\nexport async function getLocal(this: any, id: string): Promise | null> {\n const state = await getLocalDocStateByParent(this);\n const docCache = state.docCache;\n\n // check in doc-cache\n const found = docCache.getLatestDocumentDataIfExists(id);\n if (found) {\n return Promise.resolve(\n docCache.getCachedRxDocument(found) as any\n );\n }\n\n // if not found, check in storage instance\n return getSingleDocument(state.storageInstance, id)\n .then((docData) => {\n if (!docData) {\n return null;\n }\n return state.docCache.getCachedRxDocument(docData) as any;\n });\n}\n\nexport function getLocal$(this: RxCollection, id: string): Observable | null> {\n return this.$.pipe(\n startWith(null),\n mergeMap(async (cE: RxChangeEvent | null) => {\n if (cE) {\n return {\n changeEvent: cE\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n doc: doc\n };\n }\n }),\n mergeMap(async (changeEventOrDoc) => {\n if (changeEventOrDoc.changeEvent) {\n const cE = changeEventOrDoc.changeEvent;\n if (!cE.isLocal || cE.documentId !== id) {\n return {\n use: false\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n use: true,\n doc: doc\n };\n }\n } else {\n return {\n use: true,\n doc: changeEventOrDoc.doc\n };\n }\n }),\n filter(filterFlagged => filterFlagged.use),\n map(filterFlagged => {\n return filterFlagged.doc as any;\n })\n );\n}\n"],"mappings":";;AAAA,SACIA,kBAAkB,EAClBC,wBAAwB,QACrB,qBAAqB;AAY5B,SACIC,MAAM,EACNC,GAAG,EACHC,SAAS,EACTC,QAAQ,QACL,gBAAgB;AAGvB,SAASC,wBAAwB,QAAQ,0BAA0B;AACnE,SAASC,iBAAiB,EAAEC,WAAW,QAAQ,yBAAyB;;AAIxE;AACA;AACA;AACA;AACA,gBAAsBC,WAAW;EAAA;AAAA;;AA0BjC;AACA;AACA;AACA;AAHA;EAAA,wEA1BO,kBAEHC,EAAU,EACVC,IAAa;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEOL,wBAAwB,CAAC,IAAI,CAAC;QAAA;UAA5CM,KAAK;UAEX;UACMC,OAA0D,GAAG;YAC/DH,EAAE,EAAEA,EAAE;YACNC,IAAI,EAA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YAAA;UAAA;YAAA,kCAGE;cACHI,GAAG,EAAE,IAAI;cACTJ,GAAG,EAAEC,gBAAgB,CAACD;YAC1B,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CAER;IAAA;MAAA;IAAA;EAAA,IAAC,EACFpC,MAAM,CAAC,UAAAyC,aAAa;IAAA,OAAIA,aAAa,CAACD,GAAG;EAAA,EAAC,EAC1CvC,GAAG,CAAC,UAAAwC,aAAa,EAAI;IACjB,OAAOA,aAAa,CAACL,GAAG;EAC5B,CAAC,CAAC,CACL;AACL"} \ No newline at end of file diff --git a/dist/es/plugins/local-documents/rx-local-document.js b/dist/es/plugins/local-documents/rx-local-document.js index 5da9aa0ba66..81e9d53eec9 100644 --- a/dist/es/plugins/local-documents/rx-local-document.js +++ b/dist/es/plugins/local-documents/rx-local-document.js @@ -1,185 +1,27 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import objectPath from 'object-path'; -import { distinctUntilChanged, map } from 'rxjs/operators'; +import { distinctUntilChanged, filter, map, shareReplay, startWith } from 'rxjs/operators'; import { overwritable } from '../../overwritable'; +import { getDocumentDataOfRxChangeEvent } from '../../rx-change-event'; import { basePrototype, createRxDocumentConstructor } from '../../rx-document'; -import { isBulkWriteConflictError, newRxError, newRxTypeError } from '../../rx-error'; +import { newRxError, newRxTypeError } from '../../rx-error'; import { writeSingle } from '../../rx-storage-helper'; -import { clone, flatClone, getDefaultRevision, getDefaultRxDocumentMeta, getFromObjectOrThrow } from '../../util'; -import { getLocalDocStateByParent } from './local-documents-helper'; -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} +import { flatClone, getDefaultRevision, getDefaultRxDocumentMeta, getFromMapOrThrow, getFromObjectOrThrow, RXJS_SHARE_REPLAY_DEFAULTS } from '../../plugins/utils'; +import { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper'; var RxDocumentParent = createRxDocumentConstructor(); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} var RxLocalDocumentClass = /*#__PURE__*/function (_RxDocumentParent) { _inheritsLoose(RxLocalDocumentClass, _RxDocumentParent); - function RxLocalDocumentClass(id, jsonData, parent, state) { - var _this; - _this = _RxDocumentParent.call(this, null, jsonData) || this; - _this.id = id; - _this.parent = parent; - _this.state = state; - return _this; + function RxLocalDocumentClass(id, jsonData, parent) { + var _this2; + _this2 = _RxDocumentParent.call(this, null, jsonData) || this; + _this2.id = id; + _this2.parent = parent; + return _this2; } return RxLocalDocumentClass; }(RxDocumentParent); -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} var RxLocalDocumentPrototype = { get isLocal() { return true; @@ -187,22 +29,6 @@ var RxLocalDocumentPrototype = { // // overwrites // - _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) { - return; - } - switch (changeEvent.operation) { - case 'UPDATE': - this._dataSync$.next(changeEvent.documentData); - break; - case 'DELETE': - // remove from docCache to assure new upserted RxDocuments will be a new instance - var docCache = this.state.docCache; - docCache["delete"](this.primary); - this._dataSync$.next(changeEvent.documentData); - break; - } - }, get allAttachments$() { // this is overwritten here because we cannot re-set getters on the prototype throw newRxError('LD1', { @@ -216,10 +42,22 @@ var RxLocalDocumentPrototype = { return this.id; }, get $() { - return this._dataSync$.asObservable(); + var _this3 = this; + var _this = this; + return _this.parent.$.pipe(filter(function (changeEvent) { + return changeEvent.isLocal; + }), filter(function (changeEvent) { + return changeEvent.documentId === _this3.primary; + }), map(function (changeEvent) { + return getDocumentDataOfRxChangeEvent(changeEvent); + }), startWith(this._data), distinctUntilChanged(function (prev, curr) { + return prev._rev === curr._rev; + }), shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)); }, - $emit: function $emit(changeEvent) { - return this.parent.$emit(changeEvent); + getLatest: function getLatest() { + var state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent); + var latestDocData = state.docCache.getLatestDocumentData(this.primary); + return state.docCache.getCachedRxDocument(latestDocData); }, get: function get(objPath) { objPath = 'data.' + objPath; @@ -237,123 +75,143 @@ var RxLocalDocumentPrototype = { }, get$: function get$(objPath) { objPath = 'data.' + objPath; - if (objPath.includes('.item.')) { - throw newRxError('LD3', { - objPath: objPath - }); - } - if (objPath === this.primaryPath) { - throw newRxError('LD4'); + if (overwritable.isDevMode()) { + if (objPath.includes('.item.')) { + throw newRxError('LD3', { + objPath: objPath + }); + } + if (objPath === this.primaryPath) { + throw newRxError('LD4'); + } } - return this._dataSync$.pipe(map(function (data) { + return this.$.pipe(map(function (data) { return objectPath.get(data, objPath); }), distinctUntilChanged()); }, - atomicUpdate: function atomicUpdate(mutationFunction) { - var _this2 = this; - return new Promise(function (res, rej) { - _this2._atomicQueue = _this2._atomicQueue.then(function () { - try { - var _temp3 = function _temp3(_result2) { - if (_exit) return _result2; - res(_this2); - }; - var _exit = false; - var done = false; - // we need a hacky while loop to stay incide the chain-link of _atomicQueue - // while still having the option to run a retry on conflicts - var _temp2 = _for(function () { - return !_exit && !done; - }, void 0, function () { - var oldDocData = _this2._dataSync$.getValue(); - return Promise.resolve(mutationFunction(clone(oldDocData.data), _this2)).then(function (newData) { - var _temp = _catch(function () { - // always await because mutationFunction might be async - - var newDocData = flatClone(oldDocData); - newDocData.data = newData; - return Promise.resolve(_this2._saveData(newDocData, oldDocData)).then(function () { - done = true; - }); - }, function (err) { - /** - * conflicts cannot happen by just using RxDB in one process - * There are two ways they still can appear which is - * replication and multi-tab usage - * Because atomicUpdate has a mutation function, - * we can just re-run the mutation until there is no conflict - */ - var isConflict = isBulkWriteConflictError(err); - if (isConflict) {} else { - rej(err); - _exit = true; - } - }); - if (_temp && _temp.then) return _temp.then(function () {}); - }); - }); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); + incrementalModify: function () { + var _incrementalModify = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(mutationFunction) { + var _this4 = this; + var state; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return getLocalDocStateByParent(this.parent); + case 2: + state = _context2.sent; + return _context2.abrupt("return", state.incrementalWriteQueue.addWrite(this._data, /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(docData) { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return mutationFunction(docData.data, _this4); + case 2: + docData.data = _context.sent; + return _context.abrupt("return", docData); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x2) { + return _ref.apply(this, arguments); + }; + }()).then(function (result) { + return state.docCache.getCachedRxDocument(result); + })); + case 4: + case "end": + return _context2.stop(); } - }); - }); - }, - atomicPatch: function atomicPatch(patch) { - return this.atomicUpdate(function (docData) { - Object.entries(patch).forEach(function (_ref) { - var k = _ref[0], - v = _ref[1]; + }, _callee2, this); + })); + function incrementalModify(_x) { + return _incrementalModify.apply(this, arguments); + } + return incrementalModify; + }(), + incrementalPatch: function incrementalPatch(patch) { + return this.incrementalModify(function (docData) { + Object.entries(patch).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; docData[k] = v; }); return docData; }); }, - _saveData: function _saveData(newData) { - try { - var _this3 = this; - return Promise.resolve(getLocalDocStateByParent(_this3.parent)).then(function (state) { - var oldData = _this3._dataSync$.getValue(); - newData.id = _this3.id; - return state.storageInstance.bulkWrite([{ - previous: oldData, - document: newData - }], 'local-document-save-data').then(function (res) { - var docResult = res.success[newData.id]; - if (!docResult) { - throw getFromObjectOrThrow(res.error, newData.id); - } - newData = flatClone(newData); - newData._rev = docResult._rev; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }, - remove: function remove() { - try { - var _this4 = this; - return Promise.resolve(getLocalDocStateByParent(_this4.parent)).then(function (state) { - var writeData = { - id: _this4.id, - data: {}, - _deleted: true, - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision(), - _attachments: {} - }; - return writeSingle(state.storageInstance, { - previous: _this4._data, - document: writeData - }, 'local-document-remove').then(function () { - _this4.state.docCache["delete"](_this4.id); - }); - }); - } catch (e) { - return Promise.reject(e); + _saveData: function () { + var _saveData2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(newData) { + var state, oldData; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getLocalDocStateByParent(this.parent); + case 2: + state = _context3.sent; + oldData = this._data; + newData.id = this.id; + return _context3.abrupt("return", state.storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }], 'local-document-save-data').then(function (res) { + var docResult = res.success[newData.id]; + if (!docResult) { + throw getFromObjectOrThrow(res.error, newData.id); + } + newData = flatClone(newData); + newData._rev = docResult._rev; + })); + case 6: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _saveData(_x3) { + return _saveData2.apply(this, arguments); + } + return _saveData; + }(), + remove: function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { + var state, writeData; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return getLocalDocStateByParent(this.parent); + case 2: + state = _context4.sent; + writeData = { + id: this._data.id, + data: {}, + _deleted: true, + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision(), + _attachments: {} + }; + return _context4.abrupt("return", writeSingle(state.storageInstance, { + previous: this._data, + document: writeData + }, 'local-document-remove').then(function (writeResult) { + return state.docCache.getCachedRxDocument(writeResult); + })); + case 5: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function remove() { + return _remove.apply(this, arguments); } - } + return remove; + }() }; var INIT_DONE = false; var _init = function _init() { @@ -384,11 +242,11 @@ var _init = function _init() { return RxLocalDocumentPrototype[k] = getThrowingFun(k); }); }; -export function createRxLocalDocument(id, data, parent, state) { +export function createRxLocalDocument(data, parent) { _init(); - var newDoc = new RxLocalDocumentClass(id, data, parent, state); - newDoc.__proto__ = RxLocalDocumentPrototype; - state.docCache.set(id, newDoc); + var newDoc = new RxLocalDocumentClass(data.id, data, parent); + Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype); + newDoc.prototype = RxLocalDocumentPrototype; return newDoc; } //# sourceMappingURL=rx-local-document.js.map \ No newline at end of file diff --git a/dist/es/plugins/local-documents/rx-local-document.js.map b/dist/es/plugins/local-documents/rx-local-document.js.map index ebafb318c31..edecd1ef358 100644 --- a/dist/es/plugins/local-documents/rx-local-document.js.map +++ b/dist/es/plugins/local-documents/rx-local-document.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-local-document.js","names":["objectPath","distinctUntilChanged","map","overwritable","basePrototype","createRxDocumentConstructor","isBulkWriteConflictError","newRxError","newRxTypeError","writeSingle","clone","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","getFromObjectOrThrow","getLocalDocStateByParent","_catch","body","recover","result","e","then","RxDocumentParent","_settle","pact","state","value","s","_Pact","v","o","bind","observer","RxLocalDocumentClass","id","jsonData","parent","prototype","onFulfilled","onRejected","callback","_this","_isSettledPact","thenable","_for","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","RxLocalDocumentPrototype","isLocal","_handleChangeEvent","changeEvent","documentId","primary","operation","_dataSync$","next","documentData","docCache","allAttachments$","document","primaryPath","$","asObservable","$emit","get","objPath","_data","undefined","valueObj","deepFreezeWhenDevMode","get$","includes","pipe","data","atomicUpdate","mutationFunction","Promise","res","rej","_atomicQueue","done","oldDocData","getValue","newData","newDocData","_saveData","err","isConflict","atomicPatch","patch","docData","Object","entries","forEach","k","oldData","storageInstance","bulkWrite","previous","docResult","success","error","_rev","remove","writeData","_deleted","_meta","_attachments","INIT_DONE","_init","docBaseProto","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","__proto__","set"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\nimport { overwritable } from '../../overwritable';\nimport { basePrototype, createRxDocumentConstructor } from '../../rx-document';\nimport { isBulkWriteConflictError, newRxError, newRxTypeError } from '../../rx-error';\nimport { writeSingle } from '../../rx-storage-helper';\nimport type {\n LocalDocumentAtomicUpdateFunction,\n LocalDocumentState,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\nimport {\n clone,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromObjectOrThrow\n} from '../../util';\nimport { getLocalDocStateByParent } from './local-documents-helper';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase,\n public readonly state: LocalDocumentState\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n\n _handleChangeEvent(\n this: any,\n changeEvent: RxChangeEvent\n ) {\n if (changeEvent.documentId !== this.primary) {\n return;\n }\n switch (changeEvent.operation) {\n case 'UPDATE':\n this._dataSync$.next(changeEvent.documentData);\n break;\n case 'DELETE':\n // remove from docCache to assure new upserted RxDocuments will be a new instance\n const docCache = this.state.docCache;\n docCache.delete(this.primary);\n this._dataSync$.next(changeEvent.documentData);\n break;\n }\n },\n\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $() {\n return (this as RxDocument)._dataSync$.asObservable();\n },\n $emit(this: any, changeEvent: RxChangeEvent) {\n return this.parent.$emit(changeEvent);\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = objectPath.get(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n\n return this._dataSync$\n .pipe(\n map(data => objectPath.get(data, objPath)),\n distinctUntilChanged()\n );\n },\n atomicUpdate(mutationFunction: LocalDocumentAtomicUpdateFunction) {\n return new Promise((res, rej) => {\n this._atomicQueue = this._atomicQueue\n .then(async () => {\n let done = false;\n // we need a hacky while loop to stay incide the chain-link of _atomicQueue\n // while still having the option to run a retry on conflicts\n while (!done) {\n const oldDocData = this._dataSync$.getValue();\n const newData = await mutationFunction(clone(oldDocData.data), this);\n try {\n // always await because mutationFunction might be async\n\n const newDocData = flatClone(oldDocData);\n newDocData.data = newData;\n\n await this._saveData(newDocData, oldDocData);\n done = true;\n } catch (err) {\n /**\n * conflicts cannot happen by just using RxDB in one process\n * There are two ways they still can appear which is\n * replication and multi-tab usage\n * Because atomicUpdate has a mutation function,\n * we can just re-run the mutation until there is no conflict\n */\n const isConflict = isBulkWriteConflictError(err as any);\n if (isConflict) {\n // conflict error -> retrying\n } else {\n rej(err);\n return;\n }\n }\n }\n res(this);\n });\n });\n },\n atomicPatch(patch: Partial) {\n return this.atomicUpdate((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._dataSync$.getValue() as any;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[newData.id];\n if (!docResult) {\n throw getFromObjectOrThrow(res.error, newData.id);\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: any): Promise {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then(() => {\n this.state.docCache.delete(this.id);\n });\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n id: string,\n data: RxDocumentData>,\n parent: any,\n state: LocalDocumentState\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(id, data, parent, state);\n newDoc.__proto__ = RxLocalDocumentPrototype;\n state.docCache.set(id, newDoc as any);\n return newDoc as any;\n}\n"],"mappings":";AAAA,OAAOA,UAAU,MAAM,aAAa;AACpC,SAASC,oBAAoB,EAAEC,GAAG,QAAQ,gBAAgB;AAC1D,SAASC,YAAY,QAAQ,oBAAoB;AACjD,SAASC,aAAa,EAAEC,2BAA2B,QAAQ,mBAAmB;AAC9E,SAASC,wBAAwB,EAAEC,UAAU,EAAEC,cAAc,QAAQ,gBAAgB;AACrF,SAASC,WAAW,QAAQ,yBAAyB;AAarD,SACIC,KAAK,EACLC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,oBAAoB,QACjB,YAAY;AACnB,SAASC,wBAAwB,QAAQ,0BAA0B;AAyhB5D,SAASC,MAAM,CAACC,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AAjiBA,IAAMG,gBAAgB,GAAGjB,2BAA2B,EAAS;AAYtD,SAASkB,OA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EAAE;EACP,IAAMY,MAAM,GAAG,IAAI/F,oBAAoB,CAACC,EAAE,EAAE8C,IAAI,EAAE5C,MAAM,EAAEX,KAAK,CAAC;EAChEuG,MAAM,CAACC,SAAS,GAAG3E,wBAAwB;EAC3C7B,KAAK,CAACuC,QAAQ,CAACkE,GAAG,CAAChG,EAAE,EAAE8F,MAAM,CAAQ;EACrC,OAAOA,MAAM;AACjB"} \ No newline at end of file +{"version":3,"file":"rx-local-document.js","names":["objectPath","distinctUntilChanged","filter","map","shareReplay","startWith","overwritable","getDocumentDataOfRxChangeEvent","basePrototype","createRxDocumentConstructor","newRxError","newRxTypeError","writeSingle","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","getFromMapOrThrow","getFromObjectOrThrow","RXJS_SHARE_REPLAY_DEFAULTS","getLocalDocStateByParent","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","RxDocumentParent","RxLocalDocumentClass","id","jsonData","parent","RxLocalDocumentPrototype","isLocal","allAttachments$","document","primaryPath","primary","$","_this","pipe","changeEvent","documentId","_data","prev","curr","_rev","getLatest","state","latestDocData","docCache","getLatestDocumentData","getCachedRxDocument","get","objPath","undefined","valueObj","deepFreezeWhenDevMode","get$","isDevMode","includes","data","incrementalModify","mutationFunction","incrementalWriteQueue","addWrite","docData","then","result","incrementalPatch","patch","Object","entries","forEach","k","v","_saveData","newData","oldData","storageInstance","bulkWrite","previous","res","docResult","success","error","remove","writeData","_deleted","_meta","_attachments","writeResult","INIT_DONE","_init","docBaseProto","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","setPrototypeOf","prototype"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { Observable } from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs/operators';\nimport { overwritable } from '../../overwritable';\nimport { getDocumentDataOfRxChangeEvent } from '../../rx-change-event';\nimport {\n basePrototype,\n createRxDocumentConstructor\n} from '../../rx-document';\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error';\nimport { writeSingle } from '../../rx-storage-helper';\nimport type {\n LocalDocumentModifyFunction,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\nimport {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromMapOrThrow,\n getFromObjectOrThrow,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils';\nimport { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $(): Observable> {\n const _this: RxLocalDocumentClass = this as any;\n return _this.parent.$.pipe(\n filter(changeEvent => changeEvent.isLocal),\n filter(changeEvent => changeEvent.documentId === this.primary),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(this._data),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n },\n getLatest(this: RxLocalDocument): RxLocalDocument {\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n const latestDocData = state.docCache.getLatestDocumentData(this.primary);\n return state.docCache.getCachedRxDocument(latestDocData) as any;\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = objectPath.get(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (overwritable.isDevMode()) {\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n }\n return this.$\n .pipe(\n map(data => objectPath.get(data, objPath)),\n distinctUntilChanged()\n );\n },\n async incrementalModify(\n this: RxLocalDocument,\n mutationFunction: LocalDocumentModifyFunction\n ) {\n const state = await getLocalDocStateByParent(this.parent);\n\n return state.incrementalWriteQueue.addWrite(\n this._data as any,\n async (docData) => {\n docData.data = await mutationFunction(docData.data, this);\n return docData;\n }\n ).then(result => state.docCache.getCachedRxDocument(result as any));\n },\n incrementalPatch(patch: Partial) {\n return this.incrementalModify((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._data;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[newData.id];\n if (!docResult) {\n throw getFromObjectOrThrow(res.error, newData.id);\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: RxLocalDocument): Promise> {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this._data.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then((writeResult) => state.docCache.getCachedRxDocument(writeResult) as any);\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n data: RxDocumentData>,\n parent: any\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(data.id, data, parent);\n Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype);\n newDoc.prototype = RxLocalDocumentPrototype;\n return newDoc as any;\n}\n"],"mappings":";;;AAAA,OAAOA,UAAU,MAAM,aAAa;AAEpC,SACIC,oBAAoB,EACpBC,MAAM,EACNC,GAAG,EACHC,WAAW,EACXC,SAAS,QACN,gBAAgB;AACvB,SAASC,YAAY,QAAQ,oBAAoB;AACjD,SAASC,8BAA8B,QAAQ,uBAAuB;AACtE,SACIC,aAAa,EACbC,2BAA2B,QACxB,mBAAmB;AAC1B,SACIC,UAAU,EACVC,cAAc,QACX,gBAAgB;AACvB,SAASC,WAAW,QAAQ,yBAAyB;AAWrD,SACIC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,EACjBC,oBAAoB,EACpBC,0BAA0B,QACvB,qBAAqB;AAC5B,SAASC,wBAAwB,EAAEC,kCAAkC,QAAQ,0BAA0B;AAEvG,IAAMC,gBAA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c,CAACD,MAAM,EAAEzE,wBAAwB,CAAC;EACvDyE,MAAM,CAACE,SAAS,GAAG3E,wBAAwB;EAC3C,OAAOyE,MAAM;AACjB"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/index.js.map b/dist/es/plugins/lokijs/index.js.map deleted file mode 100644 index da75af4b1ef..00000000000 --- a/dist/es/plugins/lokijs/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/lokijs/index.ts"],"sourcesContent":["export * from './rx-storage-lokijs';\nexport * from './lokijs-helper';\nexport * from './rx-storage-instance-loki';\n"],"mappings":"AAAA,cAAc,qBAAqB;AACnC,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/loki-save-queue.js.map b/dist/es/plugins/lokijs/loki-save-queue.js.map deleted file mode 100644 index defe8cfae6f..00000000000 --- a/dist/es/plugins/lokijs/loki-save-queue.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"loki-save-queue.js","names":["PROMISE_RESOLVE_VOID","requestIdlePromise","LokiSaveQueue","lokiDatabase","databaseSettings","writesSinceLastRun","saveQueue","saveQueueC","addWrite","run","adapter","then","writeAmount","Promise","res","rej","saveDatabase","err","autosaveCallback"],"sources":["../../../../src/plugins/lokijs/loki-save-queue.ts"],"sourcesContent":["import type { LokiDatabaseSettings } from '../../types';\nimport {\n PROMISE_RESOLVE_VOID,\n requestIdlePromise\n} from '../../util';\n\n/**\n * The autosave feature of lokijs has strange behaviors\n * and often runs a save in critical moments when other\n * more important tasks are running.\n * So instead we use a custom save queue that ensures we\n * only run loki.saveDatabase() when nothing else is running.\n */\nexport class LokiSaveQueue {\n public writesSinceLastRun: number = 0;\n\n /**\n * Ensures that we do not run multiple saves\n * in parallel\n */\n public saveQueue: Promise = PROMISE_RESOLVE_VOID;\n // track amount of non-finished save calls in the queue.\n public saveQueueC = 0;\n\n constructor(\n public readonly lokiDatabase: Loki,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n\n }\n\n public addWrite() {\n this.writesSinceLastRun = this.writesSinceLastRun + 1;\n this.run();\n }\n\n public run() {\n if (\n // no persistence adapter given, so we do not need to save\n !this.databaseSettings.adapter ||\n // do not add more then two pending calls to the queue.\n this.saveQueueC > 2\n\n ) {\n return this.saveQueue;\n }\n\n this.saveQueueC = this.saveQueueC + 1;\n this.saveQueue = this.saveQueue\n .then(async () => {\n /**\n * Always wait until the JavaScript process is idle.\n * This ensures that CPU blocking writes are finished\n * before we proceed.\n */\n await requestIdlePromise();\n\n // no write happened since the last save call\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n /**\n * Because LokiJS is a in-memory database,\n * we can just wait until the JavaScript process is idle\n * via requestIdlePromise(). Then we know that nothing important\n * is running at the moment.\n */\n await requestIdlePromise().then(() => requestIdlePromise());\n\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n const writeAmount = this.writesSinceLastRun;\n this.writesSinceLastRun = 0;\n return new Promise((res, rej) => {\n this.lokiDatabase.saveDatabase(err => {\n if (err) {\n this.writesSinceLastRun = this.writesSinceLastRun + writeAmount;\n rej(err);\n } else {\n if (this.databaseSettings.autosaveCallback) {\n this.databaseSettings.autosaveCallback();\n }\n res();\n }\n });\n });\n })\n .catch(() => { })\n .then(() => {\n this.saveQueueC = this.saveQueueC - 1;\n });\n return this.saveQueue;\n }\n}\n"],"mappings":"AACA,SACIA,oBAAoB,EACpBC,kBAAkB,QACf,YAAY;;AAEnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;;EAEI;;EAGA,uBACoBC,YAAkB,EAClBC,gBAAsC,EACxD;IAAA,KAbKC,kBAAkB,GAAW,CAAC;IAAA,KAM9BC,SAAS,GAAkBN,oBAAoB;IAAA,KAE/CO,UAAU,GAAG,CAAC;IAAA,KAGDJ,YAAkB,GAAlBA,YAAkB;IAAA,KAClBC,gBAAsC,GAAtCA,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B,EAAE;kBAC5C;kBACAJ,GAAG,EAAE;gBACT;cACJ,CAAC,CAAC;YACN,CAAC,CAAC;UAAC;QAAA;MACP,CAAC;QAAA;MAAA;IAAA,EAAC,SACI,CAAC,YAAM,CAAE,CAAC,CAAC,CAChBH,IAAI,CAAC,YAAM;MACR,KAAI,CAACJ,UAAU,GAAG,KAAI,CAACA,UAAU,GAAG,CAAC;IACzC,CAAC,CAAC;IACN,OAAO,IAAI,CAACD,SAAS;EACzB,CAAC;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/lokijs-helper.js b/dist/es/plugins/lokijs/lokijs-helper.js deleted file mode 100644 index 5d64973767d..00000000000 --- a/dist/es/plugins/lokijs/lokijs-helper.js +++ /dev/null @@ -1,593 +0,0 @@ -import { createLokiLocalState } from './rx-storage-instance-loki'; -import lokijs from 'lokijs'; -import { add as unloadAdd } from 'unload'; -import { ensureNotFalsy, flatClone, promiseWait, randomCouchString } from '../../util'; -import { LokiSaveQueue } from './loki-save-queue'; -import { newRxError } from '../../rx-error'; -import objectPath from 'object-path'; -import { getBroadcastChannelReference } from '../../rx-storage-multiinstance'; -import { getLeaderElectorByBroadcastChannel } from '../leader-election'; -/** - * If the local state must be used, that one is returned. - * Returns false if a remote instance must be used. - */ - -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -export var mustUseLocalState = function mustUseLocalState(instance) { - try { - if (instance.closed) { - /** - * If this happens, it means that RxDB made a call to an already closed storage instance. - * This must never happen because when RxDB closes a collection or database, - * all tasks must be cleared so that no more calls are made the the storage. - */ - throw newRxError('SNH', { - args: { - instanceClosed: instance.closed, - databaseName: instance.databaseName, - collectionName: instance.collectionName - } - }); - } - if (instance.internals.localState) { - return Promise.resolve(instance.internals.localState); - } - var leaderElector = ensureNotFalsy(instance.internals.leaderElector); - return Promise.resolve(waitUntilHasLeader(leaderElector)).then(function () { - /** - * It might already have a localState after the applying - * because another subtask also called mustUSeLocalState() - */ - if (instance.internals.localState) { - return instance.internals.localState; - } - if (leaderElector.isLeader && !instance.internals.localState) { - // own is leader, use local instance - instance.internals.localState = createLokiLocalState({ - databaseInstanceToken: instance.databaseInstanceToken, - databaseName: instance.databaseName, - collectionName: instance.collectionName, - options: instance.options, - schema: instance.schema, - multiInstance: instance.internals.leaderElector ? true : false - }, instance.databaseSettings); - return ensureNotFalsy(instance.internals.localState); - } else { - // other is leader, send message to remote leading instance - return false; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var waitUntilHasLeader = function waitUntilHasLeader(leaderElector) { - try { - var _temp7 = _for(function () { - return !leaderElector.hasLeader; - }, void 0, function () { - return Promise.resolve(leaderElector.applyOnce()).then(function () { - return Promise.resolve(promiseWait(0)).then(function () {}); - }); - }); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Handles a request that came from a remote instance via requestRemoteInstance() - * Runs the requested operation over the local db instance and sends back the result. - */ -export var handleRemoteRequest = function handleRemoteRequest(instance, msg) { - try { - var _temp6 = function () { - if (msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE && msg.requestId && msg.databaseName === instance.databaseName && msg.collectionName === instance.collectionName && !msg.response) { - var _temp5 = function _temp5() { - var response = { - response: true, - requestId: msg.requestId, - databaseName: instance.databaseName, - collectionName: instance.collectionName, - result: _result, - isError: _isError, - type: msg.type - }; - ensureNotFalsy(instance.internals.leaderElector).broadcastChannel.postMessage(response); - }; - var operation = msg.operation; - var params = msg.params; - var _result; - var _isError = false; - var _temp4 = _catch(function () { - var _ref2; - return Promise.resolve((_ref2 = instance)[operation].apply(_ref2, params)).then(function (_operation) { - _result = _operation; - }); - }, function (err) { - console.dir(err); - _isError = true; - _result = err; - }); - return _temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4); - } - }(); - return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * For multi-instance usage, we send requests to the RxStorage - * to the current leading instance over the BroadcastChannel. - */ -export var requestRemoteInstance = function requestRemoteInstance(instance, operation, params) { - try { - var isRxStorageInstanceLoki = typeof instance.query === 'function'; - var messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE; - var leaderElector = ensureNotFalsy(instance.internals.leaderElector); - return Promise.resolve(waitUntilHasLeader(leaderElector)).then(function () { - var broadcastChannel = leaderElector.broadcastChannel; - var whenDeathListener; - var leaderDeadPromise = new Promise(function (res) { - whenDeathListener = function whenDeathListener(msg) { - if (msg.context === 'leader' && msg.action === 'death') { - res({ - retry: true - }); - } - }; - broadcastChannel.addEventListener('internal', whenDeathListener); - }); - var requestId = randomCouchString(12); - var responseListener; - var responsePromise = new Promise(function (res, _rej) { - responseListener = function responseListener(msg) { - if (msg.type === messageType && msg.response === true && msg.requestId === requestId) { - if (msg.isError) { - res({ - retry: false, - error: msg.result - }); - } else { - res({ - retry: false, - result: msg.result - }); - } - } - }; - broadcastChannel.addEventListener('message', responseListener); - }); - - // send out the request to the other instance - broadcastChannel.postMessage({ - response: false, - type: messageType, - operation: operation, - params: params, - requestId: requestId, - databaseName: instance.databaseName, - collectionName: instance.collectionName - }); - return Promise.race([leaderDeadPromise, responsePromise]).then(function (firstResolved) { - // clean up listeners - broadcastChannel.removeEventListener('message', responseListener); - broadcastChannel.removeEventListener('internal', whenDeathListener); - if (firstResolved.retry) { - var _ref; - /** - * The leader died while a remote request was running - * we re-run the whole operation. - * We cannot just re-run requestRemoteInstance() - * because the current instance might be the new leader now - * and then we have to use the local state instead of requesting the remote. - */ - return (_ref = instance)[operation].apply(_ref, params); - } else { - if (firstResolved.error) { - throw firstResolved.error; - } else { - return firstResolved.result; - } - } - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var closeLokiCollections = function closeLokiCollections(databaseName, collections) { - try { - return Promise.resolve(LOKI_DATABASE_STATE_BY_NAME.get(databaseName)).then(function (databaseState) { - if (!databaseState) { - // already closed - return; - } - return Promise.resolve(databaseState.saveQueue.run()).then(function () { - collections.forEach(function (collection) { - var collectionName = collection.name; - delete databaseState.collections[collectionName]; - }); - var _temp3 = function () { - if (Object.keys(databaseState.collections).length === 0) { - // all collections closed -> also close database - LOKI_DATABASE_STATE_BY_NAME["delete"](databaseName); - databaseState.unloads.forEach(function (u) { - return u.remove(); - }); - return Promise.resolve(new Promise(function (res, rej) { - databaseState.database.close(function (err) { - if (err) { - rej(err); - } else { - res(); - } - }); - })).then(function () {}); - } - }(); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * This function is at lokijs-helper - * because we need it in multiple places. - */ -export var CHANGES_COLLECTION_SUFFIX = '-rxdb-changes'; -export var LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request'; -export var LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object'; -export var RX_STORAGE_NAME_LOKIJS = 'lokijs'; - -/** - * Loki attaches a $loki property to all data - * which must be removed before returning the data back to RxDB. - */ -export function stripLokiKey(docData) { - if (!docData.$loki) { - return docData; - } - var cloned = flatClone(docData); - - /** - * In RxDB version 12.0.0, - * we introduced the _meta field that already contains the last write time. - * To be backwards compatible, we have to move the $lastWriteAt to the _meta field. - * TODO remove this in the next major version. - */ - if (cloned.$lastWriteAt) { - cloned._meta = { - lwt: cloned.$lastWriteAt - }; - delete cloned.$lastWriteAt; - } - delete cloned.$loki; - return cloned; -} - -/** - * Used to check in tests if all instances have been cleaned up. - */ -export var OPEN_LOKIJS_STORAGE_INSTANCES = new Set(); -export var LOKIJS_COLLECTION_DEFAULT_OPTIONS = { - disableChangesApi: true, - disableMeta: true, - disableDeltaChangesApi: true, - disableFreeze: true, - // TODO use 'immutable' like WatermelonDB does it - cloneMethod: 'shallow-assign', - clone: false, - transactional: false, - autoupdate: false -}; -var LOKI_DATABASE_STATE_BY_NAME = new Map(); -export function getLokiDatabase(databaseName, databaseSettings) { - var databaseState = LOKI_DATABASE_STATE_BY_NAME.get(databaseName); - if (!databaseState) { - /** - * We assume that as soon as an adapter is passed, - * the database has to be persistend. - */ - var hasPersistence = !!databaseSettings.adapter; - databaseState = function () { - try { - var _temp2 = function _temp2() { - /** - * Autosave database on process end - */ - var unloads = []; - if (hasPersistence) { - unloads.push(unloadAdd(function () { - return lokiSaveQueue.run(); - })); - } - var state = { - database: database, - databaseSettings: useSettings, - saveQueue: lokiSaveQueue, - collections: {}, - unloads: unloads - }; - return state; - }; - var persistenceMethod = hasPersistence ? 'adapter' : 'memory'; - if (databaseSettings.persistenceMethod) { - persistenceMethod = databaseSettings.persistenceMethod; - } - var useSettings = Object.assign( - // defaults - { - autoload: hasPersistence, - persistenceMethod: persistenceMethod, - verbose: true - }, databaseSettings, - // overwrites - { - /** - * RxDB uses its custom load and save handling - * so we disable the LokiJS save/load handlers. - */ - autoload: false, - autosave: false, - throttledSaves: false - }); - var database = new lokijs(databaseName + '.db', flatClone(useSettings)); - var lokiSaveQueue = new LokiSaveQueue(database, useSettings); - - /** - * Wait until all data is loaded from persistence adapter. - * Wrap the loading into the saveQueue to ensure that when many - * collections are created at the same time, the load-calls do not interfere - * with each other and cause error logs. - */ - var _temp = function () { - if (hasPersistence) { - var loadDatabasePromise = new Promise(function (res, rej) { - try { - database.loadDatabase({ - recursiveWait: false - }, function (err) { - if (useSettings.autoloadCallback) { - useSettings.autoloadCallback(err); - } - if (err) { - rej(err); - } else { - res(); - } - }); - } catch (err) { - rej(err); - } - }); - lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(function () { - return loadDatabasePromise; - }); - return Promise.resolve(loadDatabasePromise).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } - }(); - LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState); - } - return databaseState; -} -export function getLokiSortComparator(_schema, query) { - if (!query.sort) { - throw newRxError('SNH', { - query: query - }); - } - var sortOptions = query.sort; - var fun = function fun(a, b) { - var compareResult = 0; // 1 | -1 - sortOptions.find(function (sortPart) { - var fieldName = Object.keys(sortPart)[0]; - var direction = Object.values(sortPart)[0]; - var directionMultiplier = direction === 'asc' ? 1 : -1; - var valueA = objectPath.get(a, fieldName); - var valueB = objectPath.get(b, fieldName); - if (valueA === valueB) { - return false; - } else { - if (valueA > valueB) { - compareResult = 1 * directionMultiplier; - return true; - } else { - compareResult = -1 * directionMultiplier; - return true; - } - } - }); - - /** - * Two different objects should never have the same sort position. - * We ensure this by having the unique primaryKey in the sort params - * which is added by RxDB if not existing yet. - */ - if (!compareResult) { - throw newRxError('SNH', { - args: { - query: query, - a: a, - b: b - } - }); - } - return compareResult; - }; - return fun; -} -export function getLokiLeaderElector(databaseInstanceToken, broadcastChannelRefObject, databaseName) { - var broadcastChannel = getBroadcastChannelReference(databaseInstanceToken, databaseName, broadcastChannelRefObject); - var elector = getLeaderElectorByBroadcastChannel(broadcastChannel); - return elector; -} -//# sourceMappingURL=lokijs-helper.js.map \ No newline at end of file diff --git a/dist/es/plugins/lokijs/lokijs-helper.js.map b/dist/es/plugins/lokijs/lokijs-helper.js.map deleted file mode 100644 index f030ea4c136..00000000000 --- a/dist/es/plugins/lokijs/lokijs-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-helper.js","names":["createLokiLocalState","lokijs","add","unloadAdd","ensureNotFalsy","flatClone","promiseWait","randomCouchString","LokiSaveQueue","newRxError","objectPath","getBroadcastChannelReference","getLeaderElectorByBroadcastChannel","body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","mustUseLocalState","instance","closed","args","instanceClosed","databaseName","collectionName","internals","localState","leaderElector","waitUntilHasLeader","isLeader","databaseInstanceToken","options","schema","multiInstance","databaseSettings","hasLeader","applyOnce","handleRemoteRequest","msg","type","LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE","requestId","response","isError","broadcastChannel","postMessage","operation","params","err","console","dir","requestRemoteInstance","isRxStorageInstanceLoki","query","messageType","LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE","whenDeathListener","leaderDeadPromise","Promise","res","context","action","retry","addEventListener","responseListener","responsePromise","_rej","error","race","firstResolved","removeEventListener","closeLokiCollections","collections","LOKI_DATABASE_STATE_BY_NAME","get","databaseState","saveQueue","run","forEach","collection","name","Object","keys","length","unloads","u","remove","rej","database","close","CHANGES_COLLECTION_SUFFIX","RX_STORAGE_NAME_LOKIJS","stripLokiKey","docData","$loki","cloned","$lastWriteAt","_meta","lwt","OPEN_LOKIJS_STORAGE_INSTANCES","Set","LOKIJS_COLLECTION_DEFAULT_OPTIONS","disableChangesApi","disableMeta","disableDeltaChangesApi","disableFreeze","cloneMethod","clone","transactional","autoupdate","Map","getLokiDatabase","hasPersistence","adapter","push","lokiSaveQueue","useSettings","persistenceMethod","assign","autoload","verbose","autosave","throttledSaves","loadDatabasePromise","loadDatabase","recursiveWait","autoloadCallback","set","getLokiSortComparator","_schema","sort","sortOptions","fun","a","b","compareResult","find","sortPart","fieldName","direction","values","directionMultiplier","valueA","valueB","getLokiLeaderElector","broadcastChannelRefObject","elector"],"sources":["../../../../src/plugins/lokijs/lokijs-helper.ts"],"sourcesContent":["import { createLokiLocalState, RxStorageInstanceLoki } from './rx-storage-instance-loki';\nimport lokijs, { Collection } from 'lokijs';\nimport type {\n LokiDatabaseSettings,\n LokiDatabaseState,\n LokiLocalDatabaseState,\n LokiRemoteResponseBroadcastMessage,\n MangoQuery,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport {\n add as unloadAdd,\n AddReturn\n} from 'unload';\nimport { ensureNotFalsy, flatClone, promiseWait, randomCouchString } from '../../util';\nimport { LokiSaveQueue } from './loki-save-queue';\nimport type { DeterministicSortComparator } from 'event-reduce-js';\nimport { newRxError } from '../../rx-error';\nimport objectPath from 'object-path';\nimport {\n LeaderElector,\n OnMessageHandler\n} from 'broadcast-channel';\nimport { getBroadcastChannelReference } from '../../rx-storage-multiinstance';\nimport { getLeaderElectorByBroadcastChannel } from '../leader-election';\n\nexport const CHANGES_COLLECTION_SUFFIX = '-rxdb-changes';\nexport const LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request';\nexport const LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object';\nexport const RX_STORAGE_NAME_LOKIJS = 'lokijs';\n\n/**\n * Loki attaches a $loki property to all data\n * which must be removed before returning the data back to RxDB.\n */\nexport function stripLokiKey(docData: RxDocumentData & { $loki?: number; }): T {\n if (!docData.$loki) {\n return docData;\n }\n const cloned = flatClone(docData);\n\n /**\n * In RxDB version 12.0.0,\n * we introduced the _meta field that already contains the last write time.\n * To be backwards compatible, we have to move the $lastWriteAt to the _meta field.\n * TODO remove this in the next major version.\n */\n if ((cloned as any).$lastWriteAt) {\n cloned._meta = {\n lwt: (cloned as any).$lastWriteAt\n };\n delete (cloned as any).$lastWriteAt;\n }\n\n delete cloned.$loki;\n return cloned;\n}\n\n/**\n * Used to check in tests if all instances have been cleaned up.\n */\nexport const OPEN_LOKIJS_STORAGE_INSTANCES: Set> = new Set();\n\n\nexport const LOKIJS_COLLECTION_DEFAULT_OPTIONS: Partial> = {\n disableChangesApi: true,\n disableMeta: true,\n disableDeltaChangesApi: true,\n disableFreeze: true,\n // TODO use 'immutable' like WatermelonDB does it\n cloneMethod: 'shallow-assign',\n clone: false,\n transactional: false,\n autoupdate: false\n};\n\nconst LOKI_DATABASE_STATE_BY_NAME: Map> = new Map();\nexport function getLokiDatabase(\n databaseName: string,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n let databaseState: Promise | undefined = LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n /**\n * We assume that as soon as an adapter is passed,\n * the database has to be persistend.\n */\n const hasPersistence: boolean = !!databaseSettings.adapter;\n databaseState = (async () => {\n let persistenceMethod = hasPersistence ? 'adapter' : 'memory';\n if (databaseSettings.persistenceMethod) {\n persistenceMethod = databaseSettings.persistenceMethod;\n }\n const useSettings = Object.assign(\n // defaults\n {\n autoload: hasPersistence,\n persistenceMethod,\n verbose: true\n },\n databaseSettings,\n // overwrites\n {\n /**\n * RxDB uses its custom load and save handling\n * so we disable the LokiJS save/load handlers.\n */\n autoload: false,\n autosave: false,\n throttledSaves: false\n }\n );\n const database = new lokijs(\n databaseName + '.db',\n flatClone(useSettings)\n );\n const lokiSaveQueue = new LokiSaveQueue(\n database,\n useSettings\n );\n\n /**\n * Wait until all data is loaded from persistence adapter.\n * Wrap the loading into the saveQueue to ensure that when many\n * collections are created at the same time, the load-calls do not interfere\n * with each other and cause error logs.\n */\n if (hasPersistence) {\n const loadDatabasePromise = new Promise((res, rej) => {\n try {\n database.loadDatabase({\n recursiveWait: false\n }, (err) => {\n if (useSettings.autoloadCallback) {\n useSettings.autoloadCallback(err);\n }\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n } catch (err) {\n rej(err);\n }\n });\n lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(() => loadDatabasePromise);\n await loadDatabasePromise;\n }\n\n /**\n * Autosave database on process end\n */\n const unloads: AddReturn[] = [];\n if (hasPersistence) {\n unloads.push(\n unloadAdd(() => lokiSaveQueue.run())\n );\n }\n\n const state: LokiDatabaseState = {\n database,\n databaseSettings: useSettings,\n saveQueue: lokiSaveQueue,\n collections: {},\n unloads\n };\n\n return state;\n })();\n LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState);\n }\n return databaseState;\n}\n\nexport async function closeLokiCollections(\n databaseName: string,\n collections: Collection[]\n) {\n const databaseState = await LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n // already closed\n return;\n }\n await databaseState.saveQueue.run();\n collections.forEach(collection => {\n const collectionName = collection.name;\n delete databaseState.collections[collectionName];\n });\n if (Object.keys(databaseState.collections).length === 0) {\n // all collections closed -> also close database\n LOKI_DATABASE_STATE_BY_NAME.delete(databaseName);\n databaseState.unloads.forEach(u => u.remove());\n await new Promise((res, rej) => {\n databaseState.database.close(err => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n}\n\n/**\n * This function is at lokijs-helper\n * because we need it in multiple places.\n */\nexport function getLokiSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n const sortOptions: MangoQuerySortPart[] = query.sort;\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n let compareResult: number = 0; // 1 | -1\n sortOptions.find(sortPart => {\n const fieldName: string = Object.keys(sortPart)[0];\n const direction: MangoQuerySortDirection = Object.values(sortPart)[0];\n const directionMultiplier = direction === 'asc' ? 1 : -1;\n const valueA: any = objectPath.get(a as any, fieldName);\n const valueB: any = objectPath.get(b as any, fieldName);\n if (valueA === valueB) {\n return false;\n } else {\n if (valueA > valueB) {\n compareResult = 1 * directionMultiplier;\n return true;\n } else {\n compareResult = -1 * directionMultiplier;\n return true;\n }\n }\n });\n\n /**\n * Two different objects should never have the same sort position.\n * We ensure this by having the unique primaryKey in the sort params\n * which is added by RxDB if not existing yet.\n */\n if (!compareResult) {\n throw newRxError('SNH', { args: { query, a, b } });\n }\n\n return compareResult as any;\n };\n return fun;\n}\n\nexport function getLokiLeaderElector(\n databaseInstanceToken: string,\n broadcastChannelRefObject: any,\n databaseName: string\n): LeaderElector {\n const broadcastChannel = getBroadcastChannelReference(\n databaseInstanceToken,\n databaseName,\n broadcastChannelRefObject\n );\n const elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n return elector;\n}\n\n/**\n * For multi-instance usage, we send requests to the RxStorage\n * to the current leading instance over the BroadcastChannel.\n */\nexport async function requestRemoteInstance(\n instance: RxStorageInstanceLoki,\n operation: string,\n params: any[]\n): Promise {\n const isRxStorageInstanceLoki = typeof (instance as any).query === 'function';\n const messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE;\n\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n const broadcastChannel = leaderElector.broadcastChannel;\n\n type WinningPromise = {\n retry: boolean;\n result?: any;\n error?: any;\n };\n\n let whenDeathListener: OnMessageHandler;\n const leaderDeadPromise = new Promise(res => {\n whenDeathListener = (msg: any) => {\n if (msg.context === 'leader' && msg.action === 'death') {\n res({\n retry: true\n });\n }\n };\n broadcastChannel.addEventListener('internal', whenDeathListener);\n });\n const requestId = randomCouchString(12);\n let responseListener: OnMessageHandler;\n const responsePromise = new Promise((res, _rej) => {\n responseListener = (msg: any) => {\n if (\n msg.type === messageType &&\n msg.response === true &&\n msg.requestId === requestId\n ) {\n if (msg.isError) {\n res({\n retry: false,\n error: msg.result\n });\n } else {\n res({\n retry: false,\n result: msg.result\n });\n }\n }\n };\n broadcastChannel.addEventListener('message', responseListener);\n });\n\n // send out the request to the other instance\n broadcastChannel.postMessage({\n response: false,\n type: messageType,\n operation,\n params,\n requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n });\n\n\n return Promise.race([\n leaderDeadPromise,\n responsePromise\n ]).then(firstResolved => {\n\n // clean up listeners\n broadcastChannel.removeEventListener('message', responseListener);\n broadcastChannel.removeEventListener('internal', whenDeathListener);\n\n if (firstResolved.retry) {\n /**\n * The leader died while a remote request was running\n * we re-run the whole operation.\n * We cannot just re-run requestRemoteInstance()\n * because the current instance might be the new leader now\n * and then we have to use the local state instead of requesting the remote.\n */\n return (instance as any)[operation](...params);\n } else {\n if (firstResolved.error) {\n throw firstResolved.error;\n } else {\n return firstResolved.result;\n }\n }\n });\n}\n\n/**\n * Handles a request that came from a remote instance via requestRemoteInstance()\n * Runs the requested operation over the local db instance and sends back the result.\n */\nexport async function handleRemoteRequest(\n instance: RxStorageInstanceLoki,\n msg: any\n) {\n if (\n msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE &&\n msg.requestId &&\n msg.databaseName === instance.databaseName &&\n msg.collectionName === instance.collectionName &&\n !msg.response\n ) {\n const operation = (msg as any).operation;\n const params = (msg as any).params;\n let result: any;\n let isError = false;\n try {\n result = await (instance as any)[operation](...params);\n } catch (err) {\n console.dir(err);\n isError = true;\n result = err;\n }\n const response: LokiRemoteResponseBroadcastMessage = {\n response: true,\n requestId: msg.requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n result,\n isError,\n type: msg.type\n };\n ensureNotFalsy(instance.internals.leaderElector).broadcastChannel.postMessage(response);\n }\n}\n\n\nexport async function waitUntilHasLeader(leaderElector: LeaderElector) {\n while (\n !leaderElector.hasLeader\n ) {\n await leaderElector.applyOnce();\n await promiseWait(0);\n }\n}\n\n/**\n * If the local state must be used, that one is returned.\n * Returns false if a remote instance must be used.\n */\nexport async function mustUseLocalState(\n instance: RxStorageInstanceLoki\n): Promise {\n if (instance.closed) {\n /**\n * If this happens, it means that RxDB made a call to an already closed storage instance.\n * This must never happen because when RxDB closes a collection or database,\n * all tasks must be cleared so that no more calls are made the the storage.\n */\n throw newRxError('SNH', {\n args: {\n instanceClosed: instance.closed,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n }\n });\n }\n\n\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n\n /**\n * It might already have a localState after the applying\n * because another subtask also called mustUSeLocalState()\n */\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n\n if (\n leaderElector.isLeader &&\n !instance.internals.localState\n ) {\n // own is leader, use local instance\n instance.internals.localState = createLokiLocalState({\n databaseInstanceToken: instance.databaseInstanceToken,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n options: instance.options,\n schema: (instance as RxStorageInstanceLoki).schema,\n multiInstance: instance.internals.leaderElector ? true : false\n }, instance.databaseSettings);\n return ensureNotFalsy(instance.internals.localState);\n } else {\n // other is leader, send message to remote leading instance\n return false;\n }\n}\n"],"mappings":"AAAA,SAASA,oBAAoB,QAA+B,4BAA4B;AACxF,OAAOC,MAAM,MAAsB,QAAQ;AAY3C,SACIC,GAAG,IAAIC,SAAS,QAEb,QAAQ;AACf,SAASC,cAAc,EAAEC,SAAS,EAAEC,WAAW,EAAEC,iBAAiB,QAAQ,YAAY;AACtF,SAASC,aAAa,QAAQ,mBAAmB;AAEjD,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,OAAOC,UAAU,MAAM,aAAa;AAKpC,SAASC,4BAA4B,QAAQ,gCAAgC;AAC7E,SAASC,kCAAkC,QAAQ,oBAAoB;AAsYvE;AACA;AACA;AACA;;AA8IO,gBAAgBC,I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ff --git a/dist/es/plugins/lokijs/rx-storage-instance-loki.js b/dist/es/plugins/lokijs/rx-storage-instance-loki.js deleted file mode 100644 index d0c1d3f771e..00000000000 --- a/dist/es/plugins/lokijs/rx-storage-instance-loki.js +++ /dev/null @@ -1,392 +0,0 @@ -import { Subject } from 'rxjs'; -import { flatClone, now, ensureNotFalsy, isMaybeReadonlyArray, getFromMapOrThrow, getSortDocumentsByLastWriteTimeComparator, RX_META_LWT_MINIMUM, lastOfArray } from '../../util'; -import { newRxError } from '../../rx-error'; -import { closeLokiCollections, getLokiDatabase, OPEN_LOKIJS_STORAGE_INSTANCES, LOKIJS_COLLECTION_DEFAULT_OPTIONS, stripLokiKey, getLokiSortComparator, getLokiLeaderElector, requestRemoteInstance, mustUseLocalState, handleRemoteRequest, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper'; -import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; -import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; -import { addRxStorageMultiInstanceSupport, removeBroadcastChannelReference } from '../../rx-storage-multiinstance'; -export var createLokiStorageInstance = function createLokiStorageInstance(storage, params, databaseSettings) { - try { - var _temp3 = function _temp3() { - var instance = new RxStorageInstanceLoki(params.databaseInstanceToken, storage, params.databaseName, params.collectionName, params.schema, _internals, params.options, databaseSettings); - addRxStorageMultiInstanceSupport(RX_STORAGE_NAME_LOKIJS, params, instance, _internals.leaderElector ? _internals.leaderElector.broadcastChannel : undefined); - if (params.multiInstance) { - /** - * Clean up the broadcast-channel reference on close() - */ - var closeBefore = instance.close.bind(instance); - instance.close = function () { - removeBroadcastChannelReference(params.databaseInstanceToken, broadcastChannelRefObject); - return closeBefore(); - }; - var removeBefore = instance.remove.bind(instance); - instance.remove = function () { - removeBroadcastChannelReference(params.databaseInstanceToken, broadcastChannelRefObject); - return removeBefore(); - }; - - /** - * Directly create the localState when/if the db becomes leader. - */ - ensureNotFalsy(_internals.leaderElector).awaitLeadership().then(function () { - if (!instance.closed) { - mustUseLocalState(instance); - } - }); - } - return instance; - }; - var _internals = {}; - var broadcastChannelRefObject = {}; - var _temp2 = function () { - if (params.multiInstance) { - var leaderElector = getLokiLeaderElector(params.databaseInstanceToken, broadcastChannelRefObject, params.databaseName); - _internals.leaderElector = leaderElector; - } else { - // optimisation shortcut, directly create db is non multi instance. - _internals.localState = createLokiLocalState(params, databaseSettings); - return Promise.resolve(_internals.localState).then(function () {}); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } -}; -export var createLokiLocalState = function createLokiLocalState(params, databaseSettings) { - try { - if (!params.options) { - params.options = {}; - } - return Promise.resolve(getLokiDatabase(params.databaseName, databaseSettings)).then(function (databaseState) { - /** - * Construct loki indexes from RxJsonSchema indexes. - * TODO what about compound indexes? Are they possible in lokijs? - */ - var indices = []; - if (params.schema.indexes) { - params.schema.indexes.forEach(function (idx) { - if (!isMaybeReadonlyArray(idx)) { - indices.push(idx); - } - }); - } - /** - * LokiJS has no concept of custom primary key, they use a number-id that is generated. - * To be able to query fast by primary key, we always add an index to the primary. - */ - var primaryKey = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey); - indices.push(primaryKey); - var lokiCollectionName = params.collectionName + '-' + params.schema.version; - var collectionOptions = Object.assign({}, lokiCollectionName, { - indices: indices, - unique: [primaryKey] - }, LOKIJS_COLLECTION_DEFAULT_OPTIONS); - var collection = databaseState.database.addCollection(lokiCollectionName, collectionOptions); - databaseState.collections[params.collectionName] = collection; - var ret = { - databaseState: databaseState, - collection: collection - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; -var instanceId = now(); -export var RxStorageInstanceLoki = /*#__PURE__*/function () { - function RxStorageInstanceLoki(databaseInstanceToken, storage, databaseName, collectionName, schema, internals, options, databaseSettings) { - var _this = this; - this.changes$ = new Subject(); - this.instanceId = instanceId++; - this.closed = false; - this.databaseInstanceToken = databaseInstanceToken; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - this.databaseSettings = databaseSettings; - this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); - OPEN_LOKIJS_STORAGE_INSTANCES.add(this); - if (this.internals.leaderElector) { - /** - * To run handleRemoteRequest(), - * the instance will call its own methods. - * But these methods could have already been swapped out by a RxStorageWrapper - * so we must store the original methods here and use them instead. - */ - var copiedSelf = { - bulkWrite: this.bulkWrite.bind(this), - changeStream: this.changeStream.bind(this), - cleanup: this.cleanup.bind(this), - close: this.close.bind(this), - query: this.query.bind(this), - count: this.count.bind(this), - findDocumentsById: this.findDocumentsById.bind(this), - collectionName: this.collectionName, - databaseName: this.databaseName, - conflictResultionTasks: this.conflictResultionTasks.bind(this), - getAttachmentData: this.getAttachmentData.bind(this), - getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this), - internals: this.internals, - options: this.options, - remove: this.remove.bind(this), - resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this), - schema: this.schema - }; - this.internals.leaderElector.awaitLeadership().then(function () { - // this instance is leader now, so it has to reply to queries from other instances - ensureNotFalsy(_this.internals.leaderElector).broadcastChannel.addEventListener('message', function (msg) { - return handleRemoteRequest(copiedSelf, msg); - }); - }); - } - } - var _proto = RxStorageInstanceLoki.prototype; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this2 = this; - if (documentWrites.length === 0) { - throw newRxError('P2', { - args: { - documentWrites: documentWrites - } - }); - } - return Promise.resolve(mustUseLocalState(_this2)).then(function (localState) { - if (!localState) { - return requestRemoteInstance(_this2, 'bulkWrite', [documentWrites]); - } - var ret = { - success: {}, - error: {} - }; - var docsInDb = new Map(); - var docsInDbWithLokiKey = new Map(); - documentWrites.forEach(function (writeRow) { - var id = writeRow.document[_this2.primaryPath]; - var documentInDb = localState.collection.by(_this2.primaryPath, id); - if (documentInDb) { - docsInDbWithLokiKey.set(id, documentInDb); - docsInDb.set(id, stripLokiKey(documentInDb)); - } - }); - var categorized = categorizeBulkWriteRows(_this2, _this2.primaryPath, docsInDb, documentWrites, context); - ret.error = categorized.errors; - categorized.bulkInsertDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this2.primaryPath]; - localState.collection.insert(flatClone(writeRow.document)); - ret.success[docId] = writeRow.document; - }); - categorized.bulkUpdateDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this2.primaryPath]; - var documentInDbWithLokiKey = getFromMapOrThrow(docsInDbWithLokiKey, docId); - var writeDoc = Object.assign({}, writeRow.document, { - $loki: documentInDbWithLokiKey.$loki - }); - localState.collection.update(writeDoc); - ret.success[docId] = writeRow.document; - }); - localState.databaseState.saveQueue.addWrite(); - if (categorized.eventBulk.events.length > 0) { - var lastState = getNewestOfDocumentStates(_this2.primaryPath, Object.values(ret.success)); - categorized.eventBulk.checkpoint = { - id: lastState[_this2.primaryPath], - lwt: lastState._meta.lwt - }; - _this2.changes$.next(categorized.eventBulk); - } - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - try { - var _this3 = this; - return Promise.resolve(mustUseLocalState(_this3)).then(function (localState) { - if (!localState) { - return requestRemoteInstance(_this3, 'findDocumentsById', [ids, deleted]); - } - var ret = {}; - ids.forEach(function (id) { - var documentInDb = localState.collection.by(_this3.primaryPath, id); - if (documentInDb && (!documentInDb._deleted || deleted)) { - ret[id] = stripLokiKey(documentInDb); - } - }); - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - try { - var _this4 = this; - return Promise.resolve(mustUseLocalState(_this4)).then(function (localState) { - if (!localState) { - return requestRemoteInstance(_this4, 'query', [preparedQuery]); - } - var query = localState.collection.chain().find(preparedQuery.selector); - if (preparedQuery.sort) { - query = query.sort(getLokiSortComparator(_this4.schema, preparedQuery)); - } - - /** - * Offset must be used before limit in LokiJS - * @link https://github.com/techfort/LokiJS/issues/570 - */ - if (preparedQuery.skip) { - query = query.offset(preparedQuery.skip); - } - if (preparedQuery.limit) { - query = query.limit(preparedQuery.limit); - } - var foundDocuments = query.data().map(function (lokiDoc) { - return stripLokiKey(lokiDoc); - }); - return { - documents: foundDocuments - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.count = function count(preparedQuery) { - try { - var _this5 = this; - return Promise.resolve(_this5.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { - throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.'); - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _this6 = this; - return Promise.resolve(mustUseLocalState(_this6)).then(function (localState) { - if (!localState) { - return requestRemoteInstance(_this6, 'getChangedDocumentsSince', [limit, checkpoint]); - } - var sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM; - var query = localState.collection.chain().find({ - '_meta.lwt': { - $gte: sinceLwt - } - }).sort(getSortDocumentsByLastWriteTimeComparator(_this6.primaryPath)); - var changedDocs = query.data(); - var first = changedDocs[0]; - if (checkpoint && first && first[_this6.primaryPath] === checkpoint.id && first._meta.lwt === checkpoint.lwt) { - changedDocs.shift(); - } - changedDocs = changedDocs.slice(0, limit); - var lastDoc = lastOfArray(changedDocs); - return { - documents: changedDocs.map(function (docData) { - return stripLokiKey(docData); - }), - checkpoint: lastDoc ? { - id: lastDoc[_this6.primaryPath], - lwt: lastDoc._meta.lwt - } : checkpoint ? checkpoint : { - id: '', - lwt: 0 - } - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.changeStream = function changeStream() { - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(minimumDeletedTime) { - try { - var _this7 = this; - return Promise.resolve(mustUseLocalState(_this7)).then(function (localState) { - if (!localState) { - return requestRemoteInstance(_this7, 'cleanup', [minimumDeletedTime]); - } - var deleteAmountPerRun = 10; - var maxDeletionTime = now() - minimumDeletedTime; - var query = localState.collection.chain().find({ - _deleted: true, - '_meta.lwt': { - $lt: maxDeletionTime - } - }).limit(deleteAmountPerRun); - var foundDocuments = query.data(); - if (foundDocuments.length > 0) { - localState.collection.remove(foundDocuments); - localState.databaseState.saveQueue.addWrite(); - } - return foundDocuments.length !== deleteAmountPerRun; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.close = function close() { - try { - var _this8 = this; - if (_this8.closed) { - return Promise.reject(new Error('already closed')); - } - _this8.closed = true; - _this8.changes$.complete(); - OPEN_LOKIJS_STORAGE_INSTANCES["delete"](_this8); - var _temp = function () { - if (_this8.internals.localState) { - return Promise.resolve(_this8.internals.localState).then(function (localState) { - return Promise.resolve(getLokiDatabase(_this8.databaseName, _this8.databaseSettings)).then(function (dbState) { - return Promise.resolve(dbState.saveQueue.run()).then(function () { - return Promise.resolve(closeLokiCollections(_this8.databaseName, [localState.collection])).then(function () {}); - }); - }); - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.remove = function remove() { - try { - var _this9 = this; - return Promise.resolve(mustUseLocalState(_this9)).then(function (localState) { - if (!localState) { - return requestRemoteInstance(_this9, 'remove', []); - } - localState.databaseState.database.removeCollection(localState.collection.name); - return Promise.resolve(localState.databaseState.saveQueue.run()).then(function () { - return _this9.close(); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstanceLoki; -}(); -//# sourceMappingURL=rx-storage-instance-loki.js.map \ No newline at end of file diff --git a/dist/es/plugins/lokijs/rx-storage-instance-loki.js.map b/dist/es/plugins/lokijs/rx-storage-instance-loki.js.map deleted file mode 100644 index 8db6446c942..00000000000 --- a/dist/es/plugins/lokijs/rx-storage-instance-loki.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-loki.js","names":["Subject","flatClone","now","ensureNotFalsy","isMaybeReadonlyArray","getFromMapOrThrow","getSortDocumentsByLastWriteTimeComparator","RX_META_LWT_MINIMUM","lastOfArray","newRxError","closeLokiCollections","getLokiDatabase","OPEN_LOKIJS_STORAGE_INSTANCES","LOKIJS_COLLECTION_DEFAULT_OPTIONS","stripLokiKey","getLokiSortComparator","getLokiLeaderElector","requestRemoteInstance","mustUseLocalState","handleRemoteRequest","RX_STORAGE_NAME_LOKIJS","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","addRxStorageMultiInstanceSupport","removeBroadcastChannelReference","createLokiStorageInstance","storage","params","databaseSettings","instance","RxStorageInstanceLoki","databaseInstanceToken","databaseName","collectionName","schema","internals","options","leaderElector","broadcastChannel","undefined","multiInstance","closeBefore","close","bind","broadcastChannelRefObject","removeBefore","remove","awaitLeadership","then","closed","localState","createLokiLocalState","databaseState","indices","indexes","forEach","idx","push","primaryKey","lokiCollectionName","version","collectionOptions","Object","assign","unique","collection","database","addCollection","collections","ret","instanceId","changes$","primaryPath","add","copiedSelf","bulkWrite","changeStream","cleanup","query","count","findDocumentsById","conflictResultionTasks","getAttachmentData","getChangedDocumentsSince","resolveConflictResultionTask","addEventListener","msg","documentWrites","context","length","args","success","error","docsInDb","Map","docsInDbWithLokiKey","writeRow","id","document","documentInDb","by","set","categorized","errors","bulkInsertDocs","docId","insert","bulkUpdateDocs","documentInDbWithLokiKey","writeDoc","$loki","update","saveQueue","addWrite","eventBulk","events","lastState","values","checkpoint","lwt","_meta","next","ids","deleted","_deleted","preparedQuery","chain","find","selector","sort","skip","offset","limit","foundDocuments","data","map","lokiDoc","documents","result","mode","_documentId","_attachmentId","Error","sinceLwt","$gte","changedDocs","first","shift","slice","lastDoc","docData","asObservable","minimumDeletedTime","deleteAmountPerRun","maxDeletionTime","$lt","Promise","reject","complete","dbState","run","removeCollection","name","_taskSolution"],"sources":["../../../../src/plugins/lokijs/rx-storage-instance-loki.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n flatClone,\n now,\n ensureNotFalsy,\n isMaybeReadonlyArray,\n getFromMapOrThrow,\n getSortDocumentsByLastWriteTimeComparator,\n RX_META_LWT_MINIMUM,\n lastOfArray\n} from '../../util';\nimport { newRxError } from '../../rx-error';\nimport type {\n RxStorageInstance,\n LokiSettings,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n MangoQuery,\n LokiStorageInternals,\n RxStorageInstanceCreationParams,\n LokiDatabaseSettings,\n LokiLocalDatabaseState,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n DeepReadonly,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n RxStorageCountResult\n} from '../../types';\nimport {\n closeLokiCollections,\n getLokiDatabase,\n OPEN_LOKIJS_STORAGE_INSTANCES,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS,\n stripLokiKey,\n getLokiSortComparator,\n getLokiLeaderElector,\n requestRemoteInstance,\n mustUseLocalState,\n handleRemoteRequest,\n RX_STORAGE_NAME_LOKIJS\n} from './lokijs-helper';\nimport type {\n Collection\n} from 'lokijs';\nimport type { RxStorageLoki } from './rx-storage-lokijs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport, removeBroadcastChannelReference } from '../../rx-storage-multiinstance';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceLoki implements RxStorageInstance<\n RxDocType,\n LokiStorageInternals,\n LokiSettings,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n\n public closed = false;\n\n constructor(\n public readonly databaseInstanceToken: string,\n public readonly storage: RxStorageLoki,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: LokiStorageInternals,\n public readonly options: Readonly,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n OPEN_LOKIJS_STORAGE_INSTANCES.add(this);\n if (this.internals.leaderElector) {\n\n\n /**\n * To run handleRemoteRequest(),\n * the instance will call its own methods.\n * But these methods could have already been swapped out by a RxStorageWrapper\n * so we must store the original methods here and use them instead.\n */\n const copiedSelf: RxStorageInstance = {\n bulkWrite: this.bulkWrite.bind(this),\n changeStream: this.changeStream.bind(this),\n cleanup: this.cleanup.bind(this),\n close: this.close.bind(this),\n query: this.query.bind(this),\n count: this.count.bind(this),\n findDocumentsById: this.findDocumentsById.bind(this),\n collectionName: this.collectionName,\n databaseName: this.databaseName,\n conflictResultionTasks: this.conflictResultionTasks.bind(this),\n getAttachmentData: this.getAttachmentData.bind(this),\n getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this),\n internals: this.internals,\n options: this.options,\n remove: this.remove.bind(this),\n resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this),\n schema: this.schema\n };\n\n this.internals.leaderElector.awaitLeadership().then(() => {\n // this instance is leader now, so it has to reply to queries from other instances\n ensureNotFalsy(this.internals.leaderElector).broadcastChannel\n .addEventListener('message', (msg) => handleRemoteRequest(copiedSelf as any, msg));\n });\n }\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n if (documentWrites.length === 0) {\n throw newRxError('P2', {\n args: {\n documentWrites\n }\n });\n }\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'bulkWrite', [documentWrites]);\n }\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const docsInDb: Map[StringKeys], RxDocumentData> = new Map();\n const docsInDbWithLokiKey: Map<\n RxDocumentData[StringKeys],\n RxDocumentData & { $loki: number; }\n > = new Map();\n documentWrites.forEach(writeRow => {\n const id = writeRow.document[this.primaryPath];\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (documentInDb) {\n docsInDbWithLokiKey.set(id as any, documentInDb);\n docsInDb.set(id as any, stripLokiKey(documentInDb));\n }\n });\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDb,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n localState.collection.insert(flatClone(writeRow.document));\n ret.success[docId as any] = writeRow.document;\n });\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n const documentInDbWithLokiKey = getFromMapOrThrow(docsInDbWithLokiKey, docId as any);\n const writeDoc: any = Object.assign(\n {},\n writeRow.document,\n {\n $loki: documentInDbWithLokiKey.$loki\n }\n );\n localState.collection.update(writeDoc);\n ret.success[docId as any] = writeRow.document;\n });\n localState.databaseState.saveQueue.addWrite();\n\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(categorized.eventBulk);\n }\n\n return ret;\n }\n async findDocumentsById(ids: string[], deleted: boolean): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'findDocumentsById', [ids, deleted]);\n }\n\n const ret: RxDocumentDataById = {};\n ids.forEach(id => {\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = stripLokiKey(documentInDb);\n }\n });\n return ret;\n }\n async query(preparedQuery: MangoQuery): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'query', [preparedQuery]);\n }\n\n let query = localState.collection\n .chain()\n .find(preparedQuery.selector);\n\n if (preparedQuery.sort) {\n query = query.sort(getLokiSortComparator(this.schema, preparedQuery));\n }\n\n /**\n * Offset must be used before limit in LokiJS\n * @link https://github.com/techfort/LokiJS/issues/570\n */\n if (preparedQuery.skip) {\n query = query.offset(preparedQuery.skip);\n }\n\n if (preparedQuery.limit) {\n query = query.limit(preparedQuery.limit);\n }\n\n const foundDocuments = query.data().map(lokiDoc => stripLokiKey(lokiDoc));\n return {\n documents: foundDocuments\n };\n }\n async count(\n preparedQuery: MangoQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.');\n }\n\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint | null\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'getChangedDocumentsSince', [limit, checkpoint]);\n }\n\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const query = localState.collection\n .chain()\n .find({\n '_meta.lwt': {\n $gte: sinceLwt\n }\n })\n .sort(getSortDocumentsByLastWriteTimeComparator(this.primaryPath as any));\n let changedDocs = query.data();\n\n const first = changedDocs[0];\n if (\n checkpoint &&\n first &&\n first[this.primaryPath] === checkpoint.id &&\n first._meta.lwt === checkpoint.lwt\n ) {\n changedDocs.shift();\n }\n\n changedDocs = changedDocs.slice(0, limit);\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs.map(docData => stripLokiKey(docData)),\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath],\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'cleanup', [minimumDeletedTime]);\n }\n\n const deleteAmountPerRun = 10;\n const maxDeletionTime = now() - minimumDeletedTime;\n const query = localState.collection\n .chain()\n .find({\n _deleted: true,\n '_meta.lwt': {\n $lt: maxDeletionTime\n }\n }).limit(deleteAmountPerRun);\n const foundDocuments = query.data();\n if (foundDocuments.length > 0) {\n localState.collection.remove(foundDocuments);\n localState.databaseState.saveQueue.addWrite();\n }\n\n return foundDocuments.length !== deleteAmountPerRun;\n }\n\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n OPEN_LOKIJS_STORAGE_INSTANCES.delete(this);\n\n if (this.internals.localState) {\n const localState = await this.internals.localState;\n const dbState = await getLokiDatabase(\n this.databaseName,\n this.databaseSettings\n );\n await dbState.saveQueue.run();\n await closeLokiCollections(\n this.databaseName,\n [\n localState.collection\n ]\n );\n }\n }\n async remove(): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'remove', []);\n }\n localState.databaseState.database.removeCollection(localState.collection.name);\n await localState.databaseState.saveQueue.run();\n return this.close();\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\nexport async function createLokiLocalState(\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n if (!params.options) {\n params.options = {};\n }\n\n const databaseState = await getLokiDatabase(\n params.databaseName,\n databaseSettings\n );\n\n /**\n * Construct loki indexes from RxJsonSchema indexes.\n * TODO what about compound indexes? Are they possible in lokijs?\n */\n const indices: string[] = [];\n if (params.schema.indexes) {\n params.schema.indexes.forEach(idx => {\n if (!isMaybeReadonlyArray(idx)) {\n indices.push(idx);\n }\n });\n }\n /**\n * LokiJS has no concept of custom primary key, they use a number-id that is generated.\n * To be able to query fast by primary key, we always add an index to the primary.\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n indices.push(primaryKey as string);\n\n const lokiCollectionName = params.collectionName + '-' + params.schema.version;\n const collectionOptions: Partial>> = Object.assign(\n {},\n lokiCollectionName,\n {\n indices: indices as string[],\n unique: [primaryKey]\n } as any,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS\n );\n\n const collection: Collection = databaseState.database.addCollection(\n lokiCollectionName,\n collectionOptions as any\n );\n databaseState.collections[params.collectionName] = collection;\n const ret: LokiLocalDatabaseState = {\n databaseState,\n collection\n };\n\n return ret;\n}\n\n\nexport async function createLokiStorageInstance(\n storage: RxStorageLoki,\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise> {\n const internals: LokiStorageInternals = {};\n\n const broadcastChannelRefObject: DeepReadonly = {};\n\n\n if (params.multiInstance) {\n const leaderElector = getLokiLeaderElector(\n params.databaseInstanceToken,\n broadcastChannelRefObject,\n params.databaseName\n );\n internals.leaderElector = leaderElector;\n } else {\n // optimisation shortcut, directly create db is non multi instance.\n internals.localState = createLokiLocalState(params, databaseSettings);\n await internals.localState;\n }\n\n const instance = new RxStorageInstanceLoki(\n params.databaseInstanceToken,\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n databaseSettings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_LOKIJS,\n params,\n instance,\n internals.leaderElector ? internals.leaderElector.broadcastChannel : undefined\n );\n\n if (params.multiInstance) {\n /**\n * Clean up the broadcast-channel reference on close()\n */\n const closeBefore = instance.close.bind(instance);\n instance.close = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return closeBefore();\n };\n const removeBefore = instance.remove.bind(instance);\n instance.remove = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return removeBefore();\n };\n\n /**\n * Directly create the localState when/if the db becomes leader.\n */\n ensureNotFalsy(internals.leaderElector)\n .awaitLeadership()\n .then(() => {\n if (!instance.closed) {\n mustUseLocalState(instance);\n }\n });\n }\n\n\n return instance;\n}\n"],"mappings":"AAAA,SACIA,OAAO,QAEJ,MAAM;AACb,SACIC,SAAS,EACTC,GAAG,EACHC,cAAc,EACdC,oBAAoB,EACpBC,iBAAiB,EACjBC,yCAAyC,EACzCC,mBAAmB,EACnBC,WAAW,QACR,YAAY;AACnB,SAASC,UAAU,QAAQ,gBAAgB;AAwB3C,SACIC,oBAAoB,EACpBC,eAAe,EACfC,6BAA6B,EAC7BC,iCAAiC,EACjCC,YAAY,EACZC,qBAAqB,EACrBC,oBAAoB,EACpBC,qBAAqB,EACrBC,iBAAiB,EACjBC,mBAAmB,EACnBC,sBAAsB,QACnB,iBAAiB;AAKxB,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SAASC,uBAAuB,EAAEC,yBAAyB,QAAQ,yBAAyB;AAC5F,SAASC,gCAAgC,EAAEC,+BAA+B,QAAQ,gCAAgC;AA4XlH,WAAsBC,yBAAyB,YAAzBA,yBAAyB,CAC3CC,OAAsB,EACtBC,MAAgE,EAChEC,gBAAsC;EAAA,IACG;IAAA;MAmBzC,IAAMC,QAAQ,GAAG,IAAIC,qBAAqB,CACtCH,MAAM,CAACI,qBAAqB,EAC5BL,OAAO,EACPC,MAAM,CAACK,YAAY,EACnBL,MAAM,CAACM,cAAc,EACrBN,MAAM,CAACO,MAAM,EACbC,UAAS,EACTR,MAAM,CAACS,OAAO,EACdR,gBAAgB,CACnB;MAEDL,gCAAgC,CAC5BJ,sBAAsB,EACtBQ,MAAM,EACNE,QAAQ,EACRM,UAAS,CAACE,aAAa,GAAGF,UAAS,CAACE,aAAa,CAACC,gBAAgB,GAAGC,SAAS,CACjF;MAED,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iC,UAAU;QAChB,IAAI,CAACA,UAAU,EAAE;UACb,OAAOlC,qBAAqB,SAAO,QAAQ,EAAE,EAAE,CAAC;QACpD;QACAkC,UAAU,CAACE,aAAa,CAACc,QAAQ,CAAC+F,gBAAgB,CAAC/G,UAAU,CAACe,UAAU,CAACiG,IAAI,CAAC;QAAC,uBACzEhH,UAAU,CAACE,aAAa,CAAC4D,SAAS,CAACgD,GAAG,EAAE;UAC9C,OAAO,OAAKtH,KAAK,EAAE;QAAC;MAAA;IACxB,CAAC;MAAA;IAAA;EAAA;EAAA,OAEDuC,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAIlF,OAAO,EAAE;EACxB,CAAC;EAAA,OACKqF,4BAA4B,yCAAC+E,aAAyD,EAAiB;IAAA;EAAE,CAAC;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/rx-storage-lokijs.js.map b/dist/es/plugins/lokijs/rx-storage-lokijs.js.map deleted file mode 100644 index 51e6a9689de..00000000000 --- a/dist/es/plugins/lokijs/rx-storage-lokijs.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-lokijs.js","names":["lokijs","ensureNotFalsy","flatClone","createLokiStorageInstance","getLokiSortComparator","RX_STORAGE_NAME_LOKIJS","ensureRxStorageInstanceParamsAreCorrect","DEFAULT_CHECKPOINT_SCHEMA","RxStorageLokiStatics","prepareQuery","_schema","mutateableQuery","Object","keys","selector","length","$and","_deleted","getSortComparator","schema","query","getQueryMatcher","fun","doc","docWithResetDeleted","fakeCollection","data","binaryIndices","setPrototypeOf","Collection","prototype","fakeResultSet","collection","Resultset","find","ret","filteredrows","checkpointSchema","RxStorageLoki","databaseSettings","name","statics","leaderElectorByLokiDbName","Map","createStorageInstance","params","getRxStorageLoki","storage"],"sources":["../../../../src/plugins/lokijs/rx-storage-lokijs.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport lokijs from 'lokijs';\nimport type {\n LokiDatabaseSettings,\n LokiSettings,\n LokiStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageStatics\n} from '../../types';\nimport {\n ensureNotFalsy,\n flatClone\n} from '../../util';\nimport {\n createLokiStorageInstance,\n RxStorageInstanceLoki\n} from './rx-storage-instance-loki';\nimport { getLokiSortComparator, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper';\nimport type { LeaderElector } from 'broadcast-channel';\n\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\n\nexport const RxStorageLokiStatics: RxStorageStatics = {\n prepareQuery(\n _schema: RxJsonSchema>,\n mutateableQuery: MangoQuery\n ) {\n mutateableQuery = flatClone(mutateableQuery);\n if (Object.keys(ensureNotFalsy(mutateableQuery.selector)).length > 0) {\n mutateableQuery.selector = {\n $and: [\n {\n _deleted: false\n },\n mutateableQuery.selector\n ]\n };\n } else {\n mutateableQuery.selector = {\n _deleted: false\n };\n }\n\n return mutateableQuery;\n },\n\n\n getSortComparator(\n schema: RxJsonSchema>,\n query: MangoQuery\n ): DeterministicSortComparator {\n return getLokiSortComparator(schema, query);\n },\n\n /**\n * Returns a function that determines if a document matches a query selector.\n * It is important to have the exact same logix as lokijs uses, to be sure\n * that the event-reduce algorithm works correct.\n * But LokisJS does not export such a function, the query logic is deep inside of\n * the Resultset prototype.\n * Because I am lazy, I do not copy paste and maintain that code.\n * Instead we create a fake Resultset and apply the prototype method Resultset.prototype.find(),\n * same with Collection.\n */\n getQueryMatcher(\n _schema: RxJsonSchema,\n query: MangoQuery\n ): QueryMatcher> {\n const fun: QueryMatcher> = (doc: RxDocumentWriteData) => {\n if (doc._deleted) {\n return false;\n }\n const docWithResetDeleted = flatClone(doc);\n docWithResetDeleted._deleted = !!docWithResetDeleted._deleted;\n\n const fakeCollection = {\n data: [docWithResetDeleted],\n binaryIndices: {}\n };\n Object.setPrototypeOf(fakeCollection, (lokijs as any).Collection.prototype);\n const fakeResultSet: any = {\n collection: fakeCollection\n };\n Object.setPrototypeOf(fakeResultSet, (lokijs as any).Resultset.prototype);\n fakeResultSet.find(query.selector, true);\n\n const ret = fakeResultSet.filteredrows.length > 0;\n return ret;\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n};\n\nexport class RxStorageLoki implements RxStorage {\n public name = RX_STORAGE_NAME_LOKIJS;\n public statics = RxStorageLokiStatics;\n\n /**\n * Create one leader elector by db name.\n * This is done inside of the storage, not globally\n * to make it easier to test multi-tab behavior.\n */\n public leaderElectorByLokiDbName: Map = new Map();\n\n constructor(\n public databaseSettings: LokiDatabaseSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n return createLokiStorageInstance(this, params, this.databaseSettings);\n }\n}\n\nexport function getRxStorageLoki(\n databaseSettings: LokiDatabaseSettings = {}\n): RxStorageLoki {\n const storage = new RxStorageLoki(databaseSettings);\n return storage;\n}\n"],"mappings":"AAIA,OAAOA,MAAM,MAAM,QAAQ;AAa3B,SACIC,cAAc,EACdC,SAAS,QACN,YAAY;AACnB,SACIC,yBAAyB,QAEtB,4BAA4B;AACnC,SAASC,qBAAqB,EAAEC,sBAAsB,QAAQ,iBAAiB;AAG/E,SAASC,uCAAuC,QAAQ,yBAAyB;AACjF,SAASC,yBAAyB,QAAQ,wBAAwB;AAElE,OAAO,IAAMC,oBAAsC,GAAG;EAClDC,YAAY,wBACRC,OAAgD,EAChDC,eAAsC,EACxC;IACEA,eAAe,GAAGT,SAAS,CAACS,eAAe,CAAC;IAC5C,IAAIC,MAAM,CAACC,IAAI,CAACZ,cAAc,CAACU,eAAe,CAACG,QAAQ,CAAC,CAAC,CAACC,MAAM,GAAG,CAAC,EAAE;MAClEJ,eAAe,CAACG,QAAQ,GAAG;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B,CAAC;AAED,WAAa+B,aAAa;EAItB;AACJ;AACA;AACA;AACA;;EAUI,uBACWC,gBAAsC,EAC/C;IAAA,KAnBKC,IAAI,GAAGnC,sBAAsB;IAAA,KAC7BoC,OAAO,GAAGjC,oBAAoB;IAAA,KAO9BkC,yBAAyB,GAO3B,IAAIC,GAAG,EAAE;IAAA,KAGHJ,gBAAsC,GAAtCA,gBAAsC;EAC7C;EAAC;EAAA,OAEEK,qBAAqB,GAA5B,+BACIC,MAAgE,EACvB;IACzCvC,uCAAuC,CAACuC,MAAM,CAAC;IAC/C,OAAO1C,yBAAyB,CAAC,IAAI,EAAE0C,MAAM,EAAE,IAAI,CAACN,gBAAgB,CAAC;EACzE,CAAC;EAAA;AAAA;AAGL,OAAO,SAASO,gBAAgB,GAEf;EAAA,IADbP,gBAAsC,uEAAG,CAAC,CAAC;EAE3C,IAAMQ,OAAO,GAAG,IAAIT,aAAa,CAACC,gBAAgB,CAAC;EACnD,OAAOQ,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/memory/binary-search-bounds.js.map b/dist/es/plugins/memory/binary-search-bounds.js.map deleted file mode 100644 index 4f3fa437f14..00000000000 --- a/dist/es/plugins/memory/binary-search-bounds.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"binary-search-bounds.js","names":["ge","a","y","c","l","h","i","m","x","p","undefined","gt","lt","le","eq","norm","f","length","boundGE","boundGT","boundLT","boundLE","boundEQ"],"sources":["../../../../src/plugins/memory/binary-search-bounds.ts"],"sourcesContent":["/**\n * Everything in this file was copied and adapted from\n * @link https://github.com/mikolalysenko/binary-search-bounds\n *\n * TODO We should use the original npm module instead when this bug is fixed:\n * @link https://github.com/mikolalysenko/binary-search-bounds/pull/14\n */\n\n\n\ntype Compare = ((a: T, b: T) => number | null | undefined);\n\nfunction ge(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i: number = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x: any = a[m];\n const p: any = (c !== undefined) ? c(x, y) : (x - (y as any));\n if (p >= 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction gt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p > 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction lt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p < 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction le(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p <= 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction eq(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p === 0) {\n return m;\n }\n if (p <= 0) {\n l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return -1;\n}\n\nfunction norm(a: T[], y: T, c: Compare, l: any, h: any, f: any) {\n if (typeof c === 'function') {\n return f(a, y, c, (l === undefined) ? 0 : l | 0, (h === undefined) ? a.length - 1 : h | 0);\n }\n return f(a, y, undefined, (c === undefined) ? 0 : c | 0, (l === undefined) ? a.length - 1 : l | 0);\n}\n\n\nexport function boundGE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, ge);\n}\nexport function boundGT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, gt);\n}\nexport function boundLT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, lt);\n}\nexport function boundLE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, le);\n}\nexport function boundEQ(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, eq);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,EAAE,CAAIC,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAS,GAAGD,CAAC,GAAG,CAAC;EACrB,OAAOD,CAAC,IAAIC,CAAC,EAAE;IACX,IAAME,CAAC,GAAIH,CAAC,GAAGC,CAAC,KAAM,CAAC;IACvB,IAAMG,CAAM,GAAGP,CAAC,CAACM,CAAC,CAAC;IACnB,IAAME,CAAM,GAAIN,CAAC,KAAKO,SAAS,GAAIP,CAAC,CAACK,CAAC,EAAEN,CAAC,CAAC,GAAIM,CAAC,GAAIN,CAAU;IAC7D,IAAIO,CAAC,IAAI,CAAC,EAAE;MACRH,CAAC,GAAGC,CAAC;MAAEF,CAAC,GAAGE,CAAC,GAAG,CAAC;IACpB,CAAC,MAAM;MACHH,CAAC,GAAGG,CAAC,GAAG,CAAC;IACb;EACJ;EACA,OAAOD,CAAC;AACZ;AAEA,SAASK,EAAE,CAAIV,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAC,GAAGD,CAAC,GAAG,CAAC;EACb,OAAOD,CAAC,IAAIC,CAAC,EAAE;IACX,IAAME,CAAC,GAAIH,CAAC,GAAGC,CAAC,KAAM,CAAC;IACvB,IAAMG,CAAC,GAAGP,CAAC,CAACM,CAAC,CAAC;IACd,IAAME,CAAM,GAAIN,CAAC,KAAKO,SAAS,GAAIP,CAAC,CAACK,CAAC,EAAEN,CAAC,CAA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M,SAAS,GAAIT,CAAC,CAACgB,MAAM,GAAG,CAAC,GAAGb,CAAC,GAAG,CAAC,CAAC;AACtG;AAGA,OAAO,SAASc,OAAO,CAAIjB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEL,EAAE,CAAC;AAClC;AACA,OAAO,SAASmB,OAAO,CAAIlB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEM,EAAE,CAAC;AAClC;AACA,OAAO,SAASS,OAAO,CAAInB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEO,EAAE,CAAC;AAClC;AACA,OAAO,SAASS,OAAO,CAAIpB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEQ,EAAE,CAAC;AAClC;AACA,OAAO,SAASS,OAAO,CAAIrB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAES,EAAE,CAAC;AAClC"} \ No newline at end of file diff --git a/dist/es/plugins/memory/index.js.map b/dist/es/plugins/memory/index.js.map deleted file mode 100644 index 0f65bd81ba8..00000000000 --- a/dist/es/plugins/memory/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["ensureRxStorageInstanceParamsAreCorrect","flatClone","RxStorageDexieStatics","createMemoryStorageInstance","getRxStorageMemory","settings","storage","name","statics","collectionStates","Map","createStorageInstance","params","collectionName","schema","version","useSettings","Object","assign","options"],"sources":["../../../../src/plugins/memory/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type { RxStorageInstanceCreationParams } from '../../types';\nimport { flatClone } from '../../util';\nimport { RxStorageDexieStatics } from '../dexie/dexie-statics';\nimport type {\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\nimport {\n createMemoryStorageInstance,\n RxStorageInstanceMemory\n} from './rx-storage-instance-memory';\n\nexport function getRxStorageMemory(\n settings: RxStorageMemorySettings = {}\n): RxStorageMemory {\n\n const storage: RxStorageMemory = {\n name: 'memory',\n statics: RxStorageDexieStatics,\n collectionStates: new Map(),\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n\n // TODO we should not need to append the schema version here.\n params = flatClone(params);\n params.collectionName = params.collectionName + '-' + params.schema.version;\n\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n\n\n return createMemoryStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './memory-helper';\nexport * from './binary-search-bounds';\nexport * from './memory-types';\nexport * from './memory-indexes';\nexport * from './rx-storage-instance-memory';\n"],"mappings":"AAAA,SAASA,uCAAuC,QAAQ,yBAAyB;AAEjF,SAASC,SAAS,QAAQ,YAAY;AACtC,SAASC,qBAAqB,QAAQ,wBAAwB;AAM9D,SACIC,2BAA2B,QAExB,8BAA8B;AAErC,OAAO,SAASC,kBAAkB,GAEf;EAAA,IADfC,QAAiC,uEAAG,CAAC,CAAC;EAGtC,IAAMC,OAAwB,GAAG;IAC7BC,IAAI,EAAE,QAAQ;IACdC,OAAO,EAAEN,qBAAqB;IAC9BO,gBAAgB,EAAE,IAAIC,GAAG,EAAE;IAC3BC,qBAAqB,iCACjBC,MAA0F,EAC/C;MAC3CZ,uCAAuC,CAACY,MAAM,CAAC;;MAE/C;MACAA,MAAM,GAAGX,SAAS,CAACW,MAAM,CAAC;MAC1BA,MAAM,CAACC,cAAc,GAAGD,MAAM,CAACC,cAAc,GAAG,GAAG,GAAGD,MAAM,CAACE,MAAM,CAACC,OAAO;MAE3E,IAAMC,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFb,QAAQ,EACRO,MAAM,CAACO,OAAO,CACjB;MAGD,OAAOhB,2BAA2B,CAAC,IAAI,EAAES,MAAM,EAAEI,WAAW,CAAC;IACjE;EACJ,CAAC;EAED,OAAOV,OAAO;AAClB;AAGA,cAAc,iBAAiB;AAC/B,cAAc,wBAAwB;AACtC,cAAc,gBAAgB;AAC9B,cAAc,kBAAkB;AAChC,cAAc,8BAA8B"} \ No newline at end of file diff --git a/dist/es/plugins/memory/memory-helper.js.map b/dist/es/plugins/memory/memory-helper.js.map deleted file mode 100644 index 7dcc102bd4e..00000000000 --- a/dist/es/plugins/memory/memory-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"memory-helper.js","names":["pushAtSortPosition","newRxError","boundEQ","getMemoryCollectionKey","databaseName","collectionName","ensureNotRemoved","instance","internals","removed","Error","attachmentMapKey","documentId","attachmentId","SORT_BY_INDEX_STRING","a","b","indexString","putWriteRowToState","docId","state","stateByIndex","row","docInState","documents","set","document","forEach","byIndex","docsWithIndex","newIndexString","getIndexableString","id","doc","insertPosition","previousIndexString","prev","splice","next","args","indexBefore","compareDocsWithIndex","removeDocFromState","primaryPath","schema","Object","values","positionInIndex"],"sources":["../../../../src/plugins/memory/memory-helper.ts"],"sourcesContent":["import type {\n BulkWriteRow,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport type {\n DocWithIndexString,\n MemoryStorageInternals,\n MemoryStorageInternalsByIndex\n} from './memory-types';\nimport type { RxStorageInstanceMemory } from './rx-storage-instance-memory';\nimport {\n pushAtSortPosition\n} from 'array-push-at-sort-position';\nimport { newRxError } from '../../rx-error';\nimport { boundEQ } from './binary-search-bounds';\n\n\nexport function getMemoryCollectionKey(\n databaseName: string,\n collectionName: string\n): string {\n return databaseName + '--memory--' + collectionName;\n}\n\n\nexport function ensureNotRemoved(\n instance: RxStorageInstanceMemory\n) {\n if (instance.internals.removed) {\n throw new Error('removed');\n }\n}\n\nexport function attachmentMapKey(documentId: string, attachmentId: string): string {\n return documentId + '||' + attachmentId;\n}\n\nconst SORT_BY_INDEX_STRING = (a: DocWithIndexString, b: DocWithIndexString) => {\n if (a.indexString < b.indexString) {\n return -1;\n } else {\n return 1;\n }\n};\n\n\n\nexport function putWriteRowToState(\n docId: string,\n state: MemoryStorageInternals,\n stateByIndex: MemoryStorageInternalsByIndex[],\n row: BulkWriteRow,\n docInState?: RxDocumentData\n) {\n state.documents.set(docId, row.document as any);\n stateByIndex.forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const newIndexString = byIndex.getIndexableString(row.document as any);\n const [, insertPosition] = pushAtSortPosition(\n docsWithIndex,\n {\n id: docId,\n doc: row.document,\n indexString: newIndexString\n },\n SORT_BY_INDEX_STRING,\n true\n );\n\n /**\n * Remove previous if it was in the state\n */\n if (docInState) {\n const previousIndexString = byIndex.getIndexableString(docInState);\n if (previousIndexString === newIndexString) {\n /**\n * Index not changed -> The old doc must be before or after the new one.\n */\n const prev = docsWithIndex[insertPosition - 1];\n if (prev && prev.id === docId) {\n docsWithIndex.splice(insertPosition - 1, 1);\n } else {\n const next = docsWithIndex[insertPosition + 1];\n if (next.id === docId) {\n docsWithIndex.splice(insertPosition + 1, 1);\n } else {\n throw newRxError('SNH', {\n args: {\n row,\n byIndex\n }\n });\n }\n }\n } else {\n /**\n * Index changed, we must search for the old one and remove it.\n */\n const indexBefore = boundEQ(\n docsWithIndex,\n {\n indexString: previousIndexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(indexBefore, 1);\n }\n }\n });\n}\n\n\nexport function removeDocFromState(\n primaryPath: string,\n schema: RxJsonSchema>,\n state: MemoryStorageInternals,\n doc: RxDocumentData\n) {\n const docId: string = (doc as any)[primaryPath];\n state.documents.delete(docId);\n\n Object.values(state.byIndex).forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const indexString = byIndex.getIndexableString(doc);\n\n const positionInIndex = boundEQ(\n docsWithIndex,\n {\n indexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(positionInIndex, 1);\n });\n}\n\n\nexport function compareDocsWithIndex(\n a: DocWithIndexString,\n b: DocWithIndexString\n): 1 | 0 | -1 {\n if (a.indexString < b.indexString) {\n return -1;\n } else if (a.indexString === b.indexString) {\n return 0;\n } else {\n return 1;\n }\n}\n"],"mappings":"AAWA,SACIA,kBAAkB,QACf,6BAA6B;AACpC,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,OAAO,QAAQ,wBAAwB;AAGhD,OAAO,SAASC,sBAAsB,CAClCC,YAAoB,EACpBC,cAAsB,EAChB;EACN,OAAOD,YAAY,GAAG,YAAY,GAAGC,cAAc;AACvD;AAGA,OAAO,SAASC,gBAAgB,CAC5BC,QAAsC,EACxC;EACE,IAAIA,QAAQ,CAACC,SAAS,CAACC,OAAO,EAAE;IAC5B,MAAM,IAAIC,KAAK,CAAC,SAAS,CAAC;EAC9B;AACJ;AAEA,OAAO,SAASC,gBAAgB,CAACC,UAAkB,EAAEC,YAAoB,EAAU;EAC/E,OAAOD,UAAU,GAAG,IAAI,GAAGC,YAAY;AAC3C;AAEA,IAAMC,oBAAoB,GAAG,SAAvBA,oBAAoB,CAAIC,CAA0B,EAAEC,CAA0B,EAAK;EACrF,IAAID,CAAC,CAACE,WAAW,GAAGD,CAAC,CAACC,WAAW,EAAE;IAC/B,OAAO,CAAC,CAAC;EACb,CAAC,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ory/memory-indexes.js.map b/dist/es/plugins/memory/memory-indexes.js.map deleted file mode 100644 index a6debcc0b8a..00000000000 --- a/dist/es/plugins/memory/memory-indexes.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"memory-indexes.js","names":["getIndexableStringMonad","getPrimaryFieldOfPrimaryKey","addIndexesToInternalsState","state","schema","primaryPath","primaryKey","useIndexes","indexes","map","row","Array","isArray","slice","push","forEach","indexAr","unshift","byIndex","getMemoryIndexName","index","docsWithIndex","getIndexableString","changesIndex","indexName","join"],"sources":["../../../../src/plugins/memory/memory-indexes.ts"],"sourcesContent":["import { getIndexableStringMonad } from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type { RxDocumentData, RxJsonSchema } from '../../types';\nimport type { MemoryStorageInternals } from './memory-types';\n\nexport function addIndexesToInternalsState(\n state: MemoryStorageInternals,\n schema: RxJsonSchema>\n) {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const useIndexes: string[][] = !schema.indexes ? [] : schema.indexes.map(row => Array.isArray(row) ? row.slice(0) : [row]) as any;\n\n // we need this as default index\n useIndexes.push([\n primaryPath\n ]);\n\n // we need this index for running cleanup()\n useIndexes.push([\n '_meta.lwt',\n primaryPath\n ]);\n\n\n useIndexes.forEach(indexAr => {\n /**\n * Running a query will only return non-deleted documents\n * so all indexes must have the the deleted field as first index field.\n */\n indexAr.unshift('_deleted');\n\n state.byIndex[getMemoryIndexName(indexAr)] = {\n index: indexAr,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, indexAr)\n };\n });\n\n // we need this index for the changes()\n const changesIndex = [\n '_meta.lwt',\n primaryPath\n ];\n const indexName = getMemoryIndexName(changesIndex);\n state.byIndex[indexName] = {\n index: changesIndex,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, changesIndex)\n };\n\n}\n\n\nexport function getMemoryIndexName(index: string[]): string {\n return index.join(',');\n}\n"],"mappings":"AAAA,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C,KAAe,EAAU;EACxD,OAAOA,KAAK,CAACK,IAAI,CAAC,GAAG,CAAC;AAC1B"} \ No newline at end of file diff --git a/dist/es/plugins/memory/memory-types.js.map b/dist/es/plugins/memory/memory-types.js.map deleted file mode 100644 index 8ffb477cb52..00000000000 --- a/dist/es/plugins/memory/memory-types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n DexiePreparedQuery,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxStorage\n} from '../../types';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n /**\n * We re-use the memory state when multiple instances\n * are created with the same params.\n * If refCount beomces 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n\nexport type MemoryPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/memory/rx-storage-instance-memory.js.map b/dist/es/plugins/memory/rx-storage-instance-memory.js.map deleted file mode 100644 index c6bbab3b032..00000000000 --- a/dist/es/plugins/memory/rx-storage-instance-memory.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-memory.js","names":["Subject","getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","getFromMapOrThrow","lastOfArray","now","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_VOID","RX_META_LWT_MINIMUM","RxStorageDexieStatics","boundGE","boundGT","boundLE","attachmentMapKey","compareDocsWithIndex","ensureNotRemoved","getMemoryCollectionKey","putWriteRowToState","removeDocFromState","addIndexesToInternalsState","getMemoryIndexName","RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","changes$","primaryPath","primaryKey","bulkWrite","documentWrites","context","ret","success","error","categorized","documents","errors","stateByIndex","Object","values","byIndex","bulkInsertDocs","forEach","writeRow","docId","document","undefined","bulkUpdateDocs","get","attachmentsMap","attachments","attachmentsAdd","attachment","set","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","eventBulk","events","length","lastState","checkpoint","id","lwt","_meta","next","Promise","resolve","findDocumentsById","docIds","withDeleted","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","concat","lowerBound","startKeys","lowerBoundString","inclusiveStart","upperBound","endKeys","upperBoundString","inclusiveEnd","indexName","docsWithIndex","indexOfLower","indexString","indexOfUpper","rows","done","currentDoc","doc","push","sortComparator","getSortComparator","sort","slice","count","result","mode","getChangedDocumentsSince","sinceLwt","sinceId","lastDoc","cleanup","minimumDeletedTime","maxDeletionTime","getAttachmentData","data","changeStream","asObservable","remove","removed","collectionStates","close","reject","Error","complete","refCount","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","instance"],"sources":["../../../../src/plugins/memory/rx-storage-instance-memory.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport {\n getFromMapOrThrow,\n lastOfArray,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM\n} from '../../util';\nimport { RxStorageDexieStatics } from '../dexie/dexie-statics';\nimport {\n boundGE,\n boundGT,\n boundLE\n} from './binary-search-bounds';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes';\nimport type {\n MemoryPreparedQuery,\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotRemoved(this);\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n this.internals.documents,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n undefined\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n this.internals.documents.get(docId as any)\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n /**\n * Handle attachments\n */\n const attachmentsMap = this.internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(categorized.eventBulk);\n }\n return Promise.resolve(ret);\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise> {\n const ret: RxDocumentDataById = {};\n docIds.forEach(docId => {\n const docInDb = this.internals.documents.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n });\n return Promise.resolve(ret);\n }\n\n query(preparedQuery: MemoryPreparedQuery): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n this.schema,\n preparedQuery\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n const index: string[] | undefined = ['_deleted'].concat(queryPlanFields);\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound,\n queryPlan.inclusiveEnd\n );\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGE(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n const indexOfUpper = boundLE(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n\n\n if (\n !currentDoc ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n\n if (!queryMatcher || queryMatcher(currentDoc.doc)) {\n rows.push(currentDoc.doc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort) ||\n indexOfLower >= docsWithIndex.length\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(this.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: MemoryPreparedQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n\n const index = ['_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n ['_meta.lwt', this.primaryPath as any],\n [\n sinceLwt,\n sinceId\n ],\n false\n );\n\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n // TODO use array.slice() so we do not have to iterate here\n const rows: RxDocumentData[] = [];\n while (rows.length < limit && indexOfLower < docsWithIndex.length) {\n const currentDoc = docsWithIndex[indexOfLower];\n rows.push(currentDoc.doc);\n indexOfLower++;\n }\n\n const lastDoc = lastOfArray(rows);\n return Promise.resolve({\n documents: rows,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n });\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ],\n false\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n ensureNotRemoved(this);\n const data = getFromMapOrThrow(\n this.internals.attachments,\n attachmentMapKey(documentId, attachmentId)\n );\n return Promise.resolve(data.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.changes$.asObservable();\n }\n\n async remove(): Promise {\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(this.databaseName, this.collectionName)\n );\n await this.close();\n }\n\n close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n\n this.internals.refCount = this.internals.refCount - 1;\n if (this.internals.refCount === 0) {\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(this.databaseName, this.collectionName)\n );\n }\n\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(params.databaseName, params.collectionName);\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":"AACA,SAEIA,OAAO,QACJ,MAAM;AACb,SACIC,iCAAiC,EACjCC,iCAAiC,QAC9B,oBAAoB;AAC3B,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SACIC,uBAAuB,EACvBC,yBAAyB,QACtB,yBAAyB;AAkBhC,SACIC,iBAAiB,EACjBC,WAAW,EACXC,GAAG,EACHC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,QAChB,YAAY;AACnB,SAASC,qBAAqB,QAAQ,wBAAwB;AAC9D,SACIC,OAAO,EACPC,OAAO,EACPC,OAAO,QACJ,wBAAwB;AAC/B,SACIC,gBAAgB,EAChBC,oBAAoB,EACpBC,gBAAgB,EAChBC,sBAAsB,EACtBC,kBAAkB,EAClBC,kBAAkB,QACf,iBAAiB;AACxB,SACIC,0BAA0B,EAC1BC,kBAAkB,QACf,kBAAkB;AASzB,WAAaC,uBAAuB;EAWhC,iCACoBC,OAA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CAAC;EAAA,OACDW,4BAA4B,GAA5B,sCAA6BC,aAAyD,EAAiB;IACnG,OAAOvI,oBAAoB;EAC/B,CAAC;EAAA;AAAA;AAGL,OAAO,SAASwI,2BAA2B,CACvCzH,OAAwB,EACxB0H,MAA0F,EAC1FpH,QAAiC,EACU;EAC3C,IAAMqH,aAAa,GAAGjI,sBAAsB,CAACgI,MAAM,CAACzH,YAAY,EAAEyH,MAAM,CAACxH,cAAc,CAAC;EAExF,IAAIE,SAAS,GAAGJ,OAAO,CAAC+G,gBAAgB,CAAChF,GAAG,CAAC4F,aAAa,CAAC;EAC3D,IAAI,CAACvH,SAAS,EAAE;IACZA,SAAS,GAAG;MACR0G,OAAO,EAAE,KAAK;MACdM,QAAQ,EAAE,CAAC;MACXlG,SAAS,EAAE,IAAI0G,GAAG,EAAE;MACpB3F,WAAW,EAAEyF,MAAM,CAACvH,MAAM,CAAC8B,WAAW,GAAG,IAAI2F,GAAG,EAAE,GAAG/F,SAAgB;MACrEN,OAAO,EAAE,CAAC,CAAC;MACX+F,uBAAuB,EAAE,IAAI/I,OAAO;IACxC,CAAC;IACDsB,0BAA0B,CAACO,SAAS,EAAEsH,MAAM,CAACvH,MAAM,CAAC;IACpDH,OAAO,CAAC+G,gBAAgB,CAAC3E,GAAG,CAACuF,aAAa,EAAEvH,SAAS,CAAC;EAC1D,CAAC,MAAM;IACHA,SAAS,CAACgH,QAAQ,GAAGhH,SAAS,CAACgH,QAAQ,GAAG,CAAC;EAC/C;EAEA,IAAMS,QAAQ,GAAG,IAAI9H,uBAAuB,CACxCC,OAAO,EACP0H,MAAM,CAACzH,YAAY,EACnByH,MAAM,CAACxH,cAAc,EACrBwH,MAAM,CAACvH,MAAM,EACbC,SAAS,EACTsH,MAAM,CAACrH,OAAO,EACdC,QAAQ,CACX;EACD,OAAO6C,OAAO,CAACC,OAAO,CAACyE,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/es/plugins/migration/data-migrator.js b/dist/es/plugins/migration/data-migrator.js index 52d08e2add4..35c23e9f543 100644 --- a/dist/es/plugins/migration/data-migrator.js +++ b/dist/es/plugins/migration/data-migrator.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * The DataMigrator handles the documents from collections with older schemas * and transforms/saves them into the newest collection @@ -9,7 +11,7 @@ */ import { Subject } from 'rxjs'; import deepEqual from 'fast-deep-equal'; -import { clone, toPromise, flatClone, getHeightOfRevision, createRevision, PROMISE_RESOLVE_VOID, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_NULL, getDefaultRxDocumentMeta, now } from '../../util'; +import { clone, toPromise, flatClone, getHeightOfRevision, createRevision, PROMISE_RESOLVE_VOID, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_NULL, getDefaultRxDocumentMeta, now } from '../../plugins/utils'; import { createRxSchema } from '../../rx-schema'; import { newRxError } from '../../rx-error'; import { runAsyncPluginHooks, runPluginHooks } from '../../hooks'; @@ -19,189 +21,6 @@ import { map } from 'rxjs/operators'; import { getWrappedStorageInstance } from '../../rx-storage-helper'; import { getPrimaryKeyOfInternalDocument, INTERNAL_CONTEXT_COLLECTION } from '../../rx-database-internal-store'; import { normalizeMangoQuery } from '../../rx-query-helper'; -/** - * transform documents data and save them to the new collection - * @return status-action with status and migrated document - */ -export var _migrateDocuments = function _migrateDocuments(oldCollection, documentsData) { - try { - // run hooks that might mutate documentsData - return Promise.resolve(Promise.all(documentsData.map(function (docData) { - return runAsyncPluginHooks('preMigrateDocument', { - docData: docData, - oldCollection: oldCollection - }); - }))).then(function () { - // run the migration strategies on each document - return Promise.resolve(Promise.all(documentsData.map(function (docData) { - return migrateDocumentData(oldCollection, docData); - }))).then(function (migratedDocuments) { - function _temp3() { - // run hooks - return Promise.resolve(Promise.all(actions.map(function (action) { - return runAsyncPluginHooks('postMigrateDocument', action); - }))).then(function () { - // remove the documents from the old collection storage instance - var bulkDeleteInputData = documentsData.map(function (docData) { - var writeDeleted = flatClone(docData); - writeDeleted._deleted = true; - writeDeleted._attachments = {}; - return { - previous: docData, - document: writeDeleted - }; - }); - var _temp = function () { - if (bulkDeleteInputData.length) { - return Promise.resolve(oldCollection.storageInstance.bulkWrite(bulkDeleteInputData, 'data-migrator-delete')).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(function () { - return actions; - }) : actions; - }); - } - var bulkWriteToStorageInput = []; - var actions = []; - documentsData.forEach(function (docData, idx) { - var migratedDocData = migratedDocuments[idx]; - var action = { - res: null, - type: '', - migrated: migratedDocData, - doc: docData, - oldCollection: oldCollection, - newestCollection: oldCollection.newestCollection - }; - actions.push(action); - - /** - * Determiniticly handle the revision - * so migrating the same data on multiple instances - * will result in the same output. - */ - if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) { - /** - * Data not changed by migration strategies, keep the same revision. - * This ensures that other replicated instances that did not migrate already - * will still have the same document. - */ - migratedDocData._rev = docData._rev; - } else if (migratedDocData !== null) { - /** - * data changed, increase revision height - * so replicating instances use our new document data - */ - var newHeight = getHeightOfRevision(docData._rev) + 1; - var newRevision = newHeight + '-' + createRevision(oldCollection.newestCollection.database.hashFunction, migratedDocData); - migratedDocData._rev = newRevision; - } - if (migratedDocData) { - /** - * save to newest collection - * notice that this data also contains the attachments data - */ - var attachmentsBefore = migratedDocData._attachments; - var saveData = migratedDocData; - saveData._attachments = attachmentsBefore; - saveData._meta.lwt = now(); - bulkWriteToStorageInput.push(saveData); - action.res = saveData; - action.type = 'success'; - } else { - /** - * Migration strategy returned null - * which means we should not migrate this document, - * just drop it. - */ - action.type = 'deleted'; - } - }); - - /** - * Write the documents to the newest collection. - * We need to add as revision - * because we provide the _rev by our own - * to have deterministic revisions in case the migration - * runs on multiple nodes which must lead to the equal storage state. - */ - var _temp2 = function () { - if (bulkWriteToStorageInput.length) { - /** - * To ensure that we really keep that revision, we - * hackly insert this document via the RxStorageInstance.originalStorageInstance - * so that getWrappedStorageInstance() does not overwrite its own revision. - */ - var originalStorageInstance = oldCollection.newestCollection.storageInstance.originalStorageInstance; - return Promise.resolve(originalStorageInstance.bulkWrite(bulkWriteToStorageInput.map(function (document) { - return { - document: document - }; - }), 'data-migrator-import')).then(function () {}); - } - }(); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * deletes this.storageInstance and removes it from the database.collectionsCollection - */ -/** - * get an array with OldCollection-instances from all existing old storage-instances - */ -export var _getOldCollections = function _getOldCollections(dataMigrator) { - try { - return Promise.resolve(getOldCollectionDocs(dataMigrator)).then(function (oldColDocs) { - return Promise.all(oldColDocs.map(function (colDoc) { - if (!colDoc) { - return null; - } - return createOldCollection(colDoc.data.schema.version, colDoc.data.schema, dataMigrator); - }).filter(function (colDoc) { - return colDoc !== null; - })); - }); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * returns true if a migration is needed - */ -export var createOldCollection = function createOldCollection(version, schemaObj, dataMigrator) { - try { - var database = dataMigrator.newestCollection.database; - var storageInstanceCreationParams = { - databaseInstanceToken: database.token, - databaseName: database.name, - collectionName: dataMigrator.newestCollection.name, - schema: schemaObj, - options: dataMigrator.newestCollection.instanceCreationOptions, - multiInstance: database.multiInstance - }; - runPluginHooks('preCreateRxStorageInstance', storageInstanceCreationParams); - return Promise.resolve(database.storage.createStorageInstance(storageInstanceCreationParams)).then(function (storageInstance) { - var ret = { - version: version, - dataMigrator: dataMigrator, - newestCollection: dataMigrator.newestCollection, - database: database, - schema: createRxSchema(schemaObj, false), - storageInstance: storageInstance - }; - ret.storageInstance = getWrappedStorageInstance(ret.database, storageInstance, schemaObj); - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; export var DataMigrator = /*#__PURE__*/function () { function DataMigrator(newestCollection, migrationStrategies) { this._migrated = false; @@ -256,18 +75,30 @@ export var DataMigrator = /*#__PURE__*/function () { return _getOldCollections(_this).then(function (ret) { _this.nonMigratedOldCollections = ret; _this.allOldCollections = _this.nonMigratedOldCollections.slice(0); - var getAllDocuments = function getAllDocuments(storageInstance, schema) { - try { - var storage = _this.database.storage; - var getAllQueryPrepared = storage.statics.prepareQuery(storageInstance.schema, normalizeMangoQuery(schema, {})); - return Promise.resolve(storageInstance.query(getAllQueryPrepared)).then(function (queryResult) { - var allDocs = queryResult.documents; - return allDocs; - }); - } catch (e) { - return Promise.reject(e); - } - }; + var getAllDocuments = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(storageInstance, schema) { + var storage, getAllQueryPrepared, queryResult, allDocs; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + storage = _this.database.storage; + getAllQueryPrepared = storage.statics.prepareQuery(storageInstance.schema, normalizeMangoQuery(schema, {})); + _context.next = 4; + return storageInstance.query(getAllQueryPrepared); + case 4: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function getAllDocuments(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); var countAll = Promise.all(_this.nonMigratedOldCollections.map(function (oldCol) { return getAllDocuments(oldCol.storageInstance, oldCol.schema.jsonSchema).then(function (allDocs) { return allDocs.length; @@ -364,6 +195,47 @@ export var DataMigrator = /*#__PURE__*/function () { }; return DataMigrator; }(); +export function createOldCollection(_x3, _x4, _x5) { + return _createOldCollection.apply(this, arguments); +} +function _createOldCollection() { + _createOldCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(version, schemaObj, dataMigrator) { + var database, storageInstanceCreationParams, storageInstance, ret; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + database = dataMigrator.newestCollection.database; + storageInstanceCreationParams = { + databaseInstanceToken: database.token, + databaseName: database.name, + collectionName: dataMigrator.newestCollection.name, + schema: schemaObj, + options: dataMigrator.newestCollection.instanceCreationOptions, + multiInstance: database.multiInstance + }; + runPluginHooks('preCreateRxStorageInstance', storageInstanceCreationParams); + _context2.next = 5; + return database.storage.createStorageInstance(storageInstanceCreationParams); + case 5: + storageInstance = _context2.sent; + ret = { + version: version, + dataMigrator: dataMigrator, + newestCollection: dataMigrator.newestCollection, + database: database, + schema: createRxSchema(schemaObj, false), + storageInstance: storageInstance + }; + ret.storageInstance = getWrappedStorageInstance(ret.database, storageInstance, schemaObj); + return _context2.abrupt("return", ret); + case 9: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _createOldCollection.apply(this, arguments); +} export function getOldCollectionDocs(dataMigrator) { var collectionDocKeys = getPreviousVersions(dataMigrator.currentSchema.jsonSchema).map(function (version) { return dataMigrator.name + '-' + version; @@ -374,6 +246,43 @@ export function getOldCollectionDocs(dataMigrator) { return Object.values(docsObj); }); } + +/** + * get an array with OldCollection-instances from all existing old storage-instances + */ +export function _getOldCollections(_x6) { + return _getOldCollections2.apply(this, arguments); +} + +/** + * returns true if a migration is needed + */ +function _getOldCollections2() { + _getOldCollections2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(dataMigrator) { + var oldColDocs; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getOldCollectionDocs(dataMigrator); + case 2: + oldColDocs = _context3.sent; + return _context3.abrupt("return", Promise.all(oldColDocs.map(function (colDoc) { + if (!colDoc) { + return null; + } + return createOldCollection(colDoc.data.schema.version, colDoc.data.schema, dataMigrator); + }).filter(function (colDoc) { + return colDoc !== null; + }))); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _getOldCollections2.apply(this, arguments); +} export function mustMigrate(dataMigrator) { if (dataMigrator.currentSchema.version === 0) { return PROMISE_RESOLVE_FALSE; @@ -396,12 +305,12 @@ export function runStrategyIfNotNull(oldCollection, version, docOrNull) { } } export function getBatchOfOldCollection(oldCollection, batchSize) { - var _ref; + var _ref2; var storage = oldCollection.database.storage; var storageInstance = oldCollection.storageInstance; var preparedQuery = storage.statics.prepareQuery(storageInstance.schema, { selector: {}, - sort: [(_ref = {}, _ref[oldCollection.schema.primaryPath] = 'asc', _ref)], + sort: [(_ref2 = {}, _ref2[oldCollection.schema.primaryPath] = 'asc', _ref2)], limit: batchSize, skip: 0 }); @@ -470,6 +379,150 @@ export function isDocumentDataWithoutRevisionEqual(doc1, doc2) { }); return deepEqual(doc1NoRev, doc2NoRev); } + +/** + * transform documents data and save them to the new collection + * @return status-action with status and migrated document + */ +export function _migrateDocuments(_x7, _x8) { + return _migrateDocuments2.apply(this, arguments); +} + +/** + * deletes this.storageInstance and removes it from the database.collectionsCollection + */ +function _migrateDocuments2() { + _migrateDocuments2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(oldCollection, documentsData) { + var migratedDocuments, bulkWriteToStorageInput, actions, originalStorageInstance, bulkDeleteInputData; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return Promise.all(documentsData.map(function (docData) { + return runAsyncPluginHooks('preMigrateDocument', { + docData: docData, + oldCollection: oldCollection + }); + })); + case 2: + _context4.next = 4; + return Promise.all(documentsData.map(function (docData) { + return migrateDocumentData(oldCollection, docData); + })); + case 4: + migratedDocuments = _context4.sent; + bulkWriteToStorageInput = []; + actions = []; + documentsData.forEach(function (docData, idx) { + var migratedDocData = migratedDocuments[idx]; + var action = { + res: null, + type: '', + migrated: migratedDocData, + doc: docData, + oldCollection: oldCollection, + newestCollection: oldCollection.newestCollection + }; + actions.push(action); + + /** + * Determiniticly handle the revision + * so migrating the same data on multiple instances + * will result in the same output. + */ + if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) { + /** + * Data not changed by migration strategies, keep the same revision. + * This ensures that other replicated instances that did not migrate already + * will still have the same document. + */ + migratedDocData._rev = docData._rev; + } else if (migratedDocData !== null) { + /** + * data changed, increase revision height + * so replicating instances use our new document data + */ + var newHeight = getHeightOfRevision(docData._rev) + 1; + var newRevision = newHeight + '-' + createRevision(oldCollection.newestCollection.database.token); + migratedDocData._rev = newRevision; + } + if (migratedDocData) { + /** + * save to newest collection + * notice that this data also contains the attachments data + */ + var attachmentsBefore = migratedDocData._attachments; + var saveData = migratedDocData; + saveData._attachments = attachmentsBefore; + saveData._meta.lwt = now(); + bulkWriteToStorageInput.push(saveData); + action.res = saveData; + action.type = 'success'; + } else { + /** + * Migration strategy returned null + * which means we should not migrate this document, + * just drop it. + */ + action.type = 'deleted'; + } + }); + + /** + * Write the documents to the newest collection. + * We need to add as revision + * because we provide the _rev by our own + * to have deterministic revisions in case the migration + * runs on multiple nodes which must lead to the equal storage state. + */ + if (!bulkWriteToStorageInput.length) { + _context4.next = 12; + break; + } + /** + * To ensure that we really keep that revision, we + * hackly insert this document via the RxStorageInstance.originalStorageInstance + * so that getWrappedStorageInstance() does not overwrite its own revision. + */ + originalStorageInstance = oldCollection.newestCollection.storageInstance.originalStorageInstance; + _context4.next = 12; + return originalStorageInstance.bulkWrite(bulkWriteToStorageInput.map(function (document) { + return { + document: document + }; + }), 'data-migrator-import'); + case 12: + _context4.next = 14; + return Promise.all(actions.map(function (action) { + return runAsyncPluginHooks('postMigrateDocument', action); + })); + case 14: + // remove the documents from the old collection storage instance + bulkDeleteInputData = documentsData.map(function (docData) { + var writeDeleted = flatClone(docData); + writeDeleted._deleted = true; + writeDeleted._attachments = {}; + return { + previous: docData, + document: writeDeleted + }; + }); + if (!bulkDeleteInputData.length) { + _context4.next = 18; + break; + } + _context4.next = 18; + return oldCollection.storageInstance.bulkWrite(bulkDeleteInputData, 'data-migrator-delete'); + case 18: + return _context4.abrupt("return", actions); + case 19: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _migrateDocuments2.apply(this, arguments); +} export function deleteOldCollection(oldCollection) { return oldCollection.storageInstance.remove().then(function () { return oldCollection.database.removeCollectionDoc(oldCollection.dataMigrator.name, oldCollection.schema); diff --git a/dist/es/plugins/migration/data-migrator.js.map b/dist/es/plugins/migration/data-migrator.js.map index 47ef9f109f7..f4cb644ce29 100644 --- a/dist/es/plugins/migration/data-migrator.js.map +++ b/dist/es/plugins/migration/data-migrator.js.map @@ -1 +1 @@ -{"version":3,"file":"data-migrator.js","names":["Subject","deepEqual","clone","toPromise","flatClone","getHeightOfRevision","createRevision","PROMISE_RESOLVE_VOID","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_NULL","getDefaultRxDocumentMeta","now","createRxSchema","newRxError","runAsyncPluginHooks","runPluginHooks","getPreviousVersions","getMigrationStateByDatabase","map","getWrappedStorageInstance","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","normalizeMangoQuery","_migrateDocuments","oldCollection","documentsData","Promise","all","docData","migrateDocumentData","migratedDocuments","actions","action","bulkDeleteInputData","writeDeleted","_deleted","_attachments","previous","document","length","storageInstance","bulkWrite","bulkWriteToStorageInput","forEach","idx","migratedDocData","res","type","migrated","doc","newestCollection","push","isDocumentDataWithoutRevisionEqual","_rev","newHeight","newRevision","database","hashFunction","attachmentsBefore","saveData","_meta","lwt","originalStorageInstance","_getOldCollections","dataMigrator","getOldCollectionDocs","oldColDocs","colDoc","createOldCollection","data","schema","version","filter","schemaObj","storageInstanceCreationParams","databaseInstanceToken","token","databaseName","name","collectionName","options","instanceCreationOptions","multiInstance","storage","createStorageInstance","ret","DataMigrator","migrationStrategies","_migrated","nonMigratedOldCollections","allOldCollections","currentSchema","migrate","batchSize","state","done","total","handled","success","deleted","percent","stateSubject","allSubject","allList","getValue","slice","asObservable","next","then","getAllDocuments","getAllQueryPrepared","statics","prepareQuery","query","queryResult","allDocs","documents","countAll","oldCol","jsonSchema","totalCount","reduce","cur","prev","collection","currentCol","shift","currentPromise","migrationState$","migrateOldCollection","sub","subscribe","subState","Math","round","error","e","unsubscribe","c","close","complete","pipe","withCollection","migratePromise","_migratePromise","mustMigrate","must","rej","state$","err","collectionDocKeys","internalStore","findDocumentsById","key","docsObj","Object","values","runStrategyIfNotNull","docOrNull","retPromise","getBatchOfOldCollection","preparedQuery","selector","sort","primaryPath","limit","skip","result","mutateableDocData","nextVersion","resolve","doc1","doc2","doc1NoRev","assign","undefined","doc2NoRev","deleteOldCollection","remove","removeCollectionDoc","_migrate","observer","allBatchesDone","handleOneBatch","batch"],"sources":["../../../../src/plugins/migration/data-migrator.ts"],"sourcesContent":["/**\n * The DataMigrator handles the documents from collections with older schemas\n * and transforms/saves them into the newest collection\n */\n/**\n * TODO this should be completely rewritten because:\n * - This could have been done in much less code which would be easier to uderstand\n *\n */\nimport {\n Subject,\n Observable\n} from 'rxjs';\nimport deepEqual from 'fast-deep-equal';\nimport {\n clone,\n toPromise,\n flatClone,\n getHeightOfRevision,\n createRevision,\n PROMISE_RESOLVE_VOID,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_NULL,\n getDefaultRxDocumentMeta,\n now\n} from '../../util';\nimport {\n createRxSchema\n} from '../../rx-schema';\nimport {\n newRxError\n} from '../../rx-error';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from '../../hooks';\nimport type {\n RxCollection,\n RxDatabase,\n MigrationState,\n NumberFunctionMap,\n OldRxCollection,\n WithAttachmentsData,\n RxJsonSchema,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n InternalStoreCollectionDocType,\n RxStorageInstance\n} from '../../types';\nimport {\n RxSchema,\n getPreviousVersions\n} from '../../rx-schema';\nimport {\n getMigrationStateByDatabase,\n MigrationStateWithCollection\n} from './migration-state';\nimport { map } from 'rxjs/operators';\nimport {\n getWrappedStorageInstance\n} from '../../rx-storage-helper';\nimport {\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION\n} from '../../rx-database-internal-store';\nimport { normalizeMangoQuery } from '../../rx-query-helper';\n\nexport class DataMigrator {\n\n constructor(\n public newestCollection: RxCollection,\n public migrationStrategies: NumberFunctionMap\n ) {\n this.currentSchema = newestCollection.schema;\n this.database = newestCollection.database;\n this.name = newestCollection.name;\n }\n\n public currentSchema: RxSchema;\n public database: RxDatabase;\n public name: string;\n\n\n private _migrated: boolean = false;\n private _migratePromise?: Promise;\n private nonMigratedOldCollections: OldRxCollection[] = [];\n private allOldCollections: OldRxCollection[] = [];\n migrate(batchSize: number = 10): Observable {\n if (this._migrated) {\n throw newRxError('DM1');\n }\n this._migrated = true;\n\n const state = {\n done: false, // true if finished\n total: 0, // will be the doc-count\n handled: 0, // amount of handled docs\n success: 0, // handled docs which succeeded\n deleted: 0, // handled docs which got deleted\n percent: 0 // percentage\n };\n\n const stateSubject: Subject = new Subject();\n\n /**\n * Add to output of RxDatabase.migrationStates\n */\n const allSubject = getMigrationStateByDatabase(this.newestCollection.database);\n const allList = allSubject.getValue().slice(0);\n allList.push(stateSubject.asObservable());\n allSubject.next(allList);\n\n /**\n * TODO this is a side-effect which might throw\n * We did this because it is not possible to create new Observer(async(...))\n * @link https://github.com/ReactiveX/rxjs/issues/4074\n * In the future the whole migration plugin should be rewritten without rxjs\n * so we do not have this problem.\n */\n (() => {\n return _getOldCollections(this)\n .then(ret => {\n this.nonMigratedOldCollections = ret;\n this.allOldCollections = this.nonMigratedOldCollections.slice(0);\n\n const getAllDocuments = async (\n storageInstance: RxStorageInstance,\n schema: RxJsonSchema\n ): Promise[]> => {\n const storage = this.database.storage;\n const getAllQueryPrepared = storage.statics.prepareQuery(\n storageInstance.schema,\n normalizeMangoQuery(\n schema,\n {}\n )\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n };\n\n const countAll: Promise = Promise.all(\n this.nonMigratedOldCollections\n .map(oldCol => getAllDocuments(\n oldCol.storageInstance,\n oldCol.schema.jsonSchema\n ).then(allDocs => allDocs.length))\n );\n return countAll;\n })\n .then(countAll => {\n const totalCount: number = countAll\n .reduce((cur, prev) => prev = cur + prev, 0);\n state.total = totalCount;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n let currentCol = this.nonMigratedOldCollections.shift();\n let currentPromise = PROMISE_RESOLVE_VOID;\n while (currentCol) {\n const migrationState$ = migrateOldCollection(\n currentCol,\n batchSize\n );\n currentPromise = currentPromise.then(() => {\n return new Promise(res => {\n const sub = migrationState$.subscribe({\n next: (subState: any) => {\n state.handled++;\n (state as any)[subState.type] = (state as any)[subState.type] + 1;\n state.percent = Math.round(state.handled / state.total * 100);\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n },\n error: (e: any) => {\n sub.unsubscribe();\n // TODO we should not have to catch here.\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n stateSubject.error(e);\n },\n complete: () => {\n if (currentCol) {\n // TODO we should not have to catch here.\n currentCol.storageInstance.close().catch(() => { });\n }\n sub.unsubscribe();\n res();\n }\n });\n });\n });\n currentCol = this.nonMigratedOldCollections.shift();\n }\n return currentPromise;\n })\n .then(() => {\n state.done = true;\n state.percent = 100;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n stateSubject.complete();\n });\n })();\n\n\n return stateSubject.pipe(\n map(withCollection => withCollection.state)\n );\n }\n\n migratePromise(batchSize: number): Promise {\n if (!this._migratePromise) {\n this._migratePromise = mustMigrate(this)\n .then(must => {\n if (!must) {\n return PROMISE_RESOLVE_FALSE;\n } else {\n return new Promise((res, rej) => {\n const state$ = this.migrate(batchSize);\n (state$ as any).subscribe(null, rej, res);\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n })\n .catch(err => {\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n throw err;\n });\n }\n });\n }\n return this._migratePromise;\n }\n}\n\nexport async function createOldCollection(\n version: number,\n schemaObj: RxJsonSchema,\n dataMigrator: DataMigrator\n): Promise {\n const database = dataMigrator.newestCollection.database;\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: dataMigrator.newestCollection.name,\n schema: schemaObj,\n options: dataMigrator.newestCollection.instanceCreationOptions,\n multiInstance: database.multiInstance\n };\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n const storageInstance = await database.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n const ret: OldRxCollection = {\n version,\n dataMigrator,\n newestCollection: dataMigrator.newestCollection,\n database,\n schema: createRxSchema(schemaObj, false),\n storageInstance\n };\n\n ret.storageInstance = getWrappedStorageInstance(\n ret.database,\n storageInstance,\n schemaObj\n );\n\n return ret;\n}\n\n\nexport function getOldCollectionDocs(\n dataMigrator: DataMigrator\n): Promise[]> {\n\n const collectionDocKeys = getPreviousVersions(dataMigrator.currentSchema.jsonSchema)\n .map(version => dataMigrator.name + '-' + version);\n\n return dataMigrator.database.internalStore.findDocumentsById(\n collectionDocKeys.map(key => getPrimaryKeyOfInternalDocument(\n key,\n INTERNAL_CONTEXT_COLLECTION\n )),\n false\n ).then(docsObj => Object.values(docsObj));\n}\n\n/**\n * get an array with OldCollection-instances from all existing old storage-instances\n */\nexport async function _getOldCollections(\n dataMigrator: DataMigrator\n): Promise {\n const oldColDocs = await getOldCollectionDocs(dataMigrator);\n\n return Promise.all(\n oldColDocs\n .map(colDoc => {\n if (!colDoc) {\n return null as any;\n }\n return createOldCollection(\n colDoc.data.schema.version,\n colDoc.data.schema,\n dataMigrator\n );\n })\n .filter(colDoc => colDoc !== null)\n );\n}\n\n\n/**\n * returns true if a migration is needed\n */\nexport function mustMigrate(dataMigrator: DataMigrator): Promise {\n if (dataMigrator.currentSchema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return getOldCollectionDocs(dataMigrator)\n .then(oldColDocs => {\n if (oldColDocs.length === 0) {\n return false;\n } else {\n return true;\n }\n });\n}\n\nexport function runStrategyIfNotNull(\n oldCollection: OldRxCollection,\n version: number,\n docOrNull: any | null\n): Promise {\n if (docOrNull === null) {\n return PROMISE_RESOLVE_NULL;\n } else {\n const ret = oldCollection.dataMigrator.migrationStrategies[version](docOrNull, oldCollection);\n const retPromise = toPromise(ret);\n return retPromise;\n }\n}\n\nexport function getBatchOfOldCollection(\n oldCollection: OldRxCollection,\n batchSize: number\n): Promise {\n const storage = oldCollection.database.storage;\n const storageInstance = oldCollection.storageInstance;\n const preparedQuery = storage.statics.prepareQuery(\n storageInstance.schema,\n {\n selector: {},\n sort: [{ [oldCollection.schema.primaryPath]: 'asc' } as any],\n limit: batchSize,\n skip: 0\n }\n );\n\n return storageInstance\n .query(preparedQuery)\n .then(result => result.documents\n .map(doc => {\n doc = flatClone(doc);\n return doc;\n })\n );\n}\n\n/**\n * runs the doc-data through all following migrationStrategies\n * so it will match the newest schema.\n * @throws Error if final doc does not match final schema or migrationStrategy crashes\n * @return final object or null if migrationStrategy deleted it\n */\nexport function migrateDocumentData(\n oldCollection: OldRxCollection,\n docData: any\n): Promise {\n /**\n * We cannot deep-clone Blob or Buffer\n * so we just flat clone it here\n * and attach it to the deep cloned document data.\n */\n const attachmentsBefore = flatClone(docData._attachments);\n const mutateableDocData = clone(docData);\n mutateableDocData._attachments = attachmentsBefore;\n\n let nextVersion = oldCollection.version + 1;\n\n // run the document through migrationStrategies\n let currentPromise = Promise.resolve(mutateableDocData);\n while (nextVersion <= oldCollection.newestCollection.schema.version) {\n const version = nextVersion;\n currentPromise = currentPromise.then(docOrNull => runStrategyIfNotNull(\n oldCollection,\n version,\n docOrNull\n ));\n nextVersion++;\n }\n\n return currentPromise.then(doc => {\n if (doc === null) {\n return PROMISE_RESOLVE_NULL;\n }\n\n /**\n * Add _meta field if missing.\n * We need this to migration documents from pre-12.0.0 state\n * to version 12.0.0. Therefore we need to add the _meta field if it is missing.\n * TODO remove this in the major version 13.0.0\n */\n if (!doc._meta) {\n doc._meta = getDefaultRxDocumentMeta();\n }\n return doc;\n });\n}\n\n\nexport function isDocumentDataWithoutRevisionEqual(doc1: T, doc2: T): boolean {\n const doc1NoRev = Object.assign({}, doc1, {\n _attachments: undefined,\n _rev: undefined\n });\n const doc2NoRev = Object.assign({}, doc2, {\n _attachments: undefined,\n _rev: undefined\n });\n return deepEqual(doc1NoRev, doc2NoRev);\n}\n\n/**\n * transform documents data and save them to the new collection\n * @return status-action with status and migrated document\n */\nexport async function _migrateDocuments(\n oldCollection: OldRxCollection,\n documentsData: any[]\n): Promise<{ type: string; doc: any; }[]> {\n\n // run hooks that might mutate documentsData\n await Promise.all(\n documentsData.map(docData => runAsyncPluginHooks(\n 'preMigrateDocument',\n {\n docData,\n oldCollection\n }\n ))\n );\n // run the migration strategies on each document\n const migratedDocuments: (any | null)[] = await Promise.all(\n documentsData.map(docData => migrateDocumentData(oldCollection, docData))\n );\n\n\n const bulkWriteToStorageInput: RxDocumentData[] = [];\n const actions: any[] = [];\n\n documentsData.forEach((docData, idx) => {\n const migratedDocData: any | null = migratedDocuments[idx];\n const action = {\n res: null as any,\n type: '',\n migrated: migratedDocData,\n doc: docData,\n oldCollection,\n newestCollection: oldCollection.newestCollection\n };\n actions.push(action);\n\n /**\n * Determiniticly handle the revision\n * so migrating the same data on multiple instances\n * will result in the same output.\n */\n if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) {\n /**\n * Data not changed by migration strategies, keep the same revision.\n * This ensures that other replicated instances that did not migrate already\n * will still have the same document.\n */\n migratedDocData._rev = docData._rev;\n } else if (migratedDocData !== null) {\n /**\n * data changed, increase revision height\n * so replicating instances use our new document data\n */\n const newHeight = getHeightOfRevision(docData._rev) + 1;\n const newRevision = newHeight + '-' + createRevision(\n oldCollection.newestCollection.database.hashFunction,\n migratedDocData\n );\n migratedDocData._rev = newRevision;\n }\n\n\n if (migratedDocData) {\n /**\n * save to newest collection\n * notice that this data also contains the attachments data\n */\n const attachmentsBefore = migratedDocData._attachments;\n const saveData: WithAttachmentsData = migratedDocData;\n saveData._attachments = attachmentsBefore;\n saveData._meta.lwt = now();\n bulkWriteToStorageInput.push(saveData);\n action.res = saveData;\n action.type = 'success';\n } else {\n /**\n * Migration strategy returned null\n * which means we should not migrate this document,\n * just drop it.\n */\n action.type = 'deleted';\n }\n });\n\n /**\n * Write the documents to the newest collection.\n * We need to add as revision\n * because we provide the _rev by our own\n * to have deterministic revisions in case the migration\n * runs on multiple nodes which must lead to the equal storage state.\n */\n if (bulkWriteToStorageInput.length) {\n /**\n * To ensure that we really keep that revision, we\n * hackly insert this document via the RxStorageInstance.originalStorageInstance\n * so that getWrappedStorageInstance() does not overwrite its own revision.\n */\n const originalStorageInstance: RxStorageInstance = (oldCollection.newestCollection.storageInstance as any).originalStorageInstance;\n await originalStorageInstance.bulkWrite(\n bulkWriteToStorageInput.map(document => ({ document })),\n 'data-migrator-import'\n );\n }\n\n // run hooks\n await Promise.all(\n actions.map(action => runAsyncPluginHooks(\n 'postMigrateDocument',\n action\n ))\n );\n\n // remove the documents from the old collection storage instance\n const bulkDeleteInputData = documentsData.map(docData => {\n const writeDeleted = flatClone(docData);\n writeDeleted._deleted = true;\n writeDeleted._attachments = {};\n return {\n previous: docData,\n document: writeDeleted\n };\n });\n\n if (bulkDeleteInputData.length) {\n await oldCollection.storageInstance.bulkWrite(\n bulkDeleteInputData,\n 'data-migrator-delete'\n );\n }\n\n return actions;\n}\n\n\n/**\n * deletes this.storageInstance and removes it from the database.collectionsCollection\n */\nexport function deleteOldCollection(\n oldCollection: OldRxCollection\n): Promise {\n return oldCollection.storageInstance.remove()\n .then(\n () => oldCollection.database.removeCollectionDoc(\n oldCollection.dataMigrator.name,\n oldCollection.schema\n )\n );\n}\n\n/**\n * runs the migration on all documents and deletes the storage instance afterwards\n */\nexport function migrateOldCollection(\n oldCollection: OldRxCollection,\n batchSize = 10\n): Observable {\n if (oldCollection._migrate) {\n // already running\n throw newRxError('DM3');\n }\n oldCollection._migrate = true;\n\n const observer = new Subject();\n\n /**\n * TODO this is a side-effect which might throw\n * @see DataMigrator.migrate()\n */\n (() => {\n let error: any;\n const allBatchesDone = () => {\n // remove this oldCollection\n return deleteOldCollection(oldCollection)\n .then(() => observer.complete());\n };\n const handleOneBatch = () => {\n return getBatchOfOldCollection(oldCollection, batchSize)\n .then(batch => {\n if (batch.length === 0) {\n allBatchesDone();\n return false;\n } else {\n return _migrateDocuments(oldCollection, batch)\n .then((actions: any[]) => actions.forEach(action => observer.next(action)))\n .catch(e => error = e)\n .then(() => true);\n }\n })\n .then(next => {\n if (!next) {\n return;\n }\n if (error) {\n observer.error(error);\n } else {\n handleOneBatch();\n }\n });\n };\n handleOneBatch();\n })();\n\n return observer.asObservable();\n}\n\nexport function migratePromise(\n oldCollection: OldRxCollection,\n batchSize?: number\n): Promise {\n if (!oldCollection._migratePromise) {\n oldCollection._migratePromise = new Promise((res, rej) => {\n const state$ = migrateOldCollection(oldCollection, batchSize);\n (state$ as any).subscribe(null, rej, res);\n });\n }\n return oldCollection._migratePromise;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SACIA,OAAO,QAEJ,MAAM;AACb,OAAOC,SAAS,MAAM,iBAAiB;AACvC,SACIC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,mBAAmB,EACnBC,cAAc,EACdC,oBAAoB,EACpBC,qBAAqB,EACrBC,oBAAoB,EACpBC,wBAAwB,EACxBC,GAAG,QACA,YAAY;AACnB,SACIC,cAAc,QACX,iBAAiB;AACxB,SACIC,UAAU,QACP,gBAAgB;AACvB,SACIC,mBAAmB,EACnBC,cAAc,QACX,aAAa;AAcpB,SAEIC,mBAAmB,QAChB,iBAAiB;AACxB,SACIC,2BAA2B,QAExB,mBAAmB;AAC1B,SAASC,GAAG,QAAQ,gBAAgB;AACpC,SACIC,yBAAyB,QACtB,yBAAyB;AAChC,SACIC,+BAA+B,EAC/BC,2BAA2B,QACxB,kCAAkC;AACzC,SAASC,mBAAmB,QAAQ,uBAAuB;AAyX3D;AACA;AACA;AACA;AACA,WAAsBC,iBAAiB,YAAjBA,iBAAiB,CACnCC,aAA8B,EAC9BC,aAAoB;EAAA,I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,CAAC,CAAC,CACDA,IAAI,CAAC,UAAAD,IAAI,EAAI;QACV,IAAI,CAACA,IAAI,EAAE;UACP;QACJ;QACA,IAAI4B,KAAK,EAAE;UACP8C,QAAQ,CAAC9C,KAAK,CAACA,KAAK,CAAC;QACzB,CAAC,MAAM;UACHgD,cAAc,EAAE;QACpB;MACJ,CAAC,CAAC;IACV,CAAC;IACDA,cAAc,EAAE;EACpB,CAAC,GAAG;EAEJ,OAAOF,QAAQ,CAAC3E,YAAY,EAAE;AAClC;AAEA,OAAO,SAASqC,cAAc,CAC1BvH,aAA8B,EAC9BqE,SAAkB,EACN;EACZ,IAAI,CAACrE,aAAa,CAACwH,eAAe,EAAE;IAChCxH,aAAa,CAACwH,eAAe,GAAG,IAAItH,OAAO,CAAC,UAACoB,GAAG,EAAEqG,GAAG,EAAK;MACtD,IAAMC,MAAM,GAAGnB,oBAAoB,CAACzG,aAAa,EAAEqE,SAAS,CAAC;MAC5DuD,MAAM,CAASjB,SAAS,CAAC,IAAI,EAAEgB,GAAG,EAAErG,GAAG,CAAC;IAC7C,CAAC,CAAC;EACN;EACA,OAAOtB,aAAa,CAACwH,eAAe;AACxC"} \ No newline at end of file +{"version":3,"file":"data-migrator.js","names":["Subject","deepEqual","clone","toPromise","flatClone","getHeightOfRevision","createRevision","PROMISE_RESOLVE_VOID","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_NULL","getDefaultRxDocumentMeta","now","createRxSchema","newRxError","runAsyncPluginHooks","runPluginHooks","getPreviousVersions","getMigrationStateByDatabase","map","getWrappedStorageInstance","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","normalizeMangoQuery","DataMigrator","newestCollection","migrationStrategies","_migrated","nonMigratedOldCollections","allOldCollections","currentSchema","schema","database","name","migrate","batchSize","state","done","total","handled","success","deleted","percent","stateSubject","allSubject","allList","getValue","slice","push","asObservable","next","_getOldCollections","then","ret","getAllDocuments","storageInstance","storage","getAllQueryPrepared","statics","prepareQuery","query","queryResult","allDocs","documents","countAll","Promise","all","oldCol","jsonSchema","length","totalCount","reduce","cur","prev","collection","currentCol","shift","currentPromise","migrationState$","migrateOldCollection","res","sub","subscribe","subState","type","Math","round","error","e","unsubscribe","forEach","c","close","complete","pipe","withCollection","migratePromise","_migratePromise","mustMigrate","must","rej","state$","err","createOldCollection","version","schemaObj","dataMigrator","storageInstanceCreationParams","databaseInstanceToken","token","databaseName","collectionName","options","instanceCreationOptions","multiInstance","createStorageInstance","getOldCollectionDocs","collectionDocKeys","internalStore","findDocumentsById","key","docsObj","Object","values","oldColDocs","colDoc","data","filter","runStrategyIfNotNull","oldCollection","docOrNull","retPromise","getBatchOfOldCollection","preparedQuery","selector","sort","primaryPath","limit","skip","result","doc","migrateDocumentData","docData","attachmentsBefore","_attachments","mutateableDocData","nextVersion","resolve","_meta","isDocumentDataWithoutRevisionEqual","doc1","doc2","doc1NoRev","assign","undefined","_rev","doc2NoRev","_migrateDocuments","documentsData","migratedDocuments","bulkWriteToStorageInput","actions","idx","migratedDocData","action","migrated","newHeight","newRevision","saveData","lwt","originalStorageInstance","bulkWrite","document","bulkDeleteInputData","writeDeleted","_deleted","previous","deleteOldCollection","remove","removeCollectionDoc","_migrate","observer","allBatchesDone","handleOneBatch","batch"],"sources":["../../../../src/plugins/migration/data-migrator.ts"],"sourcesContent":["/**\n * The DataMigrator handles the documents from collections with older schemas\n * and transforms/saves them into the newest collection\n */\n/**\n * TODO this should be completely rewritten because:\n * - This could have been done in much less code which would be easier to uderstand\n *\n */\nimport {\n Subject,\n Observable\n} from 'rxjs';\nimport deepEqual from 'fast-deep-equal';\nimport {\n clone,\n toPromise,\n flatClone,\n getHeightOfRevision,\n createRevision,\n PROMISE_RESOLVE_VOID,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_NULL,\n getDefaultRxDocumentMeta,\n now\n} from '../../plugins/utils';\nimport {\n createRxSchema\n} from '../../rx-schema';\nimport {\n newRxError\n} from '../../rx-error';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from '../../hooks';\nimport type {\n RxCollection,\n RxDatabase,\n MigrationState,\n NumberFunctionMap,\n OldRxCollection,\n WithAttachmentsData,\n RxJsonSchema,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n InternalStoreCollectionDocType,\n RxStorageInstance\n} from '../../types';\nimport {\n RxSchema,\n getPreviousVersions\n} from '../../rx-schema';\nimport {\n getMigrationStateByDatabase,\n MigrationStateWithCollection\n} from './migration-state';\nimport { map } from 'rxjs/operators';\nimport {\n getWrappedStorageInstance\n} from '../../rx-storage-helper';\nimport {\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION\n} from '../../rx-database-internal-store';\nimport { normalizeMangoQuery } from '../../rx-query-helper';\n\nexport class DataMigrator {\n\n constructor(\n public newestCollection: RxCollection,\n public migrationStrategies: NumberFunctionMap\n ) {\n this.currentSchema = newestCollection.schema;\n this.database = newestCollection.database;\n this.name = newestCollection.name;\n }\n\n public currentSchema: RxSchema;\n public database: RxDatabase;\n public name: string;\n\n\n private _migrated: boolean = false;\n private _migratePromise?: Promise;\n private nonMigratedOldCollections: OldRxCollection[] = [];\n private allOldCollections: OldRxCollection[] = [];\n migrate(batchSize: number = 10): Observable {\n if (this._migrated) {\n throw newRxError('DM1');\n }\n this._migrated = true;\n\n const state = {\n done: false, // true if finished\n total: 0, // will be the doc-count\n handled: 0, // amount of handled docs\n success: 0, // handled docs which succeeded\n deleted: 0, // handled docs which got deleted\n percent: 0 // percentage\n };\n\n const stateSubject: Subject = new Subject();\n\n /**\n * Add to output of RxDatabase.migrationStates\n */\n const allSubject = getMigrationStateByDatabase(this.newestCollection.database);\n const allList = allSubject.getValue().slice(0);\n allList.push(stateSubject.asObservable());\n allSubject.next(allList);\n\n /**\n * TODO this is a side-effect which might throw\n * We did this because it is not possible to create new Observer(async(...))\n * @link https://github.com/ReactiveX/rxjs/issues/4074\n * In the future the whole migration plugin should be rewritten without rxjs\n * so we do not have this problem.\n */\n (() => {\n return _getOldCollections(this)\n .then(ret => {\n this.nonMigratedOldCollections = ret;\n this.allOldCollections = this.nonMigratedOldCollections.slice(0);\n\n const getAllDocuments = async (\n storageInstance: RxStorageInstance,\n schema: RxJsonSchema\n ): Promise[]> => {\n const storage = this.database.storage;\n const getAllQueryPrepared = storage.statics.prepareQuery(\n storageInstance.schema,\n normalizeMangoQuery(\n schema,\n {}\n )\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n };\n\n const countAll: Promise = Promise.all(\n this.nonMigratedOldCollections\n .map(oldCol => getAllDocuments(\n oldCol.storageInstance,\n oldCol.schema.jsonSchema\n ).then(allDocs => allDocs.length))\n );\n return countAll;\n })\n .then(countAll => {\n const totalCount: number = countAll\n .reduce((cur, prev) => prev = cur + prev, 0);\n state.total = totalCount;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n let currentCol = this.nonMigratedOldCollections.shift();\n let currentPromise = PROMISE_RESOLVE_VOID;\n while (currentCol) {\n const migrationState$ = migrateOldCollection(\n currentCol,\n batchSize\n );\n currentPromise = currentPromise.then(() => {\n return new Promise(res => {\n const sub = migrationState$.subscribe({\n next: (subState: any) => {\n state.handled++;\n (state as any)[subState.type] = (state as any)[subState.type] + 1;\n state.percent = Math.round(state.handled / state.total * 100);\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n },\n error: (e: any) => {\n sub.unsubscribe();\n // TODO we should not have to catch here.\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n stateSubject.error(e);\n },\n complete: () => {\n if (currentCol) {\n // TODO we should not have to catch here.\n currentCol.storageInstance.close().catch(() => { });\n }\n sub.unsubscribe();\n res();\n }\n });\n });\n });\n currentCol = this.nonMigratedOldCollections.shift();\n }\n return currentPromise;\n })\n .then(() => {\n state.done = true;\n state.percent = 100;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n stateSubject.complete();\n });\n })();\n\n\n return stateSubject.pipe(\n map(withCollection => withCollection.state)\n );\n }\n\n migratePromise(batchSize: number): Promise {\n if (!this._migratePromise) {\n this._migratePromise = mustMigrate(this)\n .then(must => {\n if (!must) {\n return PROMISE_RESOLVE_FALSE;\n } else {\n return new Promise((res, rej) => {\n const state$ = this.migrate(batchSize);\n (state$ as any).subscribe(null, rej, res);\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n })\n .catch(err => {\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n throw err;\n });\n }\n });\n }\n return this._migratePromise;\n }\n}\n\nexport async function createOldCollection(\n version: number,\n schemaObj: RxJsonSchema,\n dataMigrator: DataMigrator\n): Promise {\n const database = dataMigrator.newestCollection.database;\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: dataMigrator.newestCollection.name,\n schema: schemaObj,\n options: dataMigrator.newestCollection.instanceCreationOptions,\n multiInstance: database.multiInstance\n };\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n const storageInstance = await database.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n const ret: OldRxCollection = {\n version,\n dataMigrator,\n newestCollection: dataMigrator.newestCollection,\n database,\n schema: createRxSchema(schemaObj, false),\n storageInstance\n };\n\n ret.storageInstance = getWrappedStorageInstance(\n ret.database,\n storageInstance,\n schemaObj\n );\n\n return ret;\n}\n\n\nexport function getOldCollectionDocs(\n dataMigrator: DataMigrator\n): Promise[]> {\n\n const collectionDocKeys = getPreviousVersions(dataMigrator.currentSchema.jsonSchema)\n .map(version => dataMigrator.name + '-' + version);\n\n return dataMigrator.database.internalStore.findDocumentsById(\n collectionDocKeys.map(key => getPrimaryKeyOfInternalDocument(\n key,\n INTERNAL_CONTEXT_COLLECTION\n )),\n false\n ).then(docsObj => Object.values(docsObj));\n}\n\n/**\n * get an array with OldCollection-instances from all existing old storage-instances\n */\nexport async function _getOldCollections(\n dataMigrator: DataMigrator\n): Promise {\n const oldColDocs = await getOldCollectionDocs(dataMigrator);\n\n return Promise.all(\n oldColDocs\n .map(colDoc => {\n if (!colDoc) {\n return null as any;\n }\n return createOldCollection(\n colDoc.data.schema.version,\n colDoc.data.schema,\n dataMigrator\n );\n })\n .filter(colDoc => colDoc !== null)\n );\n}\n\n\n/**\n * returns true if a migration is needed\n */\nexport function mustMigrate(dataMigrator: DataMigrator): Promise {\n if (dataMigrator.currentSchema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return getOldCollectionDocs(dataMigrator)\n .then(oldColDocs => {\n if (oldColDocs.length === 0) {\n return false;\n } else {\n return true;\n }\n });\n}\n\nexport function runStrategyIfNotNull(\n oldCollection: OldRxCollection,\n version: number,\n docOrNull: any | null\n): Promise {\n if (docOrNull === null) {\n return PROMISE_RESOLVE_NULL;\n } else {\n const ret = oldCollection.dataMigrator.migrationStrategies[version](docOrNull, oldCollection);\n const retPromise = toPromise(ret);\n return retPromise;\n }\n}\n\nexport function getBatchOfOldCollection(\n oldCollection: OldRxCollection,\n batchSize: number\n): Promise {\n const storage = oldCollection.database.storage;\n const storageInstance = oldCollection.storageInstance;\n const preparedQuery = storage.statics.prepareQuery(\n storageInstance.schema,\n {\n selector: {},\n sort: [{ [oldCollection.schema.primaryPath]: 'asc' } as any],\n limit: batchSize,\n skip: 0\n }\n );\n\n return storageInstance\n .query(preparedQuery)\n .then(result => result.documents\n .map(doc => {\n doc = flatClone(doc);\n return doc;\n })\n );\n}\n\n/**\n * runs the doc-data through all following migrationStrategies\n * so it will match the newest schema.\n * @throws Error if final doc does not match final schema or migrationStrategy crashes\n * @return final object or null if migrationStrategy deleted it\n */\nexport function migrateDocumentData(\n oldCollection: OldRxCollection,\n docData: any\n): Promise {\n /**\n * We cannot deep-clone Blob or Buffer\n * so we just flat clone it here\n * and attach it to the deep cloned document data.\n */\n const attachmentsBefore = flatClone(docData._attachments);\n const mutateableDocData = clone(docData);\n mutateableDocData._attachments = attachmentsBefore;\n\n let nextVersion = oldCollection.version + 1;\n\n // run the document through migrationStrategies\n let currentPromise = Promise.resolve(mutateableDocData);\n while (nextVersion <= oldCollection.newestCollection.schema.version) {\n const version = nextVersion;\n currentPromise = currentPromise.then(docOrNull => runStrategyIfNotNull(\n oldCollection,\n version,\n docOrNull\n ));\n nextVersion++;\n }\n\n return currentPromise.then(doc => {\n if (doc === null) {\n return PROMISE_RESOLVE_NULL;\n }\n\n /**\n * Add _meta field if missing.\n * We need this to migration documents from pre-12.0.0 state\n * to version 12.0.0. Therefore we need to add the _meta field if it is missing.\n * TODO remove this in the major version 13.0.0\n */\n if (!doc._meta) {\n doc._meta = getDefaultRxDocumentMeta();\n }\n return doc;\n });\n}\n\n\nexport function isDocumentDataWithoutRevisionEqual(doc1: T, doc2: T): boolean {\n const doc1NoRev = Object.assign({}, doc1, {\n _attachments: undefined,\n _rev: undefined\n });\n const doc2NoRev = Object.assign({}, doc2, {\n _attachments: undefined,\n _rev: undefined\n });\n return deepEqual(doc1NoRev, doc2NoRev);\n}\n\n/**\n * transform documents data and save them to the new collection\n * @return status-action with status and migrated document\n */\nexport async function _migrateDocuments(\n oldCollection: OldRxCollection,\n documentsData: any[]\n): Promise<{ type: string; doc: any; }[]> {\n\n // run hooks that might mutate documentsData\n await Promise.all(\n documentsData.map(docData => runAsyncPluginHooks(\n 'preMigrateDocument',\n {\n docData,\n oldCollection\n }\n ))\n );\n // run the migration strategies on each document\n const migratedDocuments: (any | null)[] = await Promise.all(\n documentsData.map(docData => migrateDocumentData(oldCollection, docData))\n );\n\n\n const bulkWriteToStorageInput: RxDocumentData[] = [];\n const actions: any[] = [];\n\n documentsData.forEach((docData, idx) => {\n const migratedDocData: any | null = migratedDocuments[idx];\n const action = {\n res: null as any,\n type: '',\n migrated: migratedDocData,\n doc: docData,\n oldCollection,\n newestCollection: oldCollection.newestCollection\n };\n actions.push(action);\n\n /**\n * Determiniticly handle the revision\n * so migrating the same data on multiple instances\n * will result in the same output.\n */\n if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) {\n /**\n * Data not changed by migration strategies, keep the same revision.\n * This ensures that other replicated instances that did not migrate already\n * will still have the same document.\n */\n migratedDocData._rev = docData._rev;\n } else if (migratedDocData !== null) {\n /**\n * data changed, increase revision height\n * so replicating instances use our new document data\n */\n const newHeight = getHeightOfRevision(docData._rev) + 1;\n const newRevision = newHeight + '-' + createRevision(\n oldCollection.newestCollection.database.token\n );\n migratedDocData._rev = newRevision;\n }\n\n\n if (migratedDocData) {\n /**\n * save to newest collection\n * notice that this data also contains the attachments data\n */\n const attachmentsBefore = migratedDocData._attachments;\n const saveData: WithAttachmentsData = migratedDocData;\n saveData._attachments = attachmentsBefore;\n saveData._meta.lwt = now();\n bulkWriteToStorageInput.push(saveData);\n action.res = saveData;\n action.type = 'success';\n } else {\n /**\n * Migration strategy returned null\n * which means we should not migrate this document,\n * just drop it.\n */\n action.type = 'deleted';\n }\n });\n\n /**\n * Write the documents to the newest collection.\n * We need to add as revision\n * because we provide the _rev by our own\n * to have deterministic revisions in case the migration\n * runs on multiple nodes which must lead to the equal storage state.\n */\n if (bulkWriteToStorageInput.length) {\n /**\n * To ensure that we really keep that revision, we\n * hackly insert this document via the RxStorageInstance.originalStorageInstance\n * so that getWrappedStorageInstance() does not overwrite its own revision.\n */\n const originalStorageInstance: RxStorageInstance = (oldCollection.newestCollection.storageInstance as any).originalStorageInstance;\n await originalStorageInstance.bulkWrite(\n bulkWriteToStorageInput.map(document => ({ document })),\n 'data-migrator-import'\n );\n }\n\n // run hooks\n await Promise.all(\n actions.map(action => runAsyncPluginHooks(\n 'postMigrateDocument',\n action\n ))\n );\n\n // remove the documents from the old collection storage instance\n const bulkDeleteInputData = documentsData.map(docData => {\n const writeDeleted = flatClone(docData);\n writeDeleted._deleted = true;\n writeDeleted._attachments = {};\n return {\n previous: docData,\n document: writeDeleted\n };\n });\n\n if (bulkDeleteInputData.length) {\n await oldCollection.storageInstance.bulkWrite(\n bulkDeleteInputData,\n 'data-migrator-delete'\n );\n }\n\n return actions;\n}\n\n\n/**\n * deletes this.storageInstance and removes it from the database.collectionsCollection\n */\nexport function deleteOldCollection(\n oldCollection: OldRxCollection\n): Promise {\n return oldCollection.storageInstance.remove()\n .then(\n () => oldCollection.database.removeCollectionDoc(\n oldCollection.dataMigrator.name,\n oldCollection.schema\n )\n );\n}\n\n/**\n * runs the migration on all documents and deletes the storage instance afterwards\n */\nexport function migrateOldCollection(\n oldCollection: OldRxCollection,\n batchSize = 10\n): Observable {\n if (oldCollection._migrate) {\n // already running\n throw newRxError('DM3');\n }\n oldCollection._migrate = true;\n\n const observer = new Subject();\n\n /**\n * TODO this is a side-effect which might throw\n * @see DataMigrator.migrate()\n */\n (() => {\n let error: any;\n const allBatchesDone = () => {\n // remove this oldCollection\n return deleteOldCollection(oldCollection)\n .then(() => observer.complete());\n };\n const handleOneBatch = () => {\n return getBatchOfOldCollection(oldCollection, batchSize)\n .then(batch => {\n if (batch.length === 0) {\n allBatchesDone();\n return false;\n } else {\n return _migrateDocuments(oldCollection, batch)\n .then((actions: any[]) => actions.forEach(action => observer.next(action)))\n .catch(e => error = e)\n .then(() => true);\n }\n })\n .then(next => {\n if (!next) {\n return;\n }\n if (error) {\n observer.error(error);\n } else {\n handleOneBatch();\n }\n });\n };\n handleOneBatch();\n })();\n\n return observer.asObservable();\n}\n\nexport function migratePromise(\n oldCollection: OldRxCollection,\n batchSize?: number\n): Promise {\n if (!oldCollection._migratePromise) {\n oldCollection._migratePromise = new Promise((res, rej) => {\n const state$ = migrateOldCollection(oldCollection, batchSize);\n (state$ as any).subscribe(null, rej, res);\n });\n }\n return oldCollection._migratePromise;\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SACIA,OAAO,QAEJ,MAAM;AACb,OAAOC,SAAS,MAAM,iBAAiB;AACvC,SACIC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,mBAAmB,EACnBC,cA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oBAAoB,CAACkD,aAAa,EAAE9F,SAAS,CAAC;MAC5DkE,MAAM,CAASnB,SAAS,CAAC,IAAI,EAAEkB,GAAG,EAAEpB,GAAG,CAAC;IAC7C,CAAC,CAAC;EACN;EACA,OAAOiD,aAAa,CAAChC,eAAe;AACxC"} \ No newline at end of file diff --git a/dist/es/plugins/migration/index.js b/dist/es/plugins/migration/index.js index aef0f02b2ed..1456a13b948 100644 --- a/dist/es/plugins/migration/index.js +++ b/dist/es/plugins/migration/index.js @@ -1,6 +1,6 @@ import { combineLatest } from 'rxjs'; import { shareReplay, switchMap } from 'rxjs/operators'; -import { PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS } from '../../util'; +import { PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS } from '../../plugins/utils'; import { mustMigrate, DataMigrator } from './data-migrator'; import { getMigrationStateByDatabase, onDatabaseDestroy } from './migration-state'; export var DATA_MIGRATOR_BY_COLLECTION = new WeakMap(); diff --git a/dist/es/plugins/migration/index.js.map b/dist/es/plugins/migration/index.js.map index 2c0d92fe95c..42fc6be0ecf 100644 --- a/dist/es/plugins/migration/index.js.map +++ b/dist/es/plugins/migration/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["combineLatest","shareReplay","switchMap","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","mustMigrate","DataMigrator","getMigrationStateByDatabase","onDatabaseDestroy","DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","hooks","preDestroyRxDatabase","after","prototypes","RxDatabase","proto","migrationStates","pipe","list","RxCollection","getDataMigrator","has","set","asRxCollection","migrationStrategies","get","migrationNeeded","schema","version","_getOldCollections","getBatchOfOldCollection","migrateDocumentData","_migrateDocuments","deleteOldCollection","migrateOldCollection","migratePromise"],"sources":["../../../../src/plugins/migration/index.ts"],"sourcesContent":["import {\n combineLatest,\n Observable\n} from 'rxjs';\nimport {\n shareReplay,\n switchMap\n} from 'rxjs/operators';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase,\n AllMigrationStates\n} from '../../types';\nimport { PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS } from '../../util';\nimport {\n mustMigrate,\n DataMigrator\n} from './data-migrator';\nimport {\n getMigrationStateByDatabase,\n onDatabaseDestroy\n} from './migration-state';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration',\n rxdb: true,\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n switchMap(list => combineLatest(list)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getDataMigrator = function (this: RxCollection): DataMigrator {\n if (!DATA_MIGRATOR_BY_COLLECTION.has(this)) {\n DATA_MIGRATOR_BY_COLLECTION.set(\n this,\n new DataMigrator(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n\n }\n return DATA_MIGRATOR_BY_COLLECTION.get(this) as any;\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getDataMigrator());\n };\n }\n }\n};\n\n\n// used in tests\nexport {\n _getOldCollections,\n getBatchOfOldCollection,\n migrateDocumentData,\n _migrateDocuments,\n deleteOldCollection,\n migrateOldCollection,\n migratePromise,\n DataMigrator\n} from './data-migrator';\n"],"mappings":"AAAA,SACIA,aAAa,QAEV,MAAM;AACb,SACIC,WAAW,EACXC,SAAS,QACN,gBAAgB;AAOvB,SAASC,qBAAqB,EAAEC,0BAA0B,QAAQ,YAAY;AAC9E,SACIC,WAAW,EACXC,YAAY,QACT,iBAAiB;AACxB,SACIC,2BAA2B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QACT,iBAAiB"} \ No newline at end of file +{"version":3,"file":"index.js","names":["combineLatest","shareReplay","switchMap","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","mustMigrate","DataMigrator","getMigrationStateByDatabase","onDatabaseDestroy","DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","hooks","preDestroyRxDatabase","after","prototypes","RxDatabase","proto","migrationStates","pipe","list","RxCollection","getDataMigrator","has","set","asRxCollection","migrationStrategies","get","migrationNeeded","schema","version","_getOldCollections","getBatchOfOldCollection","migrateDocumentData","_migrateDocuments","deleteOldCollection","migrateOldCollection","migratePromise"],"sources":["../../../../src/plugins/migration/index.ts"],"sourcesContent":["import {\n combineLatest,\n Observable\n} from 'rxjs';\nimport {\n shareReplay,\n switchMap\n} from 'rxjs/operators';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase,\n AllMigrationStates\n} from '../../types';\nimport { PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS } from '../../plugins/utils';\nimport {\n mustMigrate,\n DataMigrator\n} from './data-migrator';\nimport {\n getMigrationStateByDatabase,\n onDatabaseDestroy\n} from './migration-state';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration',\n rxdb: true,\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n switchMap(list => combineLatest(list)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getDataMigrator = function (this: RxCollection): DataMigrator {\n if (!DATA_MIGRATOR_BY_COLLECTION.has(this)) {\n DATA_MIGRATOR_BY_COLLECTION.set(\n this,\n new DataMigrator(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n\n }\n return DATA_MIGRATOR_BY_COLLECTION.get(this) as any;\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getDataMigrator());\n };\n }\n }\n};\n\n\n// used in tests\nexport {\n _getOldCollections,\n getBatchOfOldCollection,\n migrateDocumentData,\n _migrateDocuments,\n deleteOldCollection,\n migrateOldCollection,\n migratePromise,\n DataMigrator\n} from './data-migrator';\n"],"mappings":"AAAA,SACIA,aAAa,QAEV,MAAM;AACb,SACIC,WAAW,EACXC,SAAS,QACN,gBAAgB;AAOvB,SAASC,qBAAqB,EAAEC,0BAA0B,QAAQ,qBAAqB;AACvF,SACIC,WAAW,EACXC,YAAY,QACT,iBAAiB;AACxB,SACIC,2BAA2B,EAC3BC,iBAAiB,QACd,mBAAmB;AAE1B,OAAO,IAAMC,2BAAgE,GAAG,IAAIC,OAAO,EAAE;AAE7F,OAAO,IAAMC,mBAA6B,GAAG;EACzCC,IAAI,EAAE,WAAW;EACjBC,IAAI,EAAE,IAAI;EACVC,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAER;IACX;EACJ,CAAC;EACDS,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACC,eAAe,GAAG,YAA4D;QAChF,OAAOb,2BAA2B,CAAC,IAAI,CAAC,CAACc,IAAI,CACzCnB,SAAS,CAAC,UAAAoB,IAAI;UAAA,OAAItB,aAAa,CAACsB,IAAI,CAAC;QAAA,EAAC,EACtCrB,WAAW,CAACG,0BAA0B,CAAC,CAC1C;MACL,CAAC;IACL,CAAC;IACDmB,YAAY,EAAE,sBAACJ,KAAU,EAAK;MAC1BA,KAAK,CAACK,eAAe,GAAG,YAA4C;QAChE,IAAI,CAACf,2BAA2B,CAACgB,GAAG,CAAC,IAAI,CAAC,EAAE;UACxChB,2BAA2B,CAACiB,GAAG,CAC3B,IAAI,EACJ,IAAIpB,YAAY,CACZ,IAAI,CAACqB,cAAc,EACnB,IAAI,CAACC,mBAAmB,CAC3B,CACJ;QAEL;QACA,OAAOnB,2BAA2B,CAACoB,GAAG,CAAC,IAAI,CAAC;MAChD,CAAC;MACDV,KAAK,CAACW,eAAe,GAAG,YAA8B;QAClD,IAAI,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAO7B,qBAAqB;QAChC;QACA,OAAOE,WAAW,CAAC,IAAI,CAACmB,eAAe,EAAE,CAAC;MAC9C,CAAC;IACL;EACJ;AACJ,CAAC;;AAGD;AACA,SACIS,kBAAkB,EAClBC,uBAAuB,EACvBC,mBAAmB,EACnBC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,EACpBC,cAAc,EACdjC,YAAY,QACT,iBAAiB"} \ No newline at end of file diff --git a/dist/es/plugins/migration/migration-state.js b/dist/es/plugins/migration/migration-state.js index 9648ad30b44..4dbe8f7520a 100644 --- a/dist/es/plugins/migration/migration-state.js +++ b/dist/es/plugins/migration/migration-state.js @@ -1,5 +1,5 @@ import { BehaviorSubject } from 'rxjs'; -import { ensureNotFalsy } from '../../util'; +import { ensureNotFalsy } from '../../plugins/utils'; export var DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap(); export function getMigrationStateByDatabase(database) { if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) { diff --git a/dist/es/plugins/migration/migration-state.js.map b/dist/es/plugins/migration/migration-state.js.map index 512d9c73fb1..3f2faa7f3f5 100644 --- a/dist/es/plugins/migration/migration-state.js.map +++ b/dist/es/plugins/migration/migration-state.js.map @@ -1 +1 @@ -{"version":3,"file":"migration-state.js","names":["BehaviorSubject","ensureNotFalsy","DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE","WeakMap","getMigrationStateByDatabase","database","has","set","subject","get","onDatabaseDestroy","complete"],"sources":["../../../../src/plugins/migration/migration-state.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Observable\n} from 'rxjs';\nimport type {\n MigrationState,\n RxCollection,\n RxDatabase\n} from '../../types';\nimport { ensureNotFalsy } from '../../util';\n\nexport type MigrationStateWithCollection = {\n collection: RxCollection;\n state: MigrationState;\n};\n\nexport const DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap[]>>();\n\nexport function getMigrationStateByDatabase(database: RxDatabase): BehaviorSubject[]> {\n if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) {\n DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(\n database,\n new BehaviorSubject[]>([])\n );\n }\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n return ensureNotFalsy(subject);\n}\n\n/**\n * Complete on database destroy\n * so people do not have to unsubscribe\n */\nexport function onDatabaseDestroy(database: RxDatabase) {\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n if (subject) {\n subject.complete();\n }\n}\n"],"mappings":"AAAA,SACIA,eAAe,QAEZ,MAAM;AAMb,SAASC,cAAc,QAAQ,YAAY;AAO3C,OAAO,IAAMC,wCAAwC,GAAG,IAAIC,OAAO,EAA2E;AAE9I,OAAO,SAASC,2BAA2B,CAACC,QAAoB,EAA+D;EAC3H,IAAI,CAACH,wCAAwC,CAACI,GAAG,CAACD,QAAQ,CAAC,EAAE;IACzDH,wCAAwC,CAACK,GAAG,CACxCF,QAAQ,EACR,IAAIL,eAAe,CAA6C,EAAE,CAAC,CACtE;EACL;EACA,IAAMQ,OAAO,GAAGN,wCAAwC,CAACO,GAAG,CAACJ,QAAQ,CAAC;EACtE,OAAOJ,cAAc,CAACO,OAAO,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASE,iBAAiB,CAACL,QAAoB,EAAE;EACpD,IAAMG,OAAO,GAAGN,wCAAwC,CAACO,GAAG,CAACJ,QAAQ,CAAC;EACtE,IAAIG,OAAO,EAAE;IACTA,OAAO,CAACG,QAAQ,EAAE;EACtB;AACJ"} \ No newline at end of file +{"version":3,"file":"migration-state.js","names":["BehaviorSubject","ensureNotFalsy","DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE","WeakMap","getMigrationStateByDatabase","database","has","set","subject","get","onDatabaseDestroy","complete"],"sources":["../../../../src/plugins/migration/migration-state.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Observable\n} from 'rxjs';\nimport type {\n MigrationState,\n RxCollection,\n RxDatabase\n} from '../../types';\nimport { ensureNotFalsy } from '../../plugins/utils';\n\nexport type MigrationStateWithCollection = {\n collection: RxCollection;\n state: MigrationState;\n};\n\nexport const DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap[]>>();\n\nexport function getMigrationStateByDatabase(database: RxDatabase): BehaviorSubject[]> {\n if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) {\n DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(\n database,\n new BehaviorSubject[]>([])\n );\n }\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n return ensureNotFalsy(subject);\n}\n\n/**\n * Complete on database destroy\n * so people do not have to unsubscribe\n */\nexport function onDatabaseDestroy(database: RxDatabase) {\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n if (subject) {\n subject.complete();\n }\n}\n"],"mappings":"AAAA,SACIA,eAAe,QAEZ,MAAM;AAMb,SAASC,cAAc,QAAQ,qBAAqB;AAOpD,OAAO,IAAMC,wCAAwC,GAAG,IAAIC,OAAO,EAA2E;AAE9I,OAAO,SAASC,2BAA2B,CAACC,QAAoB,EAA+D;EAC3H,IAAI,CAACH,wCAAwC,CAACI,GAAG,CAACD,QAAQ,CAAC,EAAE;IACzDH,wCAAwC,CAACK,GAAG,CACxCF,QAAQ,EACR,IAAIL,eAAe,CAA6C,EAAE,CAAC,CACtE;EACL;EACA,IAAMQ,OAAO,GAAGN,wCAAwC,CAACO,GAAG,CAACJ,QAAQ,CAAC;EACtE,OAAOJ,cAAc,CAACO,OAAO,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASE,iBAAiB,CAACL,QAAoB,EAAE;EACpD,IAAMG,OAAO,GAAGN,wCAAwC,CAACO,GAAG,CAACJ,QAAQ,CAAC;EACtE,IAAIG,OAAO,EAAE;IACTA,OAAO,CAACG,QAAQ,EAAE;EACtB;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/adapter-check.js b/dist/es/plugins/pouchdb/adapter-check.js deleted file mode 100644 index e696dfb61d8..00000000000 --- a/dist/es/plugins/pouchdb/adapter-check.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * this plugin adds the checkAdapter-function to rxdb - * you can use it to check if the given adapter is working in the current environment - */ -import { PouchDB } from './pouch-db'; -import { adapterObject, now, PROMISE_RESOLVE_FALSE, randomCouchString } from '../../util'; -/** - * The same pouchdb-location is used on each run - * To ensure when this is run multiple times, - * there will not be many created databases - */ -export var POUCHDB_LOCATION = 'rxdb-adapter-check'; -export function checkAdapter(adapter) { - // id of the document which is stored and removed to ensure everything works - var _id = POUCHDB_LOCATION + '-' + randomCouchString(12); - var pouch; - try { - pouch = new PouchDB(POUCHDB_LOCATION, adapterObject(adapter), { - auto_compaction: true, - revs_limit: 1 - }); - } catch (err) { - return PROMISE_RESOLVE_FALSE; - } - var recoveredDoc; - return pouch.info() // ensure that we wait until db is usable - // ensure write works - .then(function () { - return pouch.put({ - _id: _id, - value: { - ok: true, - time: now() - } - }); - }) - // ensure read works - .then(function () { - return pouch.get(_id); - }).then(function (doc) { - return recoveredDoc = doc; - }) - // ensure remove works - .then(function () { - return pouch.remove(recoveredDoc); - }).then(function () { - return true; - }).then(function () { - if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok) return true;else return false; - })["catch"](function () { - return false; - }); - - /** - * NOTICE: - * Do not remove the pouchdb-instance after the test - * The problem is that when this function is call in parallel, - * for example when you restore the tabs from a browser-session and open - * the same website multiple times at the same time, - * calling destroy would possibly crash the other call - */ -} -//# sourceMappingURL=adapter-check.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/adapter-check.js.map b/dist/es/plugins/pouchdb/adapter-check.js.map deleted file mode 100644 index 8fe5f044dee..00000000000 --- a/dist/es/plugins/pouchdb/adapter-check.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"adapter-check.js","names":["PouchDB","adapterObject","now","PROMISE_RESOLVE_FALSE","randomCouchString","POUCHDB_LOCATION","checkAdapter","adapter","_id","pouch","auto_compaction","revs_limit","err","recoveredDoc","info","then","put","value","ok","time","get","doc","remove"],"sources":["../../../../src/plugins/pouchdb/adapter-check.ts"],"sourcesContent":["/**\n * this plugin adds the checkAdapter-function to rxdb\n * you can use it to check if the given adapter is working in the current environment\n */\nimport {\n PouchDB\n} from './pouch-db';\nimport {\n adapterObject,\n now,\n PROMISE_RESOLVE_FALSE,\n randomCouchString\n} from '../../util';\nimport type {\n PouchDBInstance\n} from '../../types';\n\n/**\n * The same pouchdb-location is used on each run\n * To ensure when this is run multiple times,\n * there will not be many created databases\n */\nexport const POUCHDB_LOCATION = 'rxdb-adapter-check';\n\nexport function checkAdapter(adapter: any): Promise {\n // id of the document which is stored and removed to ensure everything works\n const _id = POUCHDB_LOCATION + '-' + randomCouchString(12);\n\n let pouch: PouchDBInstance;\n try {\n pouch = new (PouchDB as any)(\n POUCHDB_LOCATION,\n adapterObject(adapter), {\n auto_compaction: true,\n revs_limit: 1\n }\n );\n } catch (err) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let recoveredDoc: any;\n return pouch.info() // ensure that we wait until db is usable\n // ensure write works\n .then(() => pouch.put({\n _id,\n value: {\n ok: true,\n time: now()\n }\n }))\n // ensure read works\n .then(() => pouch.get(_id))\n .then(doc => recoveredDoc = doc)\n // ensure remove works\n .then(() => pouch.remove(recoveredDoc))\n .then(() => true)\n .then(() => {\n if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok)\n return true;\n else\n return false;\n })\n .catch(() => false);\n\n /**\n * NOTICE:\n * Do not remove the pouchdb-instance after the test\n * The problem is that when this function is call in parallel,\n * for example when you restore the tabs from a browser-session and open\n * the same website multiple times at the same time,\n * calling destroy would possibly crash the other call\n */\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,SACIA,OAAO,QACJ,YAAY;AACnB,SACIC,aAAa,EACbC,GAAG,EACHC,qBAAqB,EACrBC,iBAAiB,QACd,YAAY;AAKnB;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,gBAAgB,GAAG,oBAAoB;AAEpD,OAAO,SAASC,YAAY,CAACC,OAAY,EAAgB;EACrD;EACA,IAAMC,GAAG,GAAGH,gBAAgB,GAAG,GAAG,GAAGD,iBAAiB,CAAC,EAAE,CAAC;EAE1D,IAAIK,KAAsB;EAC1B,IAAI;IACAA,KAAK,GAAG,IAAKT,OAAO,CAChBK,gBAAgB,EAChBJ,aAAa,CAACM,OAAO,CAAC,EAAE;MACpBG,eAAe,EAAE,IAAI;MACrBC,UAAU,EAAE;IAChB,CAAC,CACJ;EACL,CAAC,CAAC,OAAOC,GAAG,EAAE;IACV,OAAOT,qBAAqB;EAChC;EAEA,IAAIU,YAAiB;EACrB,OAAOJ,KAAK,CAACK,IAAI,EAAE,CAAC;EAChB;EAAA,CACCC,IAAI,CAAC;IAAA,OAAMN,KAAK,CAACO,GAAG,CAAC;MAClBR,GAAG,EAAHA,GAAG;MACHS,KAAK,EAAE;QACHC,EAAE,EAAE,IAAI;QACRC,IAAI,EAAEjB,GAAG;MACb;IACJ,CAAC,CAAC;EAAA;EACF;EAAA,CACCa,IAAI,CAAC;IAAA,OAAMN,KAAK,CAACW,GAAG,CAACZ,GAAG,CAAC;EAAA,EAAC,CAC1BO,IAAI,CAAC,UAAAM,GAAG;IAAA,OAAIR,YAAY,GAAGQ,GAAG;EAAA;EAC/B;EAAA,CACCN,IAAI,CAAC;IAAA,OAAMN,KAAK,CAACa,MAAM,CAACT,YAAY,CAAC;EAAA,EAAC,CACtCE,IAAI,CAAC;IAAA,OAAM,IAAI;EAAA,EAAC,CAChBA,IAAI,CAAC,YAAM;IACR,IAAIF,YAAY,IAAIA,YAAY,CAACI,KAAK,IAAIJ,YAAY,CAACI,KAAK,CAACC,EAAE,EAC3D,OAAO,IAAI,CAAC,KAEZ,OAAO,KAAK;EACpB,CAAC,CAAC,SACI,CAAC;IAAA,OAAM,KAAK;EAAA,EAAC;;EAEvB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/custom-events-plugin.js b/dist/es/plugins/pouchdb/custom-events-plugin.js deleted file mode 100644 index 546fcc82622..00000000000 --- a/dist/es/plugins/pouchdb/custom-events-plugin.js +++ /dev/null @@ -1,617 +0,0 @@ -/* - * Instead of listening to pouch.changes, - * we overwrite pouchdbs bulkDocs() - * and create our own event stream, this will work more reliable - * and has less strange behaviors. - * Also we can better define what data we need for our events. - * @link http://jsbin.com/pagebi/1/edit?js,output - * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273 - * @link https://hasura.io/blog/couchdb-style-conflict-resolution-rxdb-hasura/ - */ - -import PouchDBCore from 'pouchdb-core'; -import { Subject } from 'rxjs'; -import { ensureNotFalsy, flatClone, getFromMapOrThrow, now, parseRevision, PROMISE_RESOLVE_VOID, randomCouchString } from '../../util'; -import { newRxError } from '../../rx-error'; -import { getEventKey, pouchChangeRowToChangeEvent, POUCHDB_DESIGN_PREFIX, POUCHDB_LOCAL_PREFIX, pouchDocumentDataToRxDocumentData, writeAttachmentsToAttachments } from './pouchdb-helper'; -export var eventEmitDataToStorageEvents = function eventEmitDataToStorageEvents(pouchDBInstance, primaryPath, emitData) { - try { - var ret = []; - var _temp7 = function () { - if (!emitData.writeOptions.custom && emitData.writeOptions.hasOwnProperty('new_edits') && emitData.writeOptions.new_edits === false) { - return Promise.resolve(Promise.all(emitData.writeDocs.map(function (writeDoc) { - try { - var id = writeDoc._id; - writeDoc = pouchDocumentDataToRxDocumentData(primaryPath, writeDoc); - return Promise.resolve(writeAttachmentsToAttachments(writeDoc._attachments)).then(function (_writeAttachmentsToAt) { - writeDoc._attachments = _writeAttachmentsToAt; - var previousDoc = emitData.previousDocs.get(id); - if (previousDoc) { - previousDoc = pouchDocumentDataToRxDocumentData(primaryPath, previousDoc); - } - if (previousDoc) { - var parsedRevPrevious = parseRevision(previousDoc._rev); - var parsedRevNew = parseRevision(writeDoc._rev); - if (parsedRevPrevious.height > parsedRevNew.height || - /** - * If the revision height is equal, - * we determine the higher hash as winner. - */ - - parsedRevPrevious.height === parsedRevNew.height && parsedRevPrevious.hash > parsedRevNew.hash) { - /** - * The newly added document was not the latest revision - * so we drop the write. - * With plain PouchDB it makes sense to store conflicting branches of the document - * but RxDB assumes that the conflict is resolved directly. - */ - return; - } - } - if (!previousDoc && writeDoc._deleted) { - // deleted document was added as revision - return; - } - if (previousDoc && previousDoc._deleted && writeDoc._deleted) { - // delete document was deleted again - return; - } - var event; - if ((!previousDoc || previousDoc._deleted) && !writeDoc._deleted) { - // was insert - event = { - operation: 'INSERT', - doc: writeDoc, - id: id, - previous: null - }; - } else if (writeDoc._deleted && previousDoc && !previousDoc._deleted) { - // was delete - previousDoc._rev = writeDoc._rev; - event = { - operation: 'DELETE', - doc: writeDoc, - id: id, - previous: previousDoc - }; - } else if (previousDoc) { - // was update - event = { - operation: 'UPDATE', - doc: writeDoc, - id: id, - previous: previousDoc - }; - } else { - throw newRxError('SNH', { - args: { - writeDoc: writeDoc - } - }); - } - var changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event, emitData.startTime, emitData.endTime); - ret.push(changeEvent); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); // eslint-disable-next-line brace-style - } else { - var _temp8 = function () { - if (!emitData.writeOptions.custom || emitData.writeOptions.custom && !emitData.writeOptions.custom.writeRowById) { - var writeDocsById = new Map(); - emitData.writeDocs.forEach(function (writeDoc) { - return writeDocsById.set(writeDoc._id, writeDoc); - }); - return Promise.resolve(Promise.all(emitData.writeResult.map(function (resultRow) { - try { - var id = resultRow.id; - if (id.startsWith(POUCHDB_DESIGN_PREFIX) || id.startsWith(POUCHDB_LOCAL_PREFIX)) { - return Promise.resolve(); - } - var writeDoc = getFromMapOrThrow(writeDocsById, resultRow.id); - writeDoc = pouchDocumentDataToRxDocumentData(primaryPath, writeDoc); - return Promise.resolve(writeAttachmentsToAttachments(writeDoc._attachments)).then(function (_writeAttachmentsToAt2) { - writeDoc._attachments = _writeAttachmentsToAt2; - writeDoc = flatClone(writeDoc); - writeDoc._rev = resultRow.rev; - var event = pouchChangeRowToChangeEvent(primaryPath, writeDoc); - var changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event); - ret.push(changeEvent); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } else { - var writeMap = emitData.writeOptions.custom.writeRowById; - return Promise.resolve(Promise.all(emitData.writeResult.map(function (resultRow) { - try { - if (resultRow.error) { - return Promise.resolve(); - } - var id = resultRow.id; - var writeRow = getFromMapOrThrow(writeMap, id); - return Promise.resolve(writeAttachmentsToAttachments(writeRow.document._attachments)).then(function (attachments) { - function _temp11() { - if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) {} else { - var changeEvent = changeEventToNormal(pouchDBInstance, ensureNotFalsy(emitData.writeOptions.custom).primaryPath, event, emitData.startTime, emitData.endTime); - ret.push(changeEvent); - } - } - var newDoc = Object.assign({}, writeRow.document, { - _attachments: attachments, - _rev: resultRow.rev - }); - var event; - var _temp10 = function () { - if (!writeRow.previous || writeRow.previous._deleted) { - // was insert - event = { - operation: 'INSERT', - doc: newDoc, - id: id, - previous: null - }; - } else { - var _temp12 = function () { - if (writeRow.document._deleted) { - // was delete - // we need to add the new revision to the previous doc - // so that the eventkey is calculated correctly. - // Is this a hack? idk. - return Promise.resolve(writeAttachmentsToAttachments(writeRow.previous._attachments)).then(function (attachmentsInner) { - var previousDoc = Object.assign({}, writeRow.previous, { - _attachments: attachmentsInner - }); - event = { - operation: 'DELETE', - doc: writeRow.document, - id: resultRow.id, - previous: previousDoc - }; - }); - } else { - // was update - event = { - operation: 'UPDATE', - doc: newDoc, - id: resultRow.id, - previous: writeRow.previous - }; - } - }(); - if (_temp12 && _temp12.then) return _temp12.then(function () {}); - } - }(); - return _temp10 && _temp10.then ? _temp10.then(_temp11) : _temp11(_temp10); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } - }(); - if (_temp8 && _temp8.then) return _temp8.then(function () {}); - } - }(); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () { - return ret; - }) : ret); - } catch (e) { - return Promise.reject(e); - } -}; -// ensure only added once -var addedToPouch = false; -export var EVENT_EMITTER_BY_POUCH_INSTANCE = new Map(); -export function getCustomEventEmitterByPouch(pouch) { - var key = [pouch.__opts.name, pouch.adapter].join('|'); - var emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key); - if (!emitter) { - emitter = { - subject: new Subject() - }; - EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter); - } - return emitter; -} - -/** - * Counter, used to debug stuff. - */ -var i = 0; - -/** - * Because we cannot force pouchdb to await bulkDocs runs - * inside of a transaction, like done with the other RxStorage implementations, - * we have to ensure the calls to bulkDocs() do not run in parallel. - * - * TODO this is somehow a hack. Instead of doing that, inspect how - * PouchDB runs bulkDocs internally and adapt that transaction handling. - */ -var BULK_DOC_RUN_QUEUE = new WeakMap(); - -/** - * PouchDB is like a minefield, - * where stuff randomly does not work dependent on some conditions. - * So instead of doing plain writes, - * we hack into the bulkDocs() function - * and adjust the behavior accordingly. - */ -export function addCustomEventsPluginToPouch() { - if (addedToPouch) { - return; - } - addedToPouch = true; - var oldBulkDocs = PouchDBCore.prototype.bulkDocs; - - /** - * Ensure we do not run bulkDocs() in parallel on the same PouchDB instance. - */ - var newBulkDocs = function newBulkDocs(body, options, callback) { - var _this = this; - /** - * Normalize inputs - * because there are many ways to call pouchdb.bulkDocs() - */ - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } - - /** - * PouchDB internal requests - * must still be handled normally - * to decrease the likelyness of bugs. - */ - var internalPouches = ['_replicator', '_users', 'pouch__all_dbs__']; - if (internalPouches.includes(this.name) || this.name.includes('-mrview-')) { - return oldBulkDocs.call(this, body, options, function (err, result) { - if (err) { - if (callback) { - callback(err, null); - } - } else { - if (callback) { - callback(null, result); - } - } - }); - } - var queue = BULK_DOC_RUN_QUEUE.get(this); - if (!queue) { - queue = PROMISE_RESOLVE_VOID; - } - queue = queue.then(function () { - try { - return Promise.resolve(newBulkDocsInner.bind(_this)(body, options, callback)); - } catch (e) { - return Promise.reject(e); - } - }); - BULK_DOC_RUN_QUEUE.set(this, queue); - return queue; - }; - var newBulkDocsInner = function newBulkDocsInner(body, options, callback) { - try { - var _temp3 = function _temp3() { - /** - * Custom handling if the call came from RxDB (options.custom is set). - */ - var usePouchResult = []; - var hasNonErrorWrite = false; - if (options.custom && options.hasOwnProperty('new_edits') && options.new_edits === false) { - /** - * Reset the write docs array, - * because we only write non-conflicting documents. - */ - docs = []; - var writeRowById = options.custom.writeRowById; - var insertDocsById = options.custom.insertDocsById; - Array.from(writeRowById.entries()).forEach(function (_ref) { - var id = _ref[0], - writeRow = _ref[1]; - var previousRev = writeRow.previous ? writeRow.previous._rev : null; - var newRev = parseRevision(writeRow.document._rev); - var docInDb = previousDocsInDb.get(id); - var docInDbRev = docInDb ? docInDb._rev : null; - if (docInDbRev !== previousRev) { - // we have a conflict - usePouchResult.push({ - error: true, - id: id, - status: 409 - }); - } else { - var useRevisions = { - start: newRev.height, - ids: docInDb ? docInDb._revisions.ids.slice(0) : [] - }; - useRevisions.ids.unshift(newRev.hash); - var useNewRev = useRevisions.start + '-' + newRev.hash; - hasNonErrorWrite = true; - var writeToPouchDocData = Object.assign({}, insertDocsById.get(id), { - _revisions: useRevisions, - _rev: useNewRev - }); - docs.push(writeToPouchDocData); - usePouchResult.push({ - ok: true, - id: id, - rev: writeRow.document._rev - }); - } - }); - - /** - * Optimization shortcut, - * if all document writes were conflict errors, - * we can skip directly. - */ - if (!hasNonErrorWrite) { - return usePouchResult; - } - } - - /** - * pouchdb calls this function again with transformed input. - * This would lead to duplicate events. So we marks the deeper calls via the options - * parameter and do not emit events if it is set. - */ - var deeperOptions = flatClone(options); - deeperOptions.isDeeper = true; - var callReturn; - var callPromise = new Promise(function (res, rej) { - /** - * The emitted EventBulk from the write to the pouchdb, needs to contain a checkpoint field. - * Because PouchDB works on sequence number to sort changes, - * we have to fetch the latest sequence number out of the events because it - * is not possible to that that from pouch.bulkDocs(). - */ - var docIds = new Set(docs.map(function (d) { - return d._id; - })); - var heighestSequence = 0; - var changesSub; - var heighestSequencePromise = new Promise(function (res2) { - changesSub = _this2.changes({ - since: 'now', - live: true, - include_docs: true - }).on('change', function (change) { - var docId = change.id; - if (docIds.has(docId)) { - docIds["delete"](docId); - if (heighestSequence < change.seq) { - heighestSequence = change.seq; - } - if (docIds.size === 0) { - changesSub.cancel(); - res2(heighestSequence); - } - } - }); - }); - - /** - * We cannot send the custom here, - * because when a migration between different major RxDB versions is done, - * multiple versions of the RxDB PouchDB RxStorage might have added their - * custom method via PouchDBCore.plugin() - */ - var useOptsForOldBulkDocs = flatClone(deeperOptions); - delete useOptsForOldBulkDocs.custom; - callReturn = oldBulkDocs.call(_this2, docs, useOptsForOldBulkDocs, function (err, result) { - if (err) { - if (callback) { - callback(err); - } else { - rej(err); - } - } else { - return function () { - try { - var _temp5 = function _temp5() { - result.forEach(function (row) { - usePouchResult.push(row); - }); - - /** - * For calls that came from RxDB, - * we have to ensure that the events are emitted - * before the actual call resolves. - */ - var eventsPromise = PROMISE_RESOLVE_VOID; - if (!options.isDeeper) { - var endTime = now(); - var emitData = { - emitId: runId, - writeDocs: docs, - writeOptions: options, - writeResult: usePouchResult, - previousDocs: previousDocsInDb, - startTime: startTime, - endTime: endTime - }; - eventsPromise = eventEmitDataToStorageEvents(_this2, '_id', emitData).then(function (events) { - var eventBulk = { - id: randomCouchString(10), - events: events, - checkpoint: { - sequence: heighestSequenceInner - }, - context: options.custom ? options.custom.context : 'pouchdb-internal' - }; - var emitter = getCustomEventEmitterByPouch(_this2); - emitter.subject.next(eventBulk); - }); - } - if (callback) { - callback(null, usePouchResult); - } else { - return eventsPromise.then(function () { - res(usePouchResult); - return usePouchResult; - }); - } - }; - var hasError = result.find(function (row) { - return row.error; - }); - var heighestSequenceInner = -1; - var _temp4 = function () { - if (!hasError) { - return Promise.resolve(heighestSequencePromise).then(function (_heighestSequenceProm) { - heighestSequenceInner = _heighestSequenceProm; - }); - } else { - changesSub.cancel(); - } - }(); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }(); - } - }); - }); - return options.custom ? callPromise : callReturn; - }; - var _this2 = this; - var startTime = now(); - var runId = i++; - - /** - * Normalize inputs - * because there are many ways to call pouchdb.bulkDocs() - */ - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } - var docs; - if (Array.isArray(body)) { - docs = body; - } else if (body === undefined) { - docs = []; - } else { - docs = body.docs; - if (body.hasOwnProperty('new_edits')) { - options.new_edits = body.new_edits; - } - } - - // throw if no docs given, because RxDB should never make such a call. - if (docs.length === 0) { - throw newRxError('SNH', { - args: { - body: body, - options: options - } - }); - } - - /** - * If new_edits=false we have to first find the current state - * of the document and can later check if the state was changed - * because a new revision was written and we have to emit an event. - */ - var previousDocsInDb = options.custom ? options.custom.previousDocsInDb : new Map(); - var _temp2 = function () { - if (options.hasOwnProperty('new_edits') && options.new_edits === false) { - return Promise.resolve(_this2.bulkGet({ - docs: docs.map(function (doc) { - return { - id: doc._id - }; - }), - revs: true, - latest: true - })).then(function (viaBulkGet) { - /** - * bulkGet() does not return deleted documents, - * so we must refetch them via allDocs() afterwards. - */ - var mustRefetchBecauseDeleted = []; - viaBulkGet.results.forEach(function (resultRow) { - var firstDoc = resultRow.docs[0]; - if (firstDoc.ok) { - previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok); - } else { - if (firstDoc.error && firstDoc.error.reason === 'deleted') { - mustRefetchBecauseDeleted.push(resultRow.id); - } - } - }); - var _temp = function () { - if (mustRefetchBecauseDeleted.length > 0) { - return Promise.resolve(_this2.allDocs({ - keys: mustRefetchBecauseDeleted, - include_docs: true, - conflicts: true - })).then(function (deletedDocsViaAllDocs) { - var idsWithRevs = []; - deletedDocsViaAllDocs.rows.forEach(function (row) { - idsWithRevs.push({ - id: row.id, - rev: row.value.rev - }); - }); - return Promise.resolve(_this2.bulkGet({ - docs: idsWithRevs, - revs: true, - latest: true - })).then(function (deletedDocsViaBulkGetWithRev) { - deletedDocsViaBulkGetWithRev.results.forEach(function (resultRow) { - var firstDoc = resultRow.docs[0]; - if (firstDoc.ok) { - previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok); - } else { - throw newRxError('SNH', { - args: { - deletedDocsViaBulkGetWithRev: deletedDocsViaBulkGetWithRev, - resultRow: resultRow - } - }); - } - }); - }); - }); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } - }; - PouchDBCore.plugin({ - bulkDocs: newBulkDocs - }); -} -export function changeEventToNormal(pouchDBInstance, primaryPath, change, startTime, endTime) { - var doc = change.operation === 'DELETE' ? change.previous : change.doc; - var primary = doc[primaryPath]; - var storageChangeEvent = { - eventId: getEventKey(pouchDBInstance, primary, change), - documentId: primary, - documentData: change.doc, - previousDocumentData: change.previous, - operation: change.operation, - startTime: startTime, - endTime: endTime - }; - return storageChangeEvent; -} -//# sourceMappingURL=custom-events-plugin.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/custom-events-plugin.js.map b/dist/es/plugins/pouchdb/custom-events-plugin.js.map deleted file mode 100644 index 06f32ff22f9..00000000000 --- a/dist/es/plugins/pouchdb/custom-events-plugin.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"custom-events-plugin.js","names":["PouchDBCore","Subject","ensureNotFalsy","flatClone","getFromMapOrThrow","now","parseRevision","PROMISE_RESOLVE_VOID","randomCouchString","newRxError","getEventKey","pouchChangeRowToChangeEvent","POUCHDB_DESIGN_PREFIX","POUCHDB_LOCAL_PREFIX","pouchDocumentDataToRxDocumentData","writeAttachmentsToAttachments","eventEmitDataToStorageEvents","pouchDBInstance","primaryPath","emitData","ret","writeOptions","custom","hasOwnProperty","new_edits","Promise","all","writeDocs","map","writeDoc","id","_id","_attachments","previousDoc","previousDocs","get","parsedRevPrevious","_rev","parsedRevNew","height","hash","_deleted","event","operation","doc","previous","args","changeEvent","changeEventToNormal","startTime","endTime","push","writeRowById","writeDocsById","Map","forEach","set","writeResult","resultRow","startsWith","rev","writeMap","error","writeRow","document","attachments","newDoc","Object","assign","attachmentsInner","addedToPouch","EVENT_EMITTER_BY_POUCH_INSTANCE","getCustomEventEmitterByPouch","pouch","key","__opts","name","adapter","join","emitter","subject","i","BULK_DOC_RUN_QUEUE","WeakMap","addCustomEventsPluginToPouch","oldBulkDocs","prototype","bulkDocs","newBulkDocs","body","options","callback","internalPouches","includes","call","err","result","queue","then","newBulkDocsInner","bind","usePouchResult","hasNonErrorWrite","docs","insertDocsById","Array","from","entries","previousRev","newRev","docInDb","previousDocsInDb","docInDbRev","status","useRevisions","start","ids","_revisions","slice","unshift","useNewRev","writeToPouchDocData","ok","deeperOptions","isDeeper","callReturn","callPromise","res","rej","docIds","Set","d","heighestSequence","changesSub","heighestSequencePromise","res2","changes","since","live","include_docs","on","change","docId","has","seq","size","cancel","useOptsForOldBulkDocs","row","eventsPromise","emitId","runId","events","eventBulk","checkpoint","sequence","heighestSequenceInner","context","next","hasError","find","isArray","undefined","length","bulkGet","revs","latest","viaBulkGet","mustRefetchBecauseDeleted","results","firstDoc","reason","allDocs","keys","conflicts","deletedDocsViaAllDocs","idsWithRevs","rows","value","deletedDocsViaBulkGetWithRev","plugin","primary","storageChangeEvent","eventId","documentId","documentData","previousDocumentData"],"sources":["../../../../src/plugins/pouchdb/custom-events-plugin.ts"],"sourcesContent":["/*\n * Instead of listening to pouch.changes,\n * we overwrite pouchdbs bulkDocs()\n * and create our own event stream, this will work more reliable\n * and has less strange behaviors.\n * Also we can better define what data we need for our events.\n * @link http://jsbin.com/pagebi/1/edit?js,output\n * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273\n * @link https://hasura.io/blog/couchdb-style-conflict-resolution-rxdb-hasura/\n */\n\nimport type {\n BulkWriteRow,\n EventBulk,\n PouchBulkDocOptions,\n PouchBulkDocResultRow,\n PouchChangesOnChangeEvent,\n PouchCheckpoint,\n PouchDBInstance,\n PouchWriteError,\n RxDocumentData,\n RxStorageChangeEvent\n} from '../../types';\nimport PouchDBCore from 'pouchdb-core';\nimport { Subject } from 'rxjs';\nimport {\n ensureNotFalsy,\n flatClone,\n getFromMapOrThrow,\n now,\n parseRevision,\n PROMISE_RESOLVE_VOID,\n randomCouchString\n} from '../../util';\nimport { newRxError } from '../../rx-error';\nimport {\n getEventKey,\n pouchChangeRowToChangeEvent,\n POUCHDB_DESIGN_PREFIX,\n POUCHDB_LOCAL_PREFIX,\n pouchDocumentDataToRxDocumentData,\n writeAttachmentsToAttachments\n} from './pouchdb-helper';\nimport type { ChangeEvent } from 'event-reduce-js';\n\n// ensure only added once\nlet addedToPouch = false;\n\ndeclare type EmitData = {\n emitId: number;\n writeOptions: PouchBulkDocOptions;\n writeDocs: any[];\n writeResult: (PouchBulkDocResultRow | PouchWriteError)[];\n // used on new_edits=false to check if the last revision has changed\n previousDocs: Map;\n startTime: number;\n endTime: number;\n};\n\n\ndeclare type Emitter = {\n subject: Subject>, PouchCheckpoint>>;\n};\nexport const EVENT_EMITTER_BY_POUCH_INSTANCE: Map> = new Map();\n\nexport function getCustomEventEmitterByPouch(\n pouch: PouchDBInstance\n): Emitter {\n const key = [\n pouch.__opts.name,\n pouch.adapter\n ].join('|');\n let emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key);\n if (!emitter) {\n emitter = {\n subject: new Subject()\n };\n EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter);\n }\n return emitter;\n}\n\n\n/**\n * Counter, used to debug stuff.\n */\nlet i = 0;\n\n\n/**\n * Because we cannot force pouchdb to await bulkDocs runs\n * inside of a transaction, like done with the other RxStorage implementations,\n * we have to ensure the calls to bulkDocs() do not run in parallel.\n *\n * TODO this is somehow a hack. Instead of doing that, inspect how\n * PouchDB runs bulkDocs internally and adapt that transaction handling.\n */\nconst BULK_DOC_RUN_QUEUE: WeakMap> = new WeakMap();\n\n/**\n * PouchDB is like a minefield,\n * where stuff randomly does not work dependent on some conditions.\n * So instead of doing plain writes,\n * we hack into the bulkDocs() function\n * and adjust the behavior accordingly.\n */\nexport function addCustomEventsPluginToPouch() {\n if (addedToPouch) {\n return;\n }\n addedToPouch = true;\n\n const oldBulkDocs: any = PouchDBCore.prototype.bulkDocs;\n\n /**\n * Ensure we do not run bulkDocs() in parallel on the same PouchDB instance.\n */\n const newBulkDocs = function (\n this: PouchDBInstance,\n body: any[] | { docs: any[]; new_edits?: boolean; },\n options: PouchBulkDocOptions,\n callback: Function\n ) {\n\n /**\n * Normalize inputs\n * because there are many ways to call pouchdb.bulkDocs()\n */\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (!options) {\n options = {};\n }\n\n\n /**\n * PouchDB internal requests\n * must still be handled normally\n * to decrease the likelyness of bugs.\n */\n const internalPouches = [\n '_replicator',\n '_users',\n 'pouch__all_dbs__'\n ];\n if (\n (\n internalPouches.includes(this.name) ||\n this.name.includes('-mrview-')\n )\n ) {\n return oldBulkDocs.call(\n this,\n body,\n options,\n (err: any, result: (PouchBulkDocResultRow | PouchWriteError)[]) => {\n if (err) {\n if (callback) {\n callback(err, null);\n }\n } else {\n if (callback) {\n callback(null, result);\n }\n }\n });\n }\n\n\n let queue = BULK_DOC_RUN_QUEUE.get(this);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue.then(async () => {\n const ret = await newBulkDocsInner.bind(this)(\n body,\n options,\n callback\n );\n return ret;\n });\n BULK_DOC_RUN_QUEUE.set(this, queue);\n return queue;\n };\n\n\n const newBulkDocsInner = async function (\n this: PouchDBInstance,\n body: any[] | { docs: any[]; new_edits?: boolean; },\n options: PouchBulkDocOptions,\n callback: Function\n ) {\n const startTime = now();\n const runId = i++;\n\n /**\n * Normalize inputs\n * because there are many ways to call pouchdb.bulkDocs()\n */\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (!options) {\n options = {};\n }\n\n let docs: any[];\n if (Array.isArray(body)) {\n docs = body;\n } else if (body === undefined) {\n docs = [];\n } else {\n docs = body.docs;\n if (body.hasOwnProperty('new_edits')) {\n options.new_edits = body.new_edits;\n }\n }\n\n // throw if no docs given, because RxDB should never make such a call.\n if (docs.length === 0) {\n throw newRxError('SNH', {\n args: {\n body,\n options\n }\n });\n }\n\n\n /**\n * If new_edits=false we have to first find the current state\n * of the document and can later check if the state was changed\n * because a new revision was written and we have to emit an event.\n */\n const previousDocsInDb: Map> = options.custom ? options.custom.previousDocsInDb : new Map();\n if (\n options.hasOwnProperty('new_edits') &&\n options.new_edits === false\n ) {\n const viaBulkGet = await this.bulkGet({\n docs: docs.map(doc => ({ id: doc._id })),\n revs: true,\n latest: true\n });\n\n /**\n * bulkGet() does not return deleted documents,\n * so we must refetch them via allDocs() afterwards.\n */\n const mustRefetchBecauseDeleted: string[] = [];\n\n viaBulkGet.results.forEach(resultRow => {\n const firstDoc = resultRow.docs[0];\n if (firstDoc.ok) {\n previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok);\n } else {\n if (firstDoc.error && firstDoc.error.reason === 'deleted') {\n mustRefetchBecauseDeleted.push(resultRow.id);\n }\n }\n });\n\n if (mustRefetchBecauseDeleted.length > 0) {\n const deletedDocsViaAllDocs = await this.allDocs({\n keys: mustRefetchBecauseDeleted,\n include_docs: true,\n conflicts: true,\n });\n\n const idsWithRevs: { id: string; rev: string; }[] = [];\n deletedDocsViaAllDocs.rows.forEach(row => {\n idsWithRevs.push({\n id: row.id,\n rev: row.value.rev\n });\n });\n\n const deletedDocsViaBulkGetWithRev = await this.bulkGet({\n docs: idsWithRevs,\n revs: true,\n latest: true\n });\n\n deletedDocsViaBulkGetWithRev.results.forEach(resultRow => {\n const firstDoc = resultRow.docs[0];\n if (firstDoc.ok) {\n previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok);\n } else {\n throw newRxError('SNH', {\n args: {\n deletedDocsViaBulkGetWithRev,\n resultRow\n }\n });\n }\n });\n\n }\n }\n\n /**\n * Custom handling if the call came from RxDB (options.custom is set).\n */\n const usePouchResult: (PouchBulkDocResultRow | PouchWriteError)[] = [];\n let hasNonErrorWrite = false;\n if (\n options.custom &&\n options.hasOwnProperty('new_edits') &&\n options.new_edits === false\n ) {\n /**\n * Reset the write docs array,\n * because we only write non-conflicting documents.\n */\n docs = [];\n const writeRowById: Map> = options.custom.writeRowById;\n const insertDocsById: Map = options.custom.insertDocsById;\n\n Array.from(writeRowById.entries()).forEach(([id, writeRow]) => {\n const previousRev = writeRow.previous ? writeRow.previous._rev : null;\n const newRev = parseRevision(writeRow.document._rev);\n const docInDb = previousDocsInDb.get(id);\n const docInDbRev: string | null = docInDb ? docInDb._rev : null;\n\n if (\n docInDbRev !== previousRev\n ) {\n // we have a conflict\n usePouchResult.push({\n error: true,\n id,\n status: 409\n });\n } else {\n const useRevisions = {\n start: newRev.height,\n ids: docInDb ? docInDb._revisions.ids.slice(0) : []\n };\n useRevisions.ids.unshift(newRev.hash);\n const useNewRev = useRevisions.start + '-' + newRev.hash;\n\n hasNonErrorWrite = true;\n const writeToPouchDocData = Object.assign(\n {},\n insertDocsById.get(id),\n {\n _revisions: useRevisions,\n _rev: useNewRev\n }\n );\n docs.push(writeToPouchDocData);\n usePouchResult.push({\n ok: true,\n id,\n rev: writeRow.document._rev\n });\n }\n });\n\n /**\n * Optimization shortcut,\n * if all document writes were conflict errors,\n * we can skip directly.\n */\n if (!hasNonErrorWrite) {\n return usePouchResult;\n }\n }\n\n /**\n * pouchdb calls this function again with transformed input.\n * This would lead to duplicate events. So we marks the deeper calls via the options\n * parameter and do not emit events if it is set.\n */\n const deeperOptions = flatClone(options);\n deeperOptions.isDeeper = true;\n let callReturn: any;\n const callPromise = new Promise((res, rej) => {\n\n /**\n * The emitted EventBulk from the write to the pouchdb, needs to contain a checkpoint field.\n * Because PouchDB works on sequence number to sort changes,\n * we have to fetch the latest sequence number out of the events because it\n * is not possible to that that from pouch.bulkDocs().\n */\n const docIds: Set = new Set(docs.map(d => d._id));\n let heighestSequence = 0;\n let changesSub: PouchChangesOnChangeEvent;\n const heighestSequencePromise = new Promise(res2 => {\n changesSub = this.changes({\n since: 'now',\n live: true,\n include_docs: true\n }).on('change', (change: any) => {\n const docId: string = change.id;\n if (docIds.has(docId)) {\n docIds.delete(docId);\n if (heighestSequence < change.seq) {\n heighestSequence = change.seq;\n }\n\n if (docIds.size === 0) {\n (changesSub as any).cancel();\n res2(heighestSequence);\n }\n }\n }) as any;\n });\n\n\n /**\n * We cannot send the custom here,\n * because when a migration between different major RxDB versions is done,\n * multiple versions of the RxDB PouchDB RxStorage might have added their\n * custom method via PouchDBCore.plugin()\n */\n const useOptsForOldBulkDocs = flatClone(deeperOptions);\n delete useOptsForOldBulkDocs.custom;\n\n callReturn = oldBulkDocs.call(\n this,\n docs,\n useOptsForOldBulkDocs,\n (err: any, result: (PouchBulkDocResultRow | PouchWriteError)[]) => {\n if (err) {\n if (callback) {\n callback(err);\n } else {\n rej(err);\n }\n } else {\n return (async () => {\n const hasError = result.find(row => (row as PouchWriteError).error);\n let heighestSequenceInner = -1;\n if (!hasError) {\n heighestSequenceInner = await heighestSequencePromise;\n } else {\n changesSub.cancel();\n }\n\n result.forEach(row => {\n usePouchResult.push(row);\n });\n\n /**\n * For calls that came from RxDB,\n * we have to ensure that the events are emitted\n * before the actual call resolves.\n */\n let eventsPromise = PROMISE_RESOLVE_VOID;\n if (!options.isDeeper) {\n const endTime = now();\n const emitData = {\n emitId: runId,\n writeDocs: docs,\n writeOptions: options,\n writeResult: usePouchResult,\n previousDocs: previousDocsInDb,\n startTime,\n endTime\n };\n eventsPromise = eventEmitDataToStorageEvents(\n this,\n '_id',\n emitData\n ).then(events => {\n const eventBulk: EventBulk = {\n id: randomCouchString(10),\n events,\n checkpoint: {\n sequence: heighestSequenceInner\n },\n context: options.custom ? options.custom.context : 'pouchdb-internal'\n };\n\n const emitter = getCustomEventEmitterByPouch(this);\n emitter.subject.next(eventBulk);\n });\n }\n\n if (callback) {\n callback(null, usePouchResult);\n } else {\n return eventsPromise.then(() => {\n res(usePouchResult);\n return usePouchResult;\n });\n }\n })();\n }\n });\n });\n\n if (options.custom) {\n return callPromise;\n }\n\n\n\n return callReturn;\n };\n\n PouchDBCore.plugin({\n bulkDocs: newBulkDocs\n } as any);\n\n}\n\nexport async function eventEmitDataToStorageEvents(\n pouchDBInstance: PouchDBInstance,\n primaryPath: string,\n emitData: EmitData\n): Promise>[]> {\n const ret: RxStorageChangeEvent>[] = [];\n if (\n !emitData.writeOptions.custom &&\n emitData.writeOptions.hasOwnProperty('new_edits') &&\n emitData.writeOptions.new_edits === false\n ) {\n await Promise.all(\n emitData.writeDocs.map(async (writeDoc) => {\n const id = writeDoc._id;\n writeDoc = pouchDocumentDataToRxDocumentData(\n primaryPath,\n writeDoc\n );\n writeDoc._attachments = await writeAttachmentsToAttachments(writeDoc._attachments);\n let previousDoc = emitData.previousDocs.get(id);\n if (previousDoc) {\n previousDoc = pouchDocumentDataToRxDocumentData(\n primaryPath,\n previousDoc\n );\n }\n if (previousDoc) {\n const parsedRevPrevious = parseRevision(previousDoc._rev);\n const parsedRevNew = parseRevision(writeDoc._rev);\n if (\n (\n parsedRevPrevious.height > parsedRevNew.height ||\n /**\n * If the revision height is equal,\n * we determine the higher hash as winner.\n */\n (\n parsedRevPrevious.height === parsedRevNew.height &&\n parsedRevPrevious.hash > parsedRevNew.hash\n )\n )\n ) {\n /**\n * The newly added document was not the latest revision\n * so we drop the write.\n * With plain PouchDB it makes sense to store conflicting branches of the document\n * but RxDB assumes that the conflict is resolved directly.\n */\n return;\n }\n }\n\n if (!previousDoc && writeDoc._deleted) {\n // deleted document was added as revision\n return;\n }\n\n if (previousDoc && previousDoc._deleted && writeDoc._deleted) {\n // delete document was deleted again\n return;\n }\n\n let event: ChangeEvent>;\n if ((!previousDoc || previousDoc._deleted) && !writeDoc._deleted) {\n // was insert\n event = {\n operation: 'INSERT',\n doc: writeDoc,\n id: id,\n previous: null\n };\n } else if (writeDoc._deleted && previousDoc && !previousDoc._deleted) {\n // was delete\n previousDoc._rev = writeDoc._rev;\n event = {\n operation: 'DELETE',\n doc: writeDoc,\n id: id,\n previous: previousDoc\n };\n } else if (\n previousDoc\n ) {\n // was update\n event = {\n operation: 'UPDATE',\n doc: writeDoc,\n id: id,\n previous: previousDoc\n };\n } else {\n throw newRxError('SNH', { args: { writeDoc } });\n }\n\n const changeEvent = changeEventToNormal(\n pouchDBInstance,\n primaryPath,\n event,\n emitData.startTime,\n emitData.endTime\n );\n\n ret.push(changeEvent);\n })\n );\n // eslint-disable-next-line brace-style\n }\n\n /**\n * There is no write map given for internal pouchdb document writes\n * like it is done with replication.\n */\n else if (\n !emitData.writeOptions.custom ||\n (emitData.writeOptions.custom && !emitData.writeOptions.custom.writeRowById)\n ) {\n const writeDocsById: Map = new Map();\n emitData.writeDocs.forEach(writeDoc => writeDocsById.set(writeDoc._id, writeDoc));\n await Promise.all(\n emitData.writeResult.map(async (resultRow) => {\n const id = resultRow.id;\n if (\n id.startsWith(POUCHDB_DESIGN_PREFIX) ||\n id.startsWith(POUCHDB_LOCAL_PREFIX)\n ) {\n return;\n }\n let writeDoc = getFromMapOrThrow(writeDocsById, resultRow.id);\n writeDoc = pouchDocumentDataToRxDocumentData(\n primaryPath,\n writeDoc\n );\n\n writeDoc._attachments = await writeAttachmentsToAttachments(writeDoc._attachments);\n writeDoc = flatClone(writeDoc);\n writeDoc._rev = (resultRow as any).rev;\n const event = pouchChangeRowToChangeEvent(\n primaryPath as any,\n writeDoc\n );\n const changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event);\n ret.push(changeEvent);\n })\n );\n } else {\n const writeMap: Map> = emitData.writeOptions.custom.writeRowById;\n await Promise.all(\n emitData.writeResult.map(async (resultRow) => {\n if ((resultRow as PouchWriteError).error) {\n return;\n }\n const id = resultRow.id;\n const writeRow = getFromMapOrThrow(writeMap, id);\n const attachments = await writeAttachmentsToAttachments(writeRow.document._attachments);\n const newDoc: RxDocumentData = Object.assign(\n {},\n writeRow.document,\n {\n _attachments: attachments,\n _rev: (resultRow as PouchBulkDocResultRow).rev\n }\n );\n\n let event: ChangeEvent>;\n if (!writeRow.previous || writeRow.previous._deleted) {\n // was insert\n event = {\n operation: 'INSERT',\n doc: newDoc,\n id: id,\n previous: null\n };\n } else if (writeRow.document._deleted) {\n // was delete\n\n // we need to add the new revision to the previous doc\n // so that the eventkey is calculated correctly.\n // Is this a hack? idk.\n const attachmentsInner = await writeAttachmentsToAttachments(writeRow.previous._attachments);\n const previousDoc = Object.assign(\n {},\n writeRow.previous,\n {\n _attachments: attachmentsInner\n }\n );\n\n event = {\n operation: 'DELETE',\n doc: writeRow.document,\n id: resultRow.id,\n previous: previousDoc\n } as any;\n } else {\n // was update\n event = {\n operation: 'UPDATE',\n doc: newDoc,\n id: resultRow.id,\n previous: writeRow.previous\n };\n }\n\n if (\n writeRow.document._deleted &&\n (\n !writeRow.previous ||\n writeRow.previous._deleted\n )\n ) {\n /**\n * A deleted document was newly added to the storage engine,\n * do not emit an event.\n */\n } else {\n const changeEvent = changeEventToNormal(\n pouchDBInstance,\n ensureNotFalsy(emitData.writeOptions.custom).primaryPath,\n event,\n emitData.startTime,\n emitData.endTime\n );\n ret.push(changeEvent);\n }\n })\n );\n }\n\n return ret;\n}\n\nexport function changeEventToNormal(\n pouchDBInstance: PouchDBInstance,\n primaryPath: string,\n change: ChangeEvent>,\n startTime?: number,\n endTime?: number\n): RxStorageChangeEvent> {\n const doc: RxDocumentData = change.operation === 'DELETE' ? change.previous as any : change.doc as any;\n const primary: string = (doc as any)[primaryPath];\n const storageChangeEvent: RxStorageChangeEvent> = {\n eventId: getEventKey(pouchDBInstance, primary, change),\n documentId: primary,\n documentData: change.doc as any,\n previousDocumentData: change.previous as any,\n operation: change.operation,\n startTime,\n endTime\n };\n return storageChangeEvent;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAcA,OAAOA,WAAW,MAAM,cAAc;AACtC,SAASC,OAAO,QAAQ,MAAM;AAC9B,SACIC,cAAc,EACdC,SAAS,EACTC,iBAAiB,EACjBC,GAAG,EACHC,aAAa,EACbC,oBAAoB,EACpBC,iBAAiB,QACd,YAAY;AACnB,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SACIC,WAAW,EACXC,2BAA2B,EAC3BC,qBAAqB,EACrBC,oBAAoB,EACpBC,iCAAiC,EACjCC,6BAA6B,QAC1B,kBAAkB;AAqdzB,WAAsBC,4BAA4B,YAA5BA,4BAA4B,CAC9CC,eAAgC,EAChCC,WAAmB,EACnBC,QAAkB;EAAA,IACwC;IAC1D,IAAMC,GAAsD,GAAG,EAAE;IAAC;MAAA,IAE9D,CAACD,QAAQ,CAACE,YAAY,CAACC,MAAM,IAC7BH,QAAQ,CAACE,YAAY,CAACE,cAAc,CAAC,WAAW,CAAC,IACjDJ,QAAQ,CAACE,YAAY,CAACG,SAAS,KAAK,KAAK;QAAA,uBAEnCC,OAAO,CAACC,GAAG,CACbP,QAAQ,CAACQ,SAAS,CAACC,GAAG,WAAQC,QAAQ;UAAA,IAAK;YACvC,IAAMC,E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C/B/B,eAAgC,EAChCC,WAAmB,EACnB2H,MAA8C,EAC9C5F,SAAkB,EAClBC,OAAgB,EAC+B;EAC/C,IAAMN,GAA8B,GAAGiG,MAAM,CAAClG,SAAS,KAAK,QAAQ,GAAGkG,MAAM,CAAChG,QAAQ,GAAUgG,MAAM,CAACjG,GAAU;EACjH,IAAMyI,OAAe,GAAIzI,GAAG,CAAS1B,WAAW,CAAC;EACjD,IAAMoK,kBAAmE,GAAG;IACxEC,OAAO,EAAE7K,WAAW,CAACO,eAAe,EAAEoK,OAAO,EAAExC,MAAM,CAAC;IACtD2C,UAAU,EAAEH,OAAO;IACnBI,YAAY,EAAE5C,MAAM,CAACjG,GAAU;IAC/B8I,oBAAoB,EAAE7C,MAAM,CAAChG,QAAe;IAC5CF,SAAS,EAAEkG,MAAM,CAAClG,SAAS;IAC3BM,SAAS,EAATA,SAAS;IACTC,OAAO,EAAPA;EACJ,CAAC;EACD,OAAOoI,kBAAkB;AAC7B"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/index.js b/dist/es/plugins/pouchdb/index.js deleted file mode 100644 index 234908af23e..00000000000 --- a/dist/es/plugins/pouchdb/index.js +++ /dev/null @@ -1,10 +0,0 @@ -export * from './pouch-db'; -export * from './rx-storage-pouchdb'; -export * from './adapter-check'; -export * from './custom-events-plugin'; -export * from './pouchdb-helper'; -export * from './pouch-statics'; -export * from './rx-storage-instance-pouch'; -export {}; -export {}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/index.js.map b/dist/es/plugins/pouchdb/index.js.map deleted file mode 100644 index 592c96b71c0..00000000000 --- a/dist/es/plugins/pouchdb/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/pouchdb/index.ts"],"sourcesContent":["export * from './pouch-db';\nexport * from './rx-storage-pouchdb';\nexport * from './adapter-check';\nexport * from './custom-events-plugin';\nexport * from './pouchdb-helper';\nexport * from './pouch-statics';\nexport * from './rx-storage-instance-pouch';\n\nexport type {\n PouchDBInstance,\n PouchReplicationOptions,\n PouchSettings,\n PouchSyncHandler,\n PouchSyncHandlerEvents,\n PouchdbQuery,\n} from '../../types/pouch';\n"],"mappings":"AAAA,cAAc,YAAY;AAC1B,cAAc,sBAAsB;AACpC,cAAc,iBAAiB;AAC/B,cAAc,wBAAwB;AACtC,cAAc,kBAAkB;AAChC,cAAc,iBAAiB;AAC/B,cAAc,6BAA6B;AAAC;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouch-db.js b/dist/es/plugins/pouchdb/pouch-db.js deleted file mode 100644 index 5371b3f1def..00000000000 --- a/dist/es/plugins/pouchdb/pouch-db.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * this handles the pouchdb-instance - * to easy add modules and manipulate things - * Adapters can be found here: - * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules - */ -import PouchDBCore from 'pouchdb-core'; - -/* -// comment in to debug -const pouchdbDebug = require('pouchdb-debug'); -PouchDB.plugin(pouchdbDebug); -PouchDB.debug.enable('*'); -*/ - -import { newRxError, newRxTypeError } from '../../rx-error'; - -/** - * check if the given module is a leveldown-adapter - * throws if not - */ -export function isLevelDown(adapter) { - if (!adapter || typeof adapter.super_ !== 'function') { - throw newRxError('UT4', { - adapter: adapter - }); - } -} -export function isInstanceOf(obj) { - return obj instanceof PouchDBCore; -} - -/** - * Adding a PouchDB plugin multiple times, - * can sometimes error. So we have to check if the plugin - * was added before. - */ -var ADDED_POUCH_PLUGINS = new Set(); - -/** - * Add a pouchdb plugin to the pouchdb library. - * @deprecated PouchDB RxStorage is deprecated, see - * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated - */ -export function addPouchPlugin(plugin) { - if (plugin.rxdb) { - throw newRxTypeError('PL2', { - plugin: plugin - }); - } - /** - * Pouchdb has confusing typings and modules. - * So we monkeypatch the plugin to use the default property - * when it was imported or packaged this way. - */ - if (typeof plugin === 'object' && plugin["default"]) { - plugin = plugin["default"]; - } - if (!ADDED_POUCH_PLUGINS.has(plugin)) { - ADDED_POUCH_PLUGINS.add(plugin); - PouchDBCore.plugin(plugin); - } -} -export var PouchDB = PouchDBCore; -//# sourceMappingURL=pouch-db.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouch-db.js.map b/dist/es/plugins/pouchdb/pouch-db.js.map deleted file mode 100644 index 933280b368a..00000000000 --- a/dist/es/plugins/pouchdb/pouch-db.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouch-db.js","names":["PouchDBCore","newRxError","newRxTypeError","isLevelDown","adapter","super_","isInstanceOf","obj","ADDED_POUCH_PLUGINS","Set","addPouchPlugin","plugin","rxdb","has","add","PouchDB"],"sources":["../../../../src/plugins/pouchdb/pouch-db.ts"],"sourcesContent":["/**\n * this handles the pouchdb-instance\n * to easy add modules and manipulate things\n * Adapters can be found here:\n * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules\n */\nimport PouchDBCore from 'pouchdb-core';\n\n/*\n// comment in to debug\nconst pouchdbDebug = require('pouchdb-debug');\nPouchDB.plugin(pouchdbDebug);\nPouchDB.debug.enable('*');\n*/\n\n\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error';\n\n\n/**\n * check if the given module is a leveldown-adapter\n * throws if not\n */\nexport function isLevelDown(adapter: any) {\n if (!adapter || typeof adapter.super_ !== 'function') {\n throw newRxError('UT4', {\n adapter\n });\n }\n}\n\nexport function isInstanceOf(obj: any) {\n return obj instanceof PouchDBCore;\n}\n\n/**\n * Adding a PouchDB plugin multiple times,\n * can sometimes error. So we have to check if the plugin\n * was added before.\n */\nconst ADDED_POUCH_PLUGINS: Set = new Set();\n\n/**\n * Add a pouchdb plugin to the pouchdb library.\n * @deprecated PouchDB RxStorage is deprecated, see\n * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated\n */\nexport function addPouchPlugin(plugin: any) {\n if (plugin.rxdb) {\n throw newRxTypeError('PL2', {\n plugin\n });\n }\n /**\n * Pouchdb has confusing typings and modules.\n * So we monkeypatch the plugin to use the default property\n * when it was imported or packaged this way.\n */\n if (typeof plugin === 'object' && plugin.default) {\n plugin = plugin.default;\n }\n\n if (!ADDED_POUCH_PLUGINS.has(plugin)) {\n ADDED_POUCH_PLUGINS.add(plugin);\n PouchDBCore.plugin(plugin);\n }\n}\n\n\nexport const PouchDB: any = PouchDBCore as any;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,WAAW,MAAM,cAAc;;AAEtC;AACA;AACA;AACA;AACA;AACA;;AAGA,SACIC,UAAU,EACVC,cAAc,QACX,gBAAgB;;AAGvB;AACA;AACA;AACA;AACA,OAAO,SAASC,WAAW,CAACC,OAAY,EAAE;EACtC,IAAI,CAACA,OAAO,IAAI,OAAOA,OAAO,CAACC,MAAM,KAAK,UAAU,EAAE;IAClD,MAAMJ,UAAU,CAAC,KAAK,EAAE;MACpBG,OAAO,EAAPA;IACJ,CAAC,CAAC;EACN;AACJ;AAEA,OAAO,SAASE,YAAY,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYP,WAAW;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAMQ,mBAA6B,GAAG,IAAIC,GAAG,EAAE;;AAE/C;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,cAAc,CAACC,MAAW,EAAE;EACxC,IAAIA,MAAM,CAACC,IAAI,EAAE;IACb,MAAMV,cAAc,CAAC,KAAK,EAAE;MACxBS,MAAM,EAANA;IACJ,CAAC,CAAC;EACN;EACA;AACJ;AACA;AACA;AACA;EACI,IAAI,OAAOA,MAAM,KAAK,QAAQ,IAAIA,MAAM,WAAQ,EAAE;IAC9CA,MAAM,GAAGA,MAAM,WAAQ;EAC3B;EAEA,IAAI,CAACH,mBAAmB,CAACK,GAAG,CAACF,MAAM,CAAC,EAAE;IAClCH,mBAAmB,CAACM,GAAG,CAACH,MAAM,CAAC;IAC/BX,WAAW,CAACW,MAAM,CAACA,MAAM,CAAC;EAC9B;AACJ;AAGA,OAAO,IAAMI,OAAY,GAAGf,WAAkB"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouch-statics.js b/dist/es/plugins/pouchdb/pouch-statics.js deleted file mode 100644 index 31244fd05f2..00000000000 --- a/dist/es/plugins/pouchdb/pouch-statics.js +++ /dev/null @@ -1,209 +0,0 @@ -import { filterInMemoryFields, massageSelector } from 'pouchdb-selector-core'; -import { newRxError } from '../../rx-error'; -import { getPouchIndexDesignDocNameByIndex, POUCHDB_CHECKPOINT_SCHEMA, pouchSwapPrimaryToId, primarySwapPouchDbQuerySelector } from './pouchdb-helper'; -import { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper'; -import { overwritable } from '../../overwritable'; -import { ensureNotFalsy, flatClone, isMaybeReadonlyArray } from '../../util'; -export var RxStoragePouchStatics = { - getSortComparator: function getSortComparator(schema, query) { - var _ref; - var primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey); - var sortOptions = query.sort ? query.sort : [(_ref = {}, _ref[primaryPath] = 'asc', _ref)]; - var selector = query.selector ? query.selector : {}; - var inMemoryFields = Object.keys(selector).filter(function (key) { - return !key.startsWith('$'); - }); - var fun = function fun(a, b) { - /** - * Sorting on two documents with the same primary is not allowed - * because it might end up in a non-deterministic result. - */ - if (a[primaryPath] === b[primaryPath]) { - throw newRxError('SNH', { - args: { - a: a, - b: b - }, - primaryPath: primaryPath - }); - } - - // TODO use createFieldSorter - // TODO make a performance test - var rows = [a, b].map(function (doc) { - return { - doc: pouchSwapPrimaryToId(primaryPath, doc) - }; - }); - var sortedRows = filterInMemoryFields(rows, { - selector: {}, - sort: sortOptions - }, inMemoryFields); - if (sortedRows.length !== 2) { - throw newRxError('SNH', { - query: query, - primaryPath: primaryPath, - args: { - rows: rows, - sortedRows: sortedRows - } - }); - } - if (sortedRows[0].doc._id === rows[0].doc._id) { - return -1; - } else { - return 1; - } - }; - return fun; - }, - /** - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ - getQueryMatcher: function getQueryMatcher(schema, query) { - var primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey); - var selector = query.selector ? query.selector : {}; - var massagedSelector = massageSelector(selector); - var fun = function fun(doc) { - if (doc._deleted) { - return false; - } - var cloned = pouchSwapPrimaryToId(primaryPath, doc); - var row = { - doc: cloned - }; - var rowsMatched = filterInMemoryFields([row], { - selector: massagedSelector - }, Object.keys(selector)); - var ret = rowsMatched && rowsMatched.length === 1; - return ret; - }; - return fun; - }, - /** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ - prepareQuery: function prepareQuery(schema, mutateableQuery) { - return preparePouchDbQuery(schema, mutateableQuery); - }, - checkpointSchema: POUCHDB_CHECKPOINT_SCHEMA -}; - -/** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ -export function preparePouchDbQuery(schema, mutateableQuery) { - var primaryKey = getPrimaryFieldOfPrimaryKey(schema.primaryKey); - var query = flatClone(mutateableQuery); - if (query.selector) { - query.selector = flatClone(query.selector); - } - - /** - * because sort won't work on unused keys we have to workaround - * so we add the key to the selector if necessary - * @link https://github.com/nolanlawson/pouchdb-find/issues/204 - */ - if (query.sort) { - query.sort.forEach(function (sortPart) { - var key = Object.keys(sortPart)[0]; - var comparisonOperators = ['$gt', '$gte', '$lt', '$lte', '$eq']; - var keyUsed = query.selector && query.selector[key] && Object.keys(query.selector[key]).some(function (op) { - return comparisonOperators.includes(op); - }); - if (!keyUsed) { - var schemaObj = getSchemaByObjectPath(schema, key); - if (!schemaObj) { - throw newRxError('QU5', { - query: query, - key: key, - schema: schema - }); - } - if (!query.selector) { - query.selector = {}; - } - if (!query.selector[key]) { - query.selector[key] = {}; - } - switch (schemaObj.type) { - case 'number': - case 'integer': - // TODO change back to -Infinity when issue resolved - // @link https://github.com/pouchdb/pouchdb/issues/6454 - // -Infinity does not work since pouchdb 6.2.0 - query.selector[key].$gt = -9999999999999999999999999999; - break; - case 'string': - /** - * strings need an empty string, see - * @link https://github.com/pubkey/rxdb/issues/585 - */ - if (typeof query.selector[key] !== 'string') { - query.selector[key].$gt = ''; - } - break; - default: - query.selector[key].$gt = null; - break; - } - } - }); - } - - // regex does not work over the primary key - if (overwritable.isDevMode() && query.selector && query.selector[primaryKey] && query.selector[primaryKey].$regex) { - throw newRxError('QU4', { - path: primaryKey, - query: mutateableQuery - }); - } - - // primary-swap sorting - if (query.sort) { - var sortArray = query.sort.map(function (part) { - var _newPart; - var key = Object.keys(part)[0]; - var direction = Object.values(part)[0]; - var useKey = key === primaryKey ? '_id' : key; - var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); - return newPart; - }); - query.sort = sortArray; - } - - // strip empty selectors - Object.entries(ensureNotFalsy(query.selector)).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { - delete ensureNotFalsy(query.selector)[k]; - } - }); - - /** - * Set use_index - * @link https://pouchdb.com/guides/mango-queries.html#use_index - */ - if (mutateableQuery.index) { - var indexMaybeArray = mutateableQuery.index; - var indexArray = isMaybeReadonlyArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; - indexArray = indexArray.map(function (str) { - if (str === primaryKey) { - return '_id'; - } else { - return str; - } - }); - var indexName = getPouchIndexDesignDocNameByIndex(indexArray); - delete query.index; - query.use_index = indexName; - } - query.selector = primarySwapPouchDbQuerySelector(query.selector, primaryKey); - return query; -} -//# sourceMappingURL=pouch-statics.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouch-statics.js.map b/dist/es/plugins/pouchdb/pouch-statics.js.map deleted file mode 100644 index 745102faffe..00000000000 --- a/dist/es/plugins/pouchdb/pouch-statics.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouch-statics.js","names":["filterInMemoryFields","massageSelector","newRxError","getPouchIndexDesignDocNameByIndex","POUCHDB_CHECKPOINT_SCHEMA","pouchSwapPrimaryToId","primarySwapPouchDbQuerySelector","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","overwritable","ensureNotFalsy","flatClone","isMaybeReadonlyArray","RxStoragePouchStatics","getSortComparator","schema","query","primaryPath","primaryKey","sortOptions","sort","selector","inMemoryFields","Object","keys","filter","key","startsWith","fun","a","b","args","rows","map","doc","sortedRows","length","_id","getQueryMatcher","massagedSelector","_deleted","cloned","row","rowsMatched","ret","prepareQuery","mutateableQuery","preparePouchDbQuery","checkpointSchema","forEach","sortPart","comparisonOperators","keyUsed","some","op","includes","schemaObj","type","$gt","isDevMode","$regex","path","sortArray","part","direction","values","useKey","newPart","entries","k","v","Array","isArray","index","indexMaybeArray","indexArray","str","indexName","use_index"],"sources":["../../../../src/plugins/pouchdb/pouch-statics.ts"],"sourcesContent":["import {\n filterInMemoryFields,\n massageSelector\n} from 'pouchdb-selector-core';\nimport { newRxError } from '../../rx-error';\n\nimport {\n getPouchIndexDesignDocNameByIndex,\n POUCHDB_CHECKPOINT_SCHEMA,\n pouchSwapPrimaryToId,\n primarySwapPouchDbQuerySelector\n} from './pouchdb-helper';\nimport type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport {\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath\n} from '../../rx-schema-helper';\nimport type {\n MangoQuery,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n PreparedQuery,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageStatics,\n StringKeys\n} from '../../types';\nimport { overwritable } from '../../overwritable';\nimport { ensureNotFalsy, flatClone, isMaybeReadonlyArray } from '../../util';\n\nexport const RxStoragePouchStatics: RxStorageStatics = {\n getSortComparator(\n schema: RxJsonSchema>,\n query: MangoQuery\n ): DeterministicSortComparator {\n const primaryPath: StringKeys = getPrimaryFieldOfPrimaryKey(schema.primaryKey) as any;\n const sortOptions: MangoQuerySortPart[] = query.sort ? (query.sort as any) : [{\n [primaryPath]: 'asc'\n }];\n const selector = query.selector ? query.selector : {};\n const inMemoryFields = Object\n .keys(selector)\n .filter(key => !key.startsWith('$'));\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n /**\n * Sorting on two documents with the same primary is not allowed\n * because it might end up in a non-deterministic result.\n */\n if (a[primaryPath] === b[primaryPath]) {\n throw newRxError('SNH', { args: { a, b }, primaryPath: primaryPath as any });\n }\n\n // TODO use createFieldSorter\n // TODO make a performance test\n const rows = [a, b].map(doc => ({\n doc: pouchSwapPrimaryToId(primaryPath, doc)\n }));\n const sortedRows: { doc: any; }[] = filterInMemoryFields(\n rows,\n {\n selector: {},\n sort: sortOptions\n },\n inMemoryFields\n );\n if (sortedRows.length !== 2) {\n throw newRxError('SNH', {\n query,\n primaryPath: primaryPath as any,\n args: {\n rows,\n sortedRows\n }\n });\n }\n if (sortedRows[0].doc._id === rows[0].doc._id) {\n return -1;\n } else {\n return 1;\n }\n };\n return fun;\n },\n\n /**\n * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js\n */\n getQueryMatcher(\n schema: RxJsonSchema,\n query: MangoQuery\n ): QueryMatcher> {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const selector = query.selector ? query.selector : {};\n const massagedSelector = massageSelector(selector);\n const fun: QueryMatcher> = (doc: RxDocumentWriteData) => {\n if (doc._deleted) {\n return false;\n }\n const cloned = pouchSwapPrimaryToId(primaryPath, doc);\n const row = {\n doc: cloned\n };\n const rowsMatched = filterInMemoryFields(\n [row],\n { selector: massagedSelector },\n Object.keys(selector)\n );\n const ret = rowsMatched && rowsMatched.length === 1;\n return ret;\n };\n return fun;\n },\n\n\n /**\n * pouchdb has many bugs and strange behaviors\n * this functions takes a normal mango query\n * and transforms it to one that fits for pouchdb\n */\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: MangoQuery\n ): PreparedQuery {\n return preparePouchDbQuery(\n schema,\n mutateableQuery\n );\n },\n checkpointSchema: POUCHDB_CHECKPOINT_SCHEMA\n};\n\n/**\n * pouchdb has many bugs and strange behaviors\n * this functions takes a normal mango query\n * and transforms it to one that fits for pouchdb\n */\nexport function preparePouchDbQuery(\n schema: RxJsonSchema>,\n mutateableQuery: MangoQuery\n): PreparedQuery {\n const primaryKey = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const query = flatClone(mutateableQuery);\n if (query.selector) {\n query.selector = flatClone(query.selector);\n }\n\n /**\n * because sort won't work on unused keys we have to workaround\n * so we add the key to the selector if necessary\n * @link https://github.com/nolanlawson/pouchdb-find/issues/204\n */\n if (query.sort) {\n query.sort.forEach(sortPart => {\n const key = Object.keys(sortPart)[0];\n const comparisonOperators = ['$gt', '$gte', '$lt', '$lte', '$eq'];\n const keyUsed = query.selector && query.selector[key] && Object.keys(query.selector[key]).some(op => comparisonOperators.includes(op));\n\n if (!keyUsed) {\n const schemaObj = getSchemaByObjectPath(schema, key);\n if (!schemaObj) {\n throw newRxError('QU5', {\n query,\n key,\n schema\n });\n }\n if (!query.selector) {\n query.selector = {};\n }\n if (!query.selector[key]) {\n query.selector[key] = {};\n }\n switch (schemaObj.type) {\n case 'number':\n case 'integer':\n // TODO change back to -Infinity when issue resolved\n // @link https://github.com/pouchdb/pouchdb/issues/6454\n // -Infinity does not work since pouchdb 6.2.0\n query.selector[key].$gt = -9999999999999999999999999999;\n break;\n case 'string':\n /**\n * strings need an empty string, see\n * @link https://github.com/pubkey/rxdb/issues/585\n */\n if (typeof query.selector[key] !== 'string') {\n query.selector[key].$gt = '';\n }\n break;\n default:\n query.selector[key].$gt = null;\n break;\n }\n }\n });\n }\n\n // regex does not work over the primary key\n if (\n overwritable.isDevMode() &&\n query.selector &&\n query.selector[primaryKey as any] &&\n query.selector[primaryKey as any].$regex\n ) {\n throw newRxError('QU4', {\n path: primaryKey as any,\n query: mutateableQuery\n });\n }\n\n // primary-swap sorting\n if (query.sort) {\n const sortArray: MangoQuerySortPart[] = query.sort.map(part => {\n const key = Object.keys(part)[0];\n const direction: MangoQuerySortDirection = Object.values(part)[0];\n const useKey = key === primaryKey ? '_id' : key;\n const newPart = { [useKey]: direction };\n return newPart as any;\n });\n query.sort = sortArray;\n }\n\n // strip empty selectors\n Object.entries(ensureNotFalsy(query.selector)).forEach(([k, v]) => {\n if (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys((v as any)).length === 0\n ) {\n delete ensureNotFalsy(query.selector)[k];\n }\n });\n\n /**\n * Set use_index\n * @link https://pouchdb.com/guides/mango-queries.html#use_index\n */\n if (mutateableQuery.index) {\n const indexMaybeArray = mutateableQuery.index;\n let indexArray: string[] = isMaybeReadonlyArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray];\n indexArray = indexArray.map(str => {\n if (str === primaryKey) {\n return '_id';\n } else {\n return str;\n }\n });\n const indexName = getPouchIndexDesignDocNameByIndex(indexArray);\n delete query.index;\n (query as any).use_index = indexName;\n }\n\n query.selector = primarySwapPouchDbQuerySelector(query.selector, primaryKey);\n\n return query;\n}\n"],"mappings":"AAAA,SACIA,oBAAoB,EACpBC,eAAe,QACZ,uBAAuB;AAC9B,SAASC,UAAU,QAAQ,gBAAgB;AAE3C,SACIC,iCAAiC,EACjCC,yBAAyB,EACzBC,oBAAoB,EACpBC,+BAA+B,QAC5B,kBAAkB;AAKzB,SACIC,2BAA2B,EAC3BC,qBAAqB,QAClB,wBAAwB;AAY/B,SAASC,YAAY,QAAQ,oBAAoB;AACjD,SAASC,cAAc,EAAEC,SAAS,EAAEC,oBAAoB,QAAQ,YAAY;AAE5E,OAAO,IAAMC,qBAAuC,GAAG;EACnDC,iBAAiB,6BACbC,MAA+C,EA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D,KAAK;IACjBzD,KAAK,CAAS8D,SAAS,GAAGD,SAAS;EACxC;EAEA7D,KAAK,CAACK,QAAQ,GAAGf,+BAA+B,CAACU,KAAK,CAACK,QAAQ,EAAEH,UAAU,CAAC;EAE5E,OAAOF,KAAK;AAChB"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouchdb-helper.js b/dist/es/plugins/pouchdb/pouchdb-helper.js deleted file mode 100644 index f577e4735cc..00000000000 --- a/dist/es/plugins/pouchdb/pouchdb-helper.js +++ /dev/null @@ -1,356 +0,0 @@ -import { binaryMd5 } from 'pouchdb-md5'; -import { blobBufferUtil, flatClone, getHeightOfRevision } from '../../util'; -import { newRxError } from '../../rx-error'; -import { getAttachmentSize } from '../../rx-storage-helper'; -export var writeAttachmentsToAttachments = function writeAttachmentsToAttachments(attachments) { - try { - if (!attachments) { - return Promise.resolve({}); - } - var ret = {}; - return Promise.resolve(Promise.all(Object.entries(attachments).map(function (_ref4) { - try { - var key = _ref4[0], - obj = _ref4[1]; - if (!obj.type) { - throw newRxError('SNH', { - args: { - obj: obj - } - }); - } - /** - * Is write attachment, - * so we have to remove the data to have a - * non-write attachment. - */ - var _temp3 = function () { - if (obj.data) { - var _temp2 = function _temp2(dataAsBase64String) { - return Promise.resolve(hashAttachmentData(dataAsBase64String)).then(function (hash) { - var length = getAttachmentSize(dataAsBase64String); - ret[key] = { - digest: 'md5-' + hash, - length: length, - type: _asWrite.type - }; - }); - }; - var _asWrite = obj; - var data = _asWrite.data; - var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(data); - if (isBuffer) { - data = new Blob([data]); - } - var _temp = typeof data === 'string'; - return _temp ? _temp2(data) : Promise.resolve(blobBufferUtil.toBase64String(data)).then(_temp2); - } else { - ret[key] = obj; - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var RX_STORAGE_NAME_POUCHDB = 'pouchdb'; - -/** - * Used to check in tests if all instances have been cleaned up. - */ -export var OPEN_POUCHDB_STORAGE_INSTANCES = new Set(); - -/** - * All open PouchDB instances are stored here - * so that we can find them again when needed in the internals. - */ -export var OPEN_POUCH_INSTANCES = new Map(); -export function openPouchId(databaseInstanceToken, databaseName, collectionName, schemaVersion) { - return [databaseInstanceToken, databaseName, collectionName, schemaVersion + ''].join('||'); -} - -/** - * prefix of local pouchdb documents - */ -export var POUCHDB_LOCAL_PREFIX = '_local/'; -export var POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX.length; - -/** - * Pouchdb stores indexes as design documents, - * we have to filter them out and not return the - * design documents to the outside. - */ -export var POUCHDB_DESIGN_PREFIX = '_design/'; - -/** - * PouchDB does not allow to add custom properties - * that start with lodash like RxDB's _meta field. - * So we have to map this field into a non-lodashed field. - */ -export var POUCHDB_META_FIELDNAME = 'rxdbMeta'; -export function pouchSwapIdToPrimary(primaryKey, docData) { - if (primaryKey === '_id' || docData[primaryKey]) { - return docData; - } - docData = flatClone(docData); - docData[primaryKey] = docData._id; - delete docData._id; - return docData; -} -export function pouchSwapIdToPrimaryString(primaryKey, str) { - if (str === '_id') { - return primaryKey; - } else { - return str; - } -} -export function pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc) { - var useDoc = pouchSwapIdToPrimary(primaryKey, pouchDoc); - - // always flat clone because we mutate the _attachments property. - useDoc = flatClone(useDoc); - delete useDoc._revisions; - - // ensure deleted flag is set. - useDoc._deleted = !!useDoc._deleted; - useDoc._attachments = {}; - if (pouchDoc._attachments) { - Object.entries(pouchDoc._attachments).forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; - if (value.data) { - useDoc._attachments[key] = { - data: value.data, - type: value.type ? value.type : value.content_type - }; - } else { - useDoc._attachments[key] = { - digest: value.digest, - // TODO why do we need to access value.type? - type: value.type ? value.type : value.content_type, - length: value.length - }; - } - }); - } - useDoc._meta = useDoc[POUCHDB_META_FIELDNAME]; - delete useDoc[POUCHDB_META_FIELDNAME]; - return useDoc; -} -export function rxDocumentDataToPouchDocumentData(primaryKey, doc) { - var pouchDoc = pouchSwapPrimaryToId(primaryKey, doc); - - // always flat clone because we mutate the _attachments property. - pouchDoc = flatClone(pouchDoc); - pouchDoc._attachments = {}; - if (doc._attachments) { - Object.entries(doc._attachments).forEach(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; - var useValue = value; - if (useValue.data) { - pouchDoc._attachments[key] = { - data: useValue.data, - content_type: useValue.type - }; - } else { - pouchDoc._attachments[key] = { - digest: useValue.digest, - content_type: useValue.type, - length: useValue.length, - stub: true - }; - } - }); - } - pouchDoc[POUCHDB_META_FIELDNAME] = pouchDoc._meta; - delete pouchDoc._meta; - return pouchDoc; -} - -/** - * Swaps the primaryKey of the document - * to the _id property. - */ -export function pouchSwapPrimaryToId(primaryKey, docData) { - // optimisation shortcut - if (primaryKey === '_id') { - return docData; - } - var idValue = docData[primaryKey]; - var ret = flatClone(docData); - delete ret[primaryKey]; - ret._id = idValue; - return ret; -} - -/** - * in: '_local/foobar' - * out: 'foobar' - */ -export function pouchStripLocalFlagFromPrimary(str) { - return str.substring(POUCHDB_LOCAL_PREFIX.length); -} -export function getEventKey(pouchDBInstance, primary, change) { - var useRev = change.doc ? change.doc._rev : change.previous._rev; - var eventKey = pouchDBInstance.name + '|' + primary + '|' + change.operation + '|' + useRev; - return eventKey; -} -export function pouchChangeRowToChangeEvent(primaryKey, pouchDoc) { - if (!pouchDoc) { - throw newRxError('SNH', { - args: { - pouchDoc: pouchDoc - } - }); - } - var id = pouchDoc._id; - var doc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); - var revHeight = doc._rev ? getHeightOfRevision(doc._rev) : 1; - if (pouchDoc._deleted) { - return { - operation: 'DELETE', - id: id, - doc: null, - previous: doc - }; - } else if (revHeight === 1) { - return { - operation: 'INSERT', - id: id, - doc: doc, - previous: null - }; - } else { - return { - operation: 'UPDATE', - id: id, - doc: doc, - previous: 'UNKNOWN' - }; - } -} -export function pouchChangeRowToChangeStreamEvent(primaryKey, pouchRow) { - var doc = pouchRow.doc; - if (!doc) { - throw newRxError('SNH', { - args: { - pouchRow: pouchRow - } - }); - } - var revHeight = getHeightOfRevision(doc._rev); - if (pouchRow.deleted) { - var previousDoc = flatClone(pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc)); - var ev = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'DELETE', - doc: null, - previous: previousDoc - }; - return ev; - } else if (revHeight === 1) { - var _ev = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'INSERT', - doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), - previous: null - }; - return _ev; - } else { - var _ev2 = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'UPDATE', - doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), - previous: 'UNKNOWN' - }; - return _ev2; - } -} - -/** - * Runs a primary swap with transform all custom primaryKey occurrences - * into '_id' - * @recursive - */ -export function primarySwapPouchDbQuerySelector(selector, primaryKey) { - if (primaryKey === '_id') { - return selector; - } - if (Array.isArray(selector)) { - return selector.map(function (item) { - return primarySwapPouchDbQuerySelector(item, primaryKey); - }); - } else if (typeof selector === 'object') { - var ret = {}; - Object.entries(selector).forEach(function (_ref3) { - var k = _ref3[0], - v = _ref3[1]; - if (k === primaryKey) { - ret._id = v; - } else { - if (k.startsWith('$')) { - ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); - } else { - ret[k] = v; - } - } - }); - return ret; - } else { - return selector; - } -} -export function pouchHash(data) { - return new Promise(function (res) { - binaryMd5(data, function (digest) { - res(digest); - }); - }); -} - -/** - * Runs the same hashing as PouchDB would do. - * Used to pre-calculated the hashes which is required to emit the correct events. - */ -export function hashAttachmentData(attachmentBase64String) { - var binary; - try { - binary = atob(attachmentBase64String); - } catch (err) { - console.log('hashAttachmentData() could not run b64DecodeUnicode() on ' + attachmentBase64String); - throw err; - } - return pouchHash(binary); -} -export function getPouchIndexDesignDocNameByIndex(index) { - var indexName = 'idx-rxdb-index-' + index.join(','); - return indexName; -} - -/** - * PouchDB has not way to read deleted local documents - * out of the database. - * So instead of deleting them, we set a custom deleted flag. - */ -export var RXDB_POUCH_DELETED_FLAG = 'rxdb-pouch-deleted'; -export var POUCHDB_CHECKPOINT_SCHEMA = { - type: 'object', - properties: { - sequence: { - type: 'number' - } - }, - required: ['sequence'], - additionalProperties: false -}; -//# sourceMappingURL=pouchdb-helper.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/pouchdb-helper.js.map b/dist/es/plugins/pouchdb/pouchdb-helper.js.map deleted file mode 100644 index 8d5f6f6783f..00000000000 --- a/dist/es/plugins/pouchdb/pouchdb-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-helper.js","names":["binaryMd5","blobBufferUtil","flatClone","getHeightOfRevision","newRxError","getAttachmentSize","writeAttachmentsToAttachments","attachments","ret","Promise","all","Object","entries","map","key","obj","type","args","data","dataAsBase64String","hashAttachmentData","hash","length","digest","asWrite","isBuffer","Buffer","Blob","toBase64String","RX_STORAGE_NAME_POUCHDB","OPEN_POUCHDB_STORAGE_INSTANCES","Set","OPEN_POUCH_INSTANCES","Map","openPouchId","databaseInstanceToken","databaseName","collectionName","schemaVersion","join","POUCHDB_LOCAL_PREFIX","POUCHDB_LOCAL_PREFIX_LENGTH","POUCHDB_DESIGN_PREFIX","POUCHDB_META_FIELDNAME","pouchSwapIdToPrimary","primaryKey","docData","_id","pouchSwapIdToPrimaryString","str","pouchDocumentDataToRxDocumentData","pouchDoc","useDoc","_revisions","_deleted","_attachments","forEach","value","content_type","_meta","rxDocumentDataToPouchDocumentData","doc","pouchSwapPrimaryToId","useValue","stub","idValue","pouchStripLocalFlagFromPrimary","substring","getEventKey","pouchDBInstance","primary","change","useRev","_rev","previous","eventKey","name","operation","pouchChangeRowToChangeEvent","id","revHeight","pouchChangeRowToChangeStreamEvent","pouchRow","deleted","previousDoc","ev","sequence","seq","primarySwapPouchDbQuerySelector","selector","Array","isArray","item","k","v","startsWith","pouchHash","res","attachmentBase64String","binary","atob","err","console","log","getPouchIndexDesignDocNameByIndex","index","indexName","RXDB_POUCH_DELETED_FLAG","POUCHDB_CHECKPOINT_SCHEMA","properties","required","additionalProperties"],"sources":["../../../../src/plugins/pouchdb/pouchdb-helper.ts"],"sourcesContent":["import type {\n ChangeStreamEvent,\n DeepReadonly,\n JsonSchema,\n MaybeReadonly,\n PouchChangeRow,\n PouchCheckpoint,\n PouchDBInstance,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocumentData,\n StringKeys,\n WithAttachments\n} from '../../types';\nimport type { RxStorageInstancePouch } from './rx-storage-instance-pouch';\nimport { binaryMd5 } from 'pouchdb-md5';\nimport {\n blobBufferUtil,\n flatClone,\n getHeightOfRevision\n} from '../../util';\nimport { newRxError } from '../../rx-error';\nimport type { ChangeEvent } from 'event-reduce-js';\nimport { getAttachmentSize } from '../../rx-storage-helper';\n\nexport type PouchStorageInternals = {\n pouchInstanceId: string;\n pouch: PouchDBInstance;\n};\n\n\nexport const RX_STORAGE_NAME_POUCHDB = 'pouchdb';\n\n/**\n * Used to check in tests if all instances have been cleaned up.\n */\nexport const OPEN_POUCHDB_STORAGE_INSTANCES: Set> = new Set();\n\n/**\n * All open PouchDB instances are stored here\n * so that we can find them again when needed in the internals.\n */\nexport const OPEN_POUCH_INSTANCES: Map = new Map();\nexport function openPouchId(\n databaseInstanceToken: string,\n databaseName: string,\n collectionName: string,\n schemaVersion: number\n): string {\n return [\n databaseInstanceToken,\n databaseName,\n collectionName,\n schemaVersion + ''\n ].join('||');\n}\n\n\n/**\n * prefix of local pouchdb documents\n */\nexport const POUCHDB_LOCAL_PREFIX: '_local/' = '_local/';\nexport const POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX.length;\n\n/**\n * Pouchdb stores indexes as design documents,\n * we have to filter them out and not return the\n * design documents to the outside.\n */\nexport const POUCHDB_DESIGN_PREFIX: '_design/' = '_design/';\n\n\n/**\n * PouchDB does not allow to add custom properties\n * that start with lodash like RxDB's _meta field.\n * So we have to map this field into a non-lodashed field.\n */\nexport const POUCHDB_META_FIELDNAME = 'rxdbMeta';\n\nexport function pouchSwapIdToPrimary(\n primaryKey: StringKeys>,\n docData: any\n): any {\n\n if (primaryKey === '_id' || docData[primaryKey]) {\n return docData;\n }\n\n docData = flatClone(docData);\n docData[primaryKey] = docData._id;\n delete docData._id;\n\n return docData;\n}\n\nexport function pouchSwapIdToPrimaryString(\n primaryKey: StringKeys>,\n str: keyof T\n): StringKeys> {\n if (str === '_id') {\n return primaryKey;\n } else {\n return str as any;\n }\n}\n\nexport function pouchDocumentDataToRxDocumentData(\n primaryKey: StringKeys>,\n pouchDoc: WithAttachments\n): RxDocumentData {\n let useDoc: RxDocumentData = pouchSwapIdToPrimary(primaryKey, pouchDoc);\n\n // always flat clone because we mutate the _attachments property.\n useDoc = flatClone(useDoc);\n delete (useDoc as any)._revisions;\n\n // ensure deleted flag is set.\n useDoc._deleted = !!useDoc._deleted;\n\n useDoc._attachments = {};\n if (pouchDoc._attachments) {\n Object.entries(pouchDoc._attachments).forEach(([key, value]) => {\n if ((value as any).data) {\n useDoc._attachments[key] = {\n data: (value as any).data,\n type: (value as any).type ? (value as any).type : (value as any).content_type\n } as any;\n } else {\n useDoc._attachments[key] = {\n digest: value.digest,\n // TODO why do we need to access value.type?\n type: (value as any).type ? (value as any).type : value.content_type,\n length: value.length\n };\n }\n });\n }\n\n useDoc._meta = (useDoc as any)[POUCHDB_META_FIELDNAME];\n delete (useDoc as any)[POUCHDB_META_FIELDNAME];\n\n return useDoc;\n}\n\nexport function rxDocumentDataToPouchDocumentData(\n primaryKey: StringKeys>,\n doc: RxDocumentData | RxDocumentWriteData\n): WithAttachments {\n let pouchDoc: WithAttachments = pouchSwapPrimaryToId(primaryKey, doc);\n\n // always flat clone because we mutate the _attachments property.\n pouchDoc = flatClone(pouchDoc);\n\n pouchDoc._attachments = {};\n if (doc._attachments) {\n Object.entries(doc._attachments).forEach(([key, value]) => {\n const useValue: RxAttachmentWriteData & RxAttachmentData = value as any;\n if (useValue.data) {\n (pouchDoc as any)._attachments[key] = {\n data: useValue.data,\n content_type: useValue.type\n };\n } else {\n (pouchDoc as any)._attachments[key] = {\n digest: useValue.digest,\n content_type: useValue.type,\n length: useValue.length,\n stub: true\n };\n }\n });\n }\n\n (pouchDoc as any)[POUCHDB_META_FIELDNAME] = (pouchDoc as any)._meta;\n delete (pouchDoc as any)._meta;\n\n return pouchDoc as any;\n}\n\n\n/**\n * Swaps the primaryKey of the document\n * to the _id property.\n */\nexport function pouchSwapPrimaryToId(\n primaryKey: StringKeys>,\n docData: any\n): RxDocType & { _id: string; } {\n // optimisation shortcut\n if (primaryKey === '_id') {\n return docData;\n }\n\n const idValue = docData[primaryKey];\n const ret = flatClone(docData);\n delete ret[primaryKey];\n ret._id = idValue;\n return ret;\n}\n\n/**\n * in: '_local/foobar'\n * out: 'foobar'\n */\nexport function pouchStripLocalFlagFromPrimary(str: string): string {\n return str.substring(POUCHDB_LOCAL_PREFIX.length);\n}\n\nexport function getEventKey(\n pouchDBInstance: PouchDBInstance,\n primary: string,\n change: ChangeEvent>\n): string {\n const useRev = change.doc ? change.doc._rev : change.previous._rev;\n const eventKey = pouchDBInstance.name + '|' + primary + '|' + change.operation + '|' + useRev;\n return eventKey;\n}\n\nexport function pouchChangeRowToChangeEvent(\n primaryKey: StringKeys,\n pouchDoc: any\n): ChangeEvent> {\n if (!pouchDoc) {\n throw newRxError('SNH', { args: { pouchDoc } });\n }\n const id = pouchDoc._id;\n\n const doc = pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchDoc as any\n );\n const revHeight = doc._rev ? getHeightOfRevision(doc._rev) : 1;\n\n if (pouchDoc._deleted) {\n return {\n operation: 'DELETE',\n id,\n doc: null,\n previous: doc\n };\n } else if (revHeight === 1) {\n return {\n operation: 'INSERT',\n id,\n doc,\n previous: null\n };\n } else {\n return {\n operation: 'UPDATE',\n id,\n doc: doc,\n previous: 'UNKNOWN'\n };\n }\n}\n\nexport function pouchChangeRowToChangeStreamEvent(\n primaryKey: StringKeys,\n pouchRow: PouchChangeRow\n): ChangeStreamEvent {\n const doc = pouchRow.doc;\n if (!doc) {\n throw newRxError('SNH', { args: { pouchRow } });\n }\n const revHeight = getHeightOfRevision(doc._rev);\n\n if (pouchRow.deleted) {\n const previousDoc = flatClone(\n pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchRow.doc as any\n )\n );\n const ev: ChangeStreamEvent = {\n sequence: pouchRow.seq,\n id: pouchRow.id,\n operation: 'DELETE',\n doc: null,\n previous: previousDoc\n };\n return ev;\n } else if (revHeight === 1) {\n const ev: ChangeStreamEvent = {\n sequence: pouchRow.seq,\n id: pouchRow.id,\n operation: 'INSERT',\n doc: pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchRow.doc as any\n ),\n previous: null\n };\n return ev;\n } else {\n const ev: ChangeStreamEvent = {\n sequence: pouchRow.seq,\n id: pouchRow.id,\n operation: 'UPDATE',\n doc: pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchRow.doc as any\n ),\n previous: 'UNKNOWN'\n };\n return ev;\n }\n}\n\n\n/**\n * Runs a primary swap with transform all custom primaryKey occurrences\n * into '_id'\n * @recursive\n */\nexport function primarySwapPouchDbQuerySelector(\n selector: any,\n primaryKey: StringKeys>\n): any {\n if (primaryKey === '_id') {\n return selector;\n }\n if (Array.isArray(selector)) {\n return selector.map(item => primarySwapPouchDbQuerySelector(item, primaryKey));\n } else if (typeof selector === 'object') {\n const ret: any = {};\n Object.entries(selector).forEach(([k, v]) => {\n if (k === primaryKey) {\n ret._id = v;\n } else {\n if (k.startsWith('$')) {\n ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey);\n } else {\n ret[k] = v;\n }\n }\n });\n return ret;\n } else {\n return selector;\n }\n}\n\nexport function pouchHash(data: Buffer | Blob | string): Promise {\n return new Promise(res => {\n binaryMd5(data, (digest: string) => {\n res(digest);\n });\n });\n}\n\n\n/**\n * Runs the same hashing as PouchDB would do.\n * Used to pre-calculated the hashes which is required to emit the correct events.\n */\nexport function hashAttachmentData(\n attachmentBase64String: string\n): Promise {\n let binary;\n try {\n binary = atob(attachmentBase64String);\n } catch (err) {\n console.log('hashAttachmentData() could not run b64DecodeUnicode() on ' + attachmentBase64String);\n throw err;\n }\n return pouchHash(binary);\n}\n\nexport async function writeAttachmentsToAttachments(\n attachments: { [attachmentId: string]: RxAttachmentData | RxAttachmentWriteData; }\n): Promise<{ [attachmentId: string]: RxAttachmentData; }> {\n if (!attachments) {\n return {};\n }\n const ret: { [attachmentId: string]: RxAttachmentData; } = {};\n await Promise.all(\n Object.entries(attachments)\n .map(async ([key, obj]) => {\n if (!obj.type) {\n throw newRxError('SNH', { args: { obj } });\n }\n /**\n * Is write attachment,\n * so we have to remove the data to have a\n * non-write attachment.\n */\n if ((obj as RxAttachmentWriteData).data) {\n const asWrite = (obj as RxAttachmentWriteData);\n let data: any = asWrite.data;\n const isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(data);\n if (isBuffer) {\n data = new Blob([data]);\n }\n const dataAsBase64String = typeof data === 'string' ? data : await blobBufferUtil.toBase64String(data);\n const hash = await hashAttachmentData(dataAsBase64String);\n const length = getAttachmentSize(dataAsBase64String);\n ret[key] = {\n digest: 'md5-' + hash,\n length,\n type: asWrite.type\n };\n } else {\n ret[key] = obj as RxAttachmentData;\n }\n })\n );\n return ret;\n}\n\nexport function getPouchIndexDesignDocNameByIndex(\n index: MaybeReadonly\n): string {\n const indexName = 'idx-rxdb-index-' + index.join(',');\n return indexName;\n}\n\n/**\n * PouchDB has not way to read deleted local documents\n * out of the database.\n * So instead of deleting them, we set a custom deleted flag.\n */\nexport const RXDB_POUCH_DELETED_FLAG = 'rxdb-pouch-deleted' as const;\n\n\nexport type RxLocalDocumentDataWithCustomDeletedField = RxLocalDocumentData & {\n [k in typeof RXDB_POUCH_DELETED_FLAG]?: boolean;\n};\n\n\nexport const POUCHDB_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n sequence: {\n type: 'number'\n }\n },\n required: [\n 'sequence'\n ],\n additionalProperties: false\n};\n"],"mappings":"AAiBA,SAASA,SAAS,QAAQ,aAAa;AACvC,SACIC,cAAc,EACdC,SAAS,EACTC,mBAAmB,QAChB,YAAY;AACnB,SAASC,UAAU,QAAQ,gBAAgB;AAE3C,SAASC,iBAAiB,QAAQ,yBAAyB;AA0V3D,WAAsBC,6BAA6B,YAA7BA,6BAA6B,CAC/CC,WAAkF;EAAA,IAC5B;IACtD,IAAI,CAACA,WAAW,EAAE;MACd,uBAAO,CAAC,CAAC;IACb;IACA,IAAMC,GAAkD,GAAG,CAAC,CAAC;IAAC,uBACxDC,OAAO,CAACC,GAAG,CACbC,MAAM,CAACC,OAAO,CAACL,WAAW,CAAC,CACtBM,GAAG;MAAA,IAAuB;QAAA,IAAdC,GAAG;UAAEC,GAAG;QACjB,IAAI,CAACA,GAAG,CAACC,IAAI,EAAE;UACX,MAAMZ,UAAU,CAAC,KAAK,EAAE;YAAEa,IAAI,EAAE;cAAEF,GAAG,EAAHA;YAAI;UAAE,CAAC,CAAC;QAC9C;QACA;AAChB;AACA;AACA;AACA;QAJgB;UAAA,IAKKA,GAAG,CAA2BG,IAAI;YAAA,6BAO7BC,kBAAkB;cAAA,uBACLC,kBAAkB,CAACD,kBAAkB,CAAC,iBAAnDE,IAAI;gBACV,IAAMC,MAAM,GAAGjB,iBAAiB,CAACc,kBAAkB,CAAC;gBACpDX,GAAG,CAACM,GAAG,CAAC,GAAG;kBACPS,MAAM,EAAE,MAAM,GAAGF,IAAI;kBACrBC,MAAM,EAANA,MAAM;kBACNN,IAAI,EAAEQ,QAAO,CAACR;gBAClB,CAAC;cAAC;YAAA;YAbF,IAAMQ,QAAO,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ACD8F,QAAQ,EAAE,CACN,UAAU,CACb;EACDC,oBAAoB,EAAE;AAC1B,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/rx-storage-instance-pouch.js b/dist/es/plugins/pouchdb/rx-storage-instance-pouch.js deleted file mode 100644 index 0dbefc297e3..00000000000 --- a/dist/es/plugins/pouchdb/rx-storage-instance-pouch.js +++ /dev/null @@ -1,593 +0,0 @@ -import { ObliviousSet } from 'oblivious-set'; -import { Subject } from 'rxjs'; -import { newRxError } from '../../rx-error'; -import { OPEN_POUCHDB_STORAGE_INSTANCES, OPEN_POUCH_INSTANCES, POUCHDB_DESIGN_PREFIX, pouchDocumentDataToRxDocumentData, pouchSwapIdToPrimary, rxDocumentDataToPouchDocumentData, writeAttachmentsToAttachments } from './pouchdb-helper'; -import { blobBufferUtil, flatClone, getFromMapOrThrow, getFromObjectOrThrow, lastOfArray, PROMISE_RESOLVE_VOID } from '../../util'; -import { getCustomEventEmitterByPouch } from './custom-events-plugin'; -import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -/** - * Because we internally use the findDocumentsById() - * method, it is defined here because RxStorage wrappers - * might swap out the function. - */ -var pouchFindDocumentsById = function pouchFindDocumentsById(instance, ids, deleted) { - try { - ensureNotClosed(instance); - var ret = {}; - - /** - * On deleted documents, PouchDB will only return the tombstone. - * So we have to get the properties directly for each document - * with the hack of getting the changes and then make one request per document - * with the latest revision. - * TODO create an issue at pouchdb on how to get the document data of deleted documents, - * when one past revision was written via new_edits=false - * @link https://stackoverflow.com/a/63516761/3443137 - */ - if (deleted) { - instance.nonParallelQueue = instance.nonParallelQueue.then(function () { - try { - return Promise.resolve(instance.internals.pouch.changes({ - live: false, - since: 0, - doc_ids: ids, - style: 'all_docs' - })).then(function (viaChanges) { - return Promise.resolve(Promise.all(viaChanges.results.map(function (result) { - try { - return Promise.resolve(instance.internals.pouch.get(result.id, { - rev: result.changes[0].rev, - deleted: 'ok', - style: 'all_docs' - })).then(function (firstDoc) { - var useFirstDoc = pouchDocumentDataToRxDocumentData(instance.primaryPath, firstDoc); - ret[result.id] = useFirstDoc; - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(instance.nonParallelQueue).then(function () { - return ret; - }); - } else { - instance.nonParallelQueue = instance.nonParallelQueue.then(function () { - try { - return Promise.resolve(instance.internals.pouch.allDocs({ - include_docs: true, - keys: ids - })).then(function (pouchResult) { - pouchResult.rows.filter(function (row) { - return !!row.doc; - }).forEach(function (row) { - var docData = row.doc; - docData = pouchDocumentDataToRxDocumentData(instance.primaryPath, docData); - ret[row.id] = docData; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(instance.nonParallelQueue).then(function () { - return ret; - }); - } - } catch (e) { - return Promise.reject(e); - } -}; -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -var lastId = 0; -export var RxStorageInstancePouch = /*#__PURE__*/function () { - /** - * Some PouchDB operations give wrong results when they run in parallel. - * So we have to ensure they are queued up. - */ - - function RxStorageInstancePouch(storage, databaseName, collectionName, schema, internals, options) { - var _this = this; - this.id = lastId++; - this.changes$ = new Subject(); - this.subs = []; - this.closed = false; - this.nonParallelQueue = PROMISE_RESOLVE_VOID; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - OPEN_POUCHDB_STORAGE_INSTANCES.add(this); - this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); - /** - * Instead of listening to pouch.changes, - * we have overwritten pouchdbs bulkDocs() - * and create our own event stream, this will work more reliable - * and does not mix up with write events from other sources. - */ - var emitter = getCustomEventEmitterByPouch(this.internals.pouch); - - /** - * Contains all eventIds that of emitted events, - * used because multi-instance pouchdbs often will reemit the same - * event on the other browser tab so we have to de-duplicate them. - */ - var emittedEventBulkIds = new ObliviousSet(60 * 1000); - var eventSub = emitter.subject.subscribe(function (eventBulk) { - if (eventBulk.events.length === 0 || emittedEventBulkIds.has(eventBulk.id)) { - return; - } - emittedEventBulkIds.add(eventBulk.id); - - // rewrite primaryPath of all events - eventBulk.events.forEach(function (event) { - if (event.documentData) { - event.documentData = pouchSwapIdToPrimary(_this.primaryPath, event.documentData); - } - if (event.previousDocumentData) { - event.previousDocumentData = pouchSwapIdToPrimary(_this.primaryPath, event.previousDocumentData); - } - }); - _this.changes$.next(eventBulk); - }); - this.subs.push(eventSub); - } - var _proto = RxStorageInstancePouch.prototype; - _proto.close = function close() { - ensureNotClosed(this); - this.closed = true; - this.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); - OPEN_POUCH_INSTANCES["delete"](this.internals.pouchInstanceId); - - // TODO this did not work because a closed pouchdb cannot be recreated in the same process run - // await this.internals.pouch.close(); - return PROMISE_RESOLVE_VOID; - }; - _proto.remove = function remove() { - try { - var _this2 = this; - ensureNotClosed(_this2); - _this2.closed = true; - _this2.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - OPEN_POUCHDB_STORAGE_INSTANCES["delete"](_this2); - OPEN_POUCH_INSTANCES["delete"](_this2.internals.pouchInstanceId); - return Promise.resolve(_this2.internals.pouch.destroy()).then(function () {}); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this3 = this; - ensureNotClosed(_this3); - if (documentWrites.length === 0) { - throw newRxError('P2', { - args: { - documentWrites: documentWrites - } - }); - } - var writeRowById = new Map(); - var insertDocsById = new Map(); - var writeDocs = documentWrites.map(function (writeData) { - /** - * Ensure that _meta.lwt is set correctly - */ - if (writeData.document._meta.lwt < 1000 || writeData.previous && writeData.previous._meta.lwt >= writeData.document._meta.lwt) { - throw newRxError('SNH', { - args: writeData - }); - } - - /** - * Ensure that a revision exists, - * having an empty revision here would not throw - * but just not resolve forever. - */ - if (!writeData.document._rev) { - throw newRxError('SNH', { - args: writeData - }); - } - var primary = writeData.document[_this3.primaryPath]; - writeRowById.set(primary, writeData); - var storeDocumentData = rxDocumentDataToPouchDocumentData(_this3.primaryPath, writeData.document); - insertDocsById.set(primary, storeDocumentData); - return storeDocumentData; - }); - var previousDocsInDb = new Map(); - var ret = { - success: {}, - error: {} - }; - _this3.nonParallelQueue = _this3.nonParallelQueue.then(function () { - try { - return Promise.resolve(_this3.internals.pouch.bulkDocs(writeDocs, { - new_edits: false, - custom: { - primaryPath: _this3.primaryPath, - writeRowById: writeRowById, - insertDocsById: insertDocsById, - previousDocsInDb: previousDocsInDb, - context: context - } - })).then(function (pouchResult) { - return Promise.all(pouchResult.map(function (resultRow) { - try { - var writeRow = getFromMapOrThrow(writeRowById, resultRow.id); - var _temp3 = function () { - if (resultRow.error) { - var previousDoc = getFromMapOrThrow(previousDocsInDb, resultRow.id); - var err = { - isError: true, - status: 409, - documentId: resultRow.id, - writeRow: writeRow, - documentInDb: pouchDocumentDataToRxDocumentData(_this3.primaryPath, previousDoc) - }; - ret.error[resultRow.id] = err; - } else { - var _temp2 = function _temp2() { - ret.success[resultRow.id] = _pushObj; - }; - var _pushObj = flatClone(writeRow.document); - _pushObj = pouchSwapIdToPrimary(_this3.primaryPath, _pushObj); - _pushObj._rev = resultRow.rev; - - // replace the inserted attachments with their diggest - _pushObj._attachments = {}; - var _temp = function () { - if (!writeRow.document._attachments) { - writeRow.document._attachments = {}; - } else { - return Promise.resolve(writeAttachmentsToAttachments(writeRow.document._attachments)).then(function (_writeAttachmentsToAt) { - _pushObj._attachments = _writeAttachmentsToAt; - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - })); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(_this3.nonParallelQueue).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - try { - var _this4 = this; - ensureNotClosed(_this4); - return Promise.resolve(_this4.internals.pouch.find(preparedQuery)).then(function (findResult) { - var ret = { - documents: findResult.docs.map(function (pouchDoc) { - var useDoc = pouchDocumentDataToRxDocumentData(_this4.primaryPath, pouchDoc); - return useDoc; - }) - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.count = function count(preparedQuery) { - try { - var _this5 = this; - /** - * There is no count method in PouchDB, - * so we have to run a normal query and use the result length. - */ - return Promise.resolve(_this5.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(documentId, attachmentId) { - try { - var _this6 = this; - ensureNotClosed(_this6); - return Promise.resolve(_this6.internals.pouch.getAttachment(documentId, attachmentId)).then(function (attachmentData) { - /** - * In Node.js, PouchDB works with Buffers because it is old and Node.js did - * not support Blob at the time is was coded. - * So here we have to transform the Buffer to a Blob. - */ - var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(attachmentData); - if (isBuffer) { - attachmentData = new Blob([attachmentData]); - } - return Promise.resolve(blobBufferUtil.toBase64String(attachmentData)); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - return pouchFindDocumentsById(this, ids, deleted); - }; - _proto.changeStream = function changeStream() { - ensureNotClosed(this); - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(_minimumDeletedTime) { - ensureNotClosed(this); - /** - * PouchDB does not support purging documents. - * So instead we run a compaction that might at least help a bit - * in freeing up disc space. - * @link https://github.com/pouchdb/pouchdb/issues/802 - */ - return this.internals.pouch.compact().then(function () { - return true; - }); - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _temp5 = function _temp5() { - return Promise.resolve(pouchFindDocumentsById(_this7, changedDocuments.map(function (o) { - return o.id; - }), true)).then(function (documentsData) { - if (Object.keys(documentsData).length > 0 && checkpoint && checkpoint.sequence === lastSequence) { - /** - * When documents are returned, it makes no sense - * if the sequence is equal to the one given at the checkpoint. - */ - throw new Error('same sequence'); - } - var lastRow = lastOfArray(changedDocuments); - var documents = changedDocuments.map(function (changeRow) { - return getFromObjectOrThrow(documentsData, changeRow.id); - }); - return { - documents: documents, - checkpoint: lastRow ? { - sequence: lastRow.sequence - } : checkpoint ? checkpoint : { - sequence: -1 - } - }; - }); - }; - var _this7 = this; - ensureNotClosed(_this7); - if (!limit || typeof limit !== 'number') { - throw new Error('wrong limit'); - } - var pouchChangesOpts = { - live: false, - limit: limit, - include_docs: false, - since: checkpoint ? checkpoint.sequence : 0, - descending: false - }; - var lastSequence = 0; - var first = true; - var skippedDesignDocuments = 0; - var changedDocuments = []; - /** - * Because PouchDB also returns changes of _design documents, - * we have to fill up the results with more changes if this happens. - */ - var _temp4 = _for(function () { - return !!first || skippedDesignDocuments > 0; - }, void 0, function () { - first = false; - skippedDesignDocuments = 0; - return Promise.resolve(_this7.internals.pouch.changes(pouchChangesOpts)).then(function (pouchResults) { - var addChangedDocuments = pouchResults.results.filter(function (row) { - var isDesignDoc = row.id.startsWith(POUCHDB_DESIGN_PREFIX); - if (isDesignDoc) { - skippedDesignDocuments = skippedDesignDocuments + 1; - return false; - } else { - return true; - } - }).map(function (row) { - return { - id: row.id, - sequence: row.seq - }; - }); - changedDocuments = changedDocuments.concat(addChangedDocuments); - lastSequence = pouchResults.last_seq; - - // modify pouch options for next run of pouch.changes() - pouchChangesOpts.since = lastSequence; - pouchChangesOpts.limit = skippedDesignDocuments; - }); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstancePouch; -}(); -function ensureNotClosed(instance) { - if (instance.closed) { - throw new Error('RxStorageInstancePouch is closed ' + instance.databaseName + '-' + instance.collectionName); - } -} -//# sourceMappingURL=rx-storage-instance-pouch.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/rx-storage-instance-pouch.js.map b/dist/es/plugins/pouchdb/rx-storage-instance-pouch.js.map deleted file mode 100644 index ef6f69bedc9..00000000000 --- a/dist/es/plugins/pouchdb/rx-storage-instance-pouch.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-pouch.js","names":["ObliviousSet","Subject","newRxError","OPEN_POUCHDB_STORAGE_INSTANCES","OPEN_POUCH_INSTANCES","POUCHDB_DESIGN_PREFIX","pouchDocumentDataToRxDocumentData","pouchSwapIdToPrimary","rxDocumentDataToPouchDocumentData","writeAttachmentsToAttachments","blobBufferUtil","flatClone","getFromMapOrThrow","getFromObjectOrThrow","lastOfArray","PROMISE_RESOLVE_VOID","getCustomEventEmitterByPouch","getPrimaryFieldOfPrimaryKey","_settle","pact","state","value","s","_Pact","v","o","bind","then","observer","pouchFindDocumentsById","instance","ids","deleted","ensureNotClosed","ret","nonParallelQueue","internals","pouch","changes","live","since","doc_ids","style","viaChanges","Promise","all","results","map","result","get","id","rev","firstDoc","useFirstDoc","primaryPath","allDocs","include_docs","keys","pouchResult","rows","filter","row","doc","forEach","docData","prototype","onFulfilled","onRejected","callback","e","_this","_isSettledPact","thenable","_for","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","lastId","RxStorageInstancePouch","storage","databaseName","collectionName","schema","options","changes$","subs","closed","add","primaryKey","emitter","emittedEventBulkIds","eventSub","subject","subscribe","eventBulk","events","length","has","event","documentData","previousDocumentData","next","push","close","sub","unsubscribe","pouchInstanceId","remove","destroy","bulkWrite","documentWrites","context","args","writeRowById","Map","insertDocsById","writeDocs","writeData","document","_meta","lwt","previous","_rev","primary","set","storeDocumentData","previousDocsInDb","success","error","bulkDocs","new_edits","custom","resultRow","writeRow","previousDoc","err","isError","status","documentId","documentInDb","pushObj","_attachments","query","preparedQuery","find","findResult","documents","docs","pouchDoc","useDoc","count","mode","getAttachmentData","attachmentId","getAttachment","attachmentData","isBuffer","Buffer","Blob","toBase64String","findDocumentsById","changeStream","asObservable","cleanup","_minimumDeletedTime","compact","getChangedDocumentsSince","limit","checkpoint","changedDocuments","documentsData","Object","sequence","lastSequence","Error","lastRow","changeRow","pouchChangesOpts","descending","first","skippedDesignDocuments","pouchResults","addChangedDocuments","isDesignDoc","startsWith","seq","concat","last_seq","conflictResultionTasks","resolveConflictResultionTask","_taskSolution"],"sources":["../../../../src/plugins/pouchdb/rx-storage-instance-pouch.ts"],"sourcesContent":["import { ObliviousSet } from 'oblivious-set';\nimport {\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport { newRxError } from '../../rx-error';\nimport type {\n BulkWriteRow,\n EventBulk,\n PouchBulkDocResultRow,\n PouchChangesOptionsNonLive,\n PouchCheckpoint,\n PouchSettings,\n PouchWriteError,\n PreparedQuery,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport {\n OPEN_POUCHDB_STORAGE_INSTANCES,\n OPEN_POUCH_INSTANCES,\n POUCHDB_DESIGN_PREFIX,\n pouchDocumentDataToRxDocumentData,\n PouchStorageInternals,\n pouchSwapIdToPrimary,\n rxDocumentDataToPouchDocumentData,\n writeAttachmentsToAttachments\n} from './pouchdb-helper';\nimport {\n blobBufferUtil,\n flatClone,\n getFromMapOrThrow,\n getFromObjectOrThrow,\n lastOfArray,\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport {\n getCustomEventEmitterByPouch\n} from './custom-events-plugin';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\n\n\nlet lastId = 0;\n\nexport class RxStorageInstancePouch implements RxStorageInstance<\nRxDocType,\nPouchStorageInternals,\nPouchSettings,\nPouchCheckpoint\n> {\n public readonly id: number = lastId++;\n\n private changes$: Subject>, PouchCheckpoint>> = new Subject();\n private subs: Subscription[] = [];\n public primaryPath: StringKeys>;\n\n public closed: boolean = false;\n\n\n /**\n * Some PouchDB operations give wrong results when they run in parallel.\n * So we have to ensure they are queued up.\n */\n public nonParallelQueue: Promise = PROMISE_RESOLVE_VOID;\n\n constructor(\n public readonly storage: RxStorage,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: Readonly,\n public readonly options: Readonly\n ) {\n OPEN_POUCHDB_STORAGE_INSTANCES.add(this);\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n /**\n * Instead of listening to pouch.changes,\n * we have overwritten pouchdbs bulkDocs()\n * and create our own event stream, this will work more reliable\n * and does not mix up with write events from other sources.\n */\n const emitter = getCustomEventEmitterByPouch(this.internals.pouch);\n\n /**\n * Contains all eventIds that of emitted events,\n * used because multi-instance pouchdbs often will reemit the same\n * event on the other browser tab so we have to de-duplicate them.\n */\n const emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n const eventSub = emitter.subject.subscribe((eventBulk) => {\n if (\n eventBulk.events.length === 0 ||\n emittedEventBulkIds.has(eventBulk.id)\n ) {\n return;\n }\n emittedEventBulkIds.add(eventBulk.id);\n\n // rewrite primaryPath of all events\n eventBulk.events.forEach(event => {\n if (event.documentData) {\n event.documentData = pouchSwapIdToPrimary(\n this.primaryPath,\n event.documentData as any\n );\n }\n if (event.previousDocumentData) {\n event.previousDocumentData = pouchSwapIdToPrimary(\n this.primaryPath,\n event.previousDocumentData as any\n );\n }\n });\n this.changes$.next(eventBulk);\n });\n this.subs.push(eventSub);\n }\n\n close() {\n ensureNotClosed(this);\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n OPEN_POUCHDB_STORAGE_INSTANCES.delete(this);\n OPEN_POUCH_INSTANCES.delete(this.internals.pouchInstanceId);\n\n // TODO this did not work because a closed pouchdb cannot be recreated in the same process run\n // await this.internals.pouch.close();\n return PROMISE_RESOLVE_VOID;\n }\n\n async remove() {\n ensureNotClosed(this);\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n\n OPEN_POUCHDB_STORAGE_INSTANCES.delete(this);\n OPEN_POUCH_INSTANCES.delete(this.internals.pouchInstanceId);\n\n await this.internals.pouch.destroy();\n }\n public async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise<\n RxStorageBulkWriteResponse\n > {\n ensureNotClosed(this);\n if (documentWrites.length === 0) {\n throw newRxError('P2', {\n args: {\n documentWrites\n }\n });\n }\n\n const writeRowById: Map> = new Map();\n const insertDocsById: Map = new Map();\n const writeDocs: (RxDocType & { _id: string; _rev: string; })[] = documentWrites.map(writeData => {\n\n /**\n * Ensure that _meta.lwt is set correctly\n */\n if (\n writeData.document._meta.lwt < 1000 ||\n (\n writeData.previous &&\n writeData.previous._meta.lwt >= writeData.document._meta.lwt\n )\n ) {\n throw newRxError('SNH', {\n args: writeData\n });\n }\n\n /**\n * Ensure that a revision exists,\n * having an empty revision here would not throw\n * but just not resolve forever.\n */\n if (!writeData.document._rev) {\n throw newRxError('SNH', {\n args: writeData\n });\n }\n\n const primary: string = (writeData.document as any)[this.primaryPath];\n writeRowById.set(primary, writeData);\n const storeDocumentData: any = rxDocumentDataToPouchDocumentData(\n this.primaryPath,\n writeData.document\n );\n insertDocsById.set(primary, storeDocumentData);\n return storeDocumentData;\n });\n\n const previousDocsInDb: Map> = new Map();\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n this.nonParallelQueue = this.nonParallelQueue.then(async () => {\n const pouchResult = await this.internals.pouch.bulkDocs(writeDocs, {\n new_edits: false,\n custom: {\n primaryPath: this.primaryPath,\n writeRowById,\n insertDocsById,\n previousDocsInDb,\n context\n }\n } as any);\n return Promise.all(\n pouchResult.map(async (resultRow) => {\n const writeRow = getFromMapOrThrow(writeRowById, resultRow.id);\n if ((resultRow as PouchWriteError).error) {\n const previousDoc = getFromMapOrThrow(previousDocsInDb, resultRow.id);\n const err: RxStorageBulkWriteError = {\n isError: true,\n status: 409,\n documentId: resultRow.id,\n writeRow,\n documentInDb: pouchDocumentDataToRxDocumentData(\n this.primaryPath,\n previousDoc\n )\n };\n ret.error[resultRow.id] = err;\n } else {\n let pushObj: RxDocumentData = flatClone(writeRow.document) as any;\n pushObj = pouchSwapIdToPrimary(this.primaryPath, pushObj);\n pushObj._rev = (resultRow as PouchBulkDocResultRow).rev;\n\n // replace the inserted attachments with their diggest\n pushObj._attachments = {};\n if (!writeRow.document._attachments) {\n writeRow.document._attachments = {};\n } else {\n pushObj._attachments = await writeAttachmentsToAttachments(writeRow.document._attachments);\n }\n ret.success[resultRow.id] = pushObj;\n }\n })\n );\n });\n await this.nonParallelQueue;\n return ret;\n }\n\n public async query(\n preparedQuery: PreparedQuery\n ): Promise> {\n ensureNotClosed(this);\n const findResult = await this.internals.pouch.find(preparedQuery);\n const ret: RxStorageQueryResult = {\n documents: findResult.docs.map(pouchDoc => {\n const useDoc = pouchDocumentDataToRxDocumentData(\n this.primaryPath,\n pouchDoc\n );\n return useDoc;\n })\n };\n return ret;\n }\n async count(\n preparedQuery: PreparedQuery\n ): Promise {\n /**\n * There is no count method in PouchDB,\n * so we have to run a normal query and use the result length.\n */\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n async getAttachmentData(\n documentId: string,\n attachmentId: string\n ): Promise {\n ensureNotClosed(this);\n let attachmentData = await this.internals.pouch.getAttachment(\n documentId,\n attachmentId\n );\n\n /**\n * In Node.js, PouchDB works with Buffers because it is old and Node.js did\n * not support Blob at the time is was coded.\n * So here we have to transform the Buffer to a Blob.\n */\n const isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(attachmentData);\n if (isBuffer) {\n attachmentData = new Blob([attachmentData]);\n }\n\n const ret = await blobBufferUtil.toBase64String(attachmentData);\n return ret;\n }\n\n findDocumentsById(\n ids: string[],\n deleted: boolean\n ): Promise> {\n return pouchFindDocumentsById(\n this,\n ids,\n deleted\n );\n }\n\n changeStream(): Observable>, PouchCheckpoint>> {\n ensureNotClosed(this);\n return this.changes$.asObservable();\n }\n\n cleanup(_minimumDeletedTime: number): Promise {\n ensureNotClosed(this);\n /**\n * PouchDB does not support purging documents.\n * So instead we run a compaction that might at least help a bit\n * in freeing up disc space.\n * @link https://github.com/pouchdb/pouchdb/issues/802\n */\n return this.internals.pouch\n .compact()\n .then(() => true);\n }\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: PouchCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: PouchCheckpoint;\n }> {\n ensureNotClosed(this);\n if (!limit || typeof limit !== 'number') {\n throw new Error('wrong limit');\n }\n\n const pouchChangesOpts: PouchChangesOptionsNonLive = {\n live: false,\n limit: limit,\n include_docs: false,\n since: checkpoint ? checkpoint.sequence : 0,\n descending: false\n };\n\n let lastSequence = 0;\n let first = true;\n let skippedDesignDocuments = 0;\n let changedDocuments: { id: string; sequence: number; }[] = [];\n /**\n * Because PouchDB also returns changes of _design documents,\n * we have to fill up the results with more changes if this happens.\n */\n while (first || skippedDesignDocuments > 0) {\n first = false;\n skippedDesignDocuments = 0;\n const pouchResults = await this.internals.pouch.changes(pouchChangesOpts);\n const addChangedDocuments = pouchResults.results\n .filter(row => {\n const isDesignDoc = row.id.startsWith(POUCHDB_DESIGN_PREFIX);\n if (isDesignDoc) {\n skippedDesignDocuments = skippedDesignDocuments + 1;\n return false;\n } else {\n return true;\n }\n })\n .map(row => ({\n id: row.id,\n sequence: row.seq\n }));\n changedDocuments = changedDocuments.concat(addChangedDocuments);\n lastSequence = pouchResults.last_seq;\n\n // modify pouch options for next run of pouch.changes()\n pouchChangesOpts.since = lastSequence;\n pouchChangesOpts.limit = skippedDesignDocuments;\n }\n\n const documentsData = await pouchFindDocumentsById(\n this,\n changedDocuments.map(o => o.id),\n true\n );\n\n if (\n Object.keys(documentsData).length > 0 &&\n checkpoint && checkpoint.sequence === lastSequence\n ) {\n /**\n * When documents are returned, it makes no sense\n * if the sequence is equal to the one given at the checkpoint.\n */\n throw new Error('same sequence');\n }\n\n const lastRow = lastOfArray(changedDocuments);\n const documents = changedDocuments.map(changeRow => getFromObjectOrThrow(documentsData, changeRow.id));\n\n return {\n documents,\n checkpoint: lastRow ? {\n sequence: lastRow.sequence\n } : checkpoint ? checkpoint : {\n sequence: -1\n }\n };\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n}\n\n\n\nfunction ensureNotClosed(\n instance: RxStorageInstancePouch\n) {\n if (instance.closed) {\n throw new Error('RxStorageInstancePouch is closed ' + instance.databaseName + '-' + instance.collectionName);\n }\n}\n\n\n/**\n * Because we internally use the findDocumentsById()\n * method, it is defined here because RxStorage wrappers\n * might swap out the function.\n */\nasync function pouchFindDocumentsById(\n instance: RxStorageInstancePouch,\n ids: string[],\n deleted: boolean\n): Promise> {\n ensureNotClosed(instance);\n const ret: RxDocumentDataById = {};\n\n /**\n * On deleted documents, PouchDB will only return the tombstone.\n * So we have to get the properties directly for each document\n * with the hack of getting the changes and then make one request per document\n * with the latest revision.\n * TODO create an issue at pouchdb on how to get the document data of deleted documents,\n * when one past revision was written via new_edits=false\n * @link https://stackoverflow.com/a/63516761/3443137\n */\n if (deleted) {\n instance.nonParallelQueue = instance.nonParallelQueue.then(async () => {\n const viaChanges = await instance.internals.pouch.changes({\n live: false,\n since: 0,\n doc_ids: ids,\n style: 'all_docs'\n });\n await Promise.all(\n viaChanges.results.map(async (result) => {\n const firstDoc = await instance.internals.pouch.get(\n result.id,\n {\n rev: result.changes[0].rev,\n deleted: 'ok',\n style: 'all_docs'\n }\n );\n const useFirstDoc = pouchDocumentDataToRxDocumentData(\n instance.primaryPath,\n firstDoc\n );\n ret[result.id] = useFirstDoc;\n })\n );\n });\n await instance.nonParallelQueue;\n return ret;\n } else {\n instance.nonParallelQueue = instance.nonParallelQueue.then(async () => {\n const pouchResult = await instance.internals.pouch.allDocs({\n include_docs: true,\n keys: ids\n });\n pouchResult.rows\n .filter(row => !!row.doc)\n .forEach(row => {\n let docData = row.doc;\n docData = pouchDocumentDataToRxDocumentData(\n instance.primaryPath,\n docData\n );\n ret[row.id] = docData;\n });\n });\n await instance.nonParallelQueue;\n return ret;\n }\n}\n"],"mappings":"AAAA,SAASA,YAAY,QAAQ,eAAe;AAC5C,SAEIC,OAAO,QAEJ,MAAM;AACb,SAASC,UAAU,QAAQ,gBAAgB;AAwB3C,SACIC,8BAA8B,EAC9BC,oBAAoB,EACpBC,qBAAqB,EACrBC,iCAAiC,EAEjCC,oBAAoB,EACpBC,iCAAiC,EACjCC,6BAA6B,QAC1B,kBAAkB;AACzB,SACIC,cAAc,EACdC,SAAS,EACTC,iBAAiB,EACjBC,oBAAoB,EACpBC,WAAW,EACXC,oBAAoB,QACjB,YAAY;AACnB,SACIC,4BAA4B,QACzB,wBAAwB;AAC/B,SAASC,2BAA2B,QAAQ,wBAAwB;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,mBAAmB,GAAGD,YAAY,CAAC9I,OAAO,CAC3Cc,MAAM,CAAC,UAAAC,GAAG,EAAI;YACX,IAAMiI,WAAW,GAAGjI,GAAG,CAACX,EAAE,CAAC6I,UAAU,CAAC1L,qBAAqB,CAAC;YAC5D,IAAIyL,WAAW,EAAE;cACbH,sBAAsB,GAAGA,sBAAsB,GAAG,CAAC;cACnD,OAAO,KAAK;YAChB,CAAC,MAAM;cACH,OAAO,IAAI;YACf;UACJ,CAAC,CAAC,CACD5I,GAAG,CAAC,UAAAc,GAAG;YAAA,OAAK;cACTX,EAAE,EAAEW,GAAG,CAACX,EAAE;cACViI,QAAQ,EAAEtH,GAAG,CAACmI;YAClB,CAAC;UAAA,CAAC,CAAC;UACPhB,gBAAgB,GAAGA,gBAAgB,CAACiB,MAAM,CAACJ,mBAAmB,CAAC;UAC/DT,YAAY,GAAGQ,YAAY,CAACM,QAAQ;;UAEpC;UACAV,gBAAgB,CAAChJ,KAAK,GAAG4I,YAAY;UACrCI,gBAAgB,CAACV,KAAK,GAAGa,sBAAsB;QAAC;MACpD,CAAC;MAAA;IA8BL,CAAC;MAAA;IAAA;EAAA;EAAA,OAEDQ,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAIlM,OAAO,EAAE;EACxB,CAAC;EAAA,OACKmM,4BAA4B,yCAACC,aAAyD,EAAiB;IAAA;EAAE,CAAC;EAAA;AAAA;AAKpH,SAASpK,eAAe,CACpBH,QAAqC,EACvC;EACE,IAAIA,QAAQ,CAAC+D,MAAM,EAAE;IACjB,MAAM,IAAIwF,KAAK,CAAC,mCAAmC,GAAGvJ,QAAQ,CAACyD,YAAY,GAAG,GAAG,GAAGzD,QAAQ,CAAC0D,cAAc,CAAC;EAChH;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/rx-storage-pouchdb.js b/dist/es/plugins/pouchdb/rx-storage-pouchdb.js deleted file mode 100644 index ba8817fc85c..00000000000 --- a/dist/es/plugins/pouchdb/rx-storage-pouchdb.js +++ /dev/null @@ -1,176 +0,0 @@ -import { adapterObject, getFromMapOrThrow, isMaybeReadonlyArray } from '../../util'; -import { addPouchPlugin, isLevelDown, PouchDB } from './pouch-db'; -import { newRxError } from '../../rx-error'; -import { RxStorageInstancePouch } from './rx-storage-instance-pouch'; -import { getPouchIndexDesignDocNameByIndex, openPouchId, OPEN_POUCH_INSTANCES, RX_STORAGE_NAME_POUCHDB } from './pouchdb-helper'; -import PouchDBFind from 'pouchdb-find'; -import { RxStoragePouchStatics } from './pouch-statics'; -import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; -import { addCustomEventsPluginToPouch } from './custom-events-plugin'; -import { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance'; -import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper'; -/** - * Creates the indexes of the schema inside of the pouchdb instance. - * Will skip indexes that already exist. - */ -export var createIndexesOnPouch = function createIndexesOnPouch(pouch, schema) { - try { - if (!schema.indexes) { - return Promise.resolve(); - } - var primaryKey = getPrimaryFieldOfPrimaryKey(schema.primaryKey); - return Promise.resolve(pouch.getIndexes()).then(function (before) { - var existingIndexes = new Set(before.indexes.map(function (idx) { - return idx.name; - })); - return Promise.resolve(Promise.all(schema.indexes.map(function (indexMaybeArray) { - var indexArray = isMaybeReadonlyArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; - - /** - * replace primary key with _id - * because that is the enforced primary key on pouchdb. - */ - indexArray = indexArray.map(function (key) { - if (key === primaryKey) { - return '_id'; - } else { - return key; - } - }); - var indexName = getPouchIndexDesignDocNameByIndex(indexArray); - if (existingIndexes.has(indexName)) { - // index already exists - return; - } - - /** - * TODO we might have even better performance by doing a pouch.bulkDocs() - * on index creation - */ - return pouch.createIndex({ - name: indexName, - ddoc: indexName, - index: { - fields: indexArray - } - }); - }))).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * returns the pouchdb-database-name - */ -export var RxStoragePouch = /*#__PURE__*/function () { - function RxStoragePouch(adapter) { - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.name = RX_STORAGE_NAME_POUCHDB; - this.statics = RxStoragePouchStatics; - this.adapter = adapter; - this.pouchSettings = pouchSettings; - checkPouchAdapter(adapter); - } - var _proto = RxStoragePouch.prototype; - _proto.createPouch = function createPouch(location, options) { - var pouchDbParameters = { - location: location, - adapter: adapterObject(this.adapter), - settings: options - }; - var pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); - var pouch = new PouchDB(pouchDbParameters.location, pouchDBOptions); - - /** - * In the past we found some errors where the PouchDB is not directly usable - * so we we had to call .info() first to ensure it can be used. - * I commented this out for now to get faster database/collection creation. - * We might have to add this again if something fails. - */ - // await pouch.info(); - - return Promise.resolve(pouch); - }; - _proto.createStorageInstance = function createStorageInstance(params) { - try { - var _this = this; - ensureRxStorageInstanceParamsAreCorrect(params); - var pouchLocation = getPouchLocation(params.databaseName, params.collectionName, params.schema.version); - return Promise.resolve(_this.createPouch(pouchLocation, params.options)).then(function (pouch) { - return Promise.resolve(createIndexesOnPouch(pouch, params.schema)).then(function () { - var pouchInstanceId = openPouchId(params.databaseInstanceToken, params.databaseName, params.collectionName, params.schema.version); - var instance = new RxStorageInstancePouch(_this, params.databaseName, params.collectionName, params.schema, { - pouch: pouch, - pouchInstanceId: pouchInstanceId - }, params.options); - OPEN_POUCH_INSTANCES.set(pouchInstanceId, pouch); - addRxStorageMultiInstanceSupport(RX_STORAGE_NAME_POUCHDB, params, instance); - return instance; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - return RxStoragePouch; -}(); - -/** - * Checks if all is ok with the given adapter, - * else throws an error. - */ -export function checkPouchAdapter(adapter) { - if (typeof adapter === 'string') { - if (!PouchDB.adapters || !PouchDB.adapters[adapter]) { - throw newRxError('DB9', { - adapter: adapter - }); - } - } else { - isLevelDown(adapter); - if (!PouchDB.adapters || !PouchDB.adapters.leveldb) { - throw newRxError('DB10', { - adapter: adapter - }); - } - } -} -export function getPouchLocation(dbName, collectionName, schemaVersion) { - var prefix = dbName + '-rxdb-' + schemaVersion + '-'; - if (!collectionName.includes('/')) { - return prefix + collectionName; - } else { - // if collectionName is a path, we have to prefix the last part only - var split = collectionName.split('/'); - var last = split.pop(); - var ret = split.join('/'); - ret += '/' + prefix + last; - return ret; - } -} -export function getPouchDBOfRxCollection(collection) { - var id = openPouchId(collection.database.token, collection.database.name, collection.name, collection.schema.version); - var pouch = getFromMapOrThrow(OPEN_POUCH_INSTANCES, id); - return pouch; -} -var addedRxDBPouchPlugins = false; - -/** - * @deprecated PouchDB RxStorage is deprecated, see - * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated - */ -export function getRxStoragePouch(adapter, pouchSettings) { - if (!addedRxDBPouchPlugins) { - addedRxDBPouchPlugins = true; - addPouchPlugin(PouchDBFind); - addCustomEventsPluginToPouch(); - } - if (!adapter) { - throw new Error('adapter missing'); - } - var storage = new RxStoragePouch(adapter, pouchSettings); - return storage; -} -//# sourceMappingURL=rx-storage-pouchdb.js.map \ No newline at end of file diff --git a/dist/es/plugins/pouchdb/rx-storage-pouchdb.js.map b/dist/es/plugins/pouchdb/rx-storage-pouchdb.js.map deleted file mode 100644 index 131afacd9b6..00000000000 --- a/dist/es/plugins/pouchdb/rx-storage-pouchdb.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-pouchdb.js","names":["adapterObject","getFromMapOrThrow","isMaybeReadonlyArray","addPouchPlugin","isLevelDown","PouchDB","newRxError","RxStorageInstancePouch","getPouchIndexDesignDocNameByIndex","openPouchId","OPEN_POUCH_INSTANCES","RX_STORAGE_NAME_POUCHDB","PouchDBFind","RxStoragePouchStatics","getPrimaryFieldOfPrimaryKey","addCustomEventsPluginToPouch","addRxStorageMultiInstanceSupport","ensureRxStorageInstanceParamsAreCorrect","createIndexesOnPouch","pouch","schema","indexes","primaryKey","getIndexes","before","existingIndexes","Set","map","idx","name","Promise","all","indexMaybeArray","indexArray","key","indexName","has","createIndex","ddoc","index","fields","RxStoragePouch","adapter","pouchSettings","statics","checkPouchAdapter","createPouch","location","options","pouchDbParameters","settings","pouchDBOptions","Object","assign","resolve","createStorageInstance","params","pouchLocation","getPouchLocation","databaseName","collectionName","version","pouchInstanceId","databaseInstanceToken","instance","set","adapters","leveldb","dbName","schemaVersion","prefix","includes","split","last","pop","ret","join","getPouchDBOfRxCollection","collection","id","database","token","addedRxDBPouchPlugins","getRxStoragePouch","Error","storage"],"sources":["../../../../src/plugins/pouchdb/rx-storage-pouchdb.ts"],"sourcesContent":["\nimport type {\n PouchDBInstance,\n PouchSettings,\n RxJsonSchema,\n RxStorageInstanceCreationParams,\n RxStorage,\n MaybeReadonly,\n RxCollection\n} from '../../types';\n\nimport {\n adapterObject,\n getFromMapOrThrow,\n isMaybeReadonlyArray\n} from '../../util';\nimport {\n addPouchPlugin,\n isLevelDown,\n PouchDB\n} from './pouch-db';\nimport { newRxError } from '../../rx-error';\n\nimport { RxStorageInstancePouch } from './rx-storage-instance-pouch';\nimport {\n getPouchIndexDesignDocNameByIndex,\n openPouchId,\n OPEN_POUCH_INSTANCES,\n PouchStorageInternals,\n RX_STORAGE_NAME_POUCHDB\n} from './pouchdb-helper';\nimport PouchDBFind from 'pouchdb-find';\nimport { RxStoragePouchStatics } from './pouch-statics';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { addCustomEventsPluginToPouch } from './custom-events-plugin';\nimport { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\n\n\n\nexport class RxStoragePouch implements RxStorage {\n public name: string = RX_STORAGE_NAME_POUCHDB;\n public statics = RxStoragePouchStatics;\n\n constructor(\n public adapter: any,\n public pouchSettings: PouchSettings = {}\n ) {\n checkPouchAdapter(adapter);\n }\n\n private createPouch(\n location: string,\n options: PouchSettings\n ): Promise {\n const pouchDbParameters = {\n location: location,\n adapter: adapterObject(this.adapter),\n settings: options\n };\n const pouchDBOptions = Object.assign(\n {},\n pouchDbParameters.adapter,\n this.pouchSettings,\n pouchDbParameters.settings\n );\n const pouch = new PouchDB(\n pouchDbParameters.location,\n pouchDBOptions\n ) as PouchDBInstance;\n\n /**\n * In the past we found some errors where the PouchDB is not directly usable\n * so we we had to call .info() first to ensure it can be used.\n * I commented this out for now to get faster database/collection creation.\n * We might have to add this again if something fails.\n */\n // await pouch.info();\n\n return Promise.resolve(pouch);\n }\n\n public async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n\n ensureRxStorageInstanceParamsAreCorrect(params);\n\n const pouchLocation = getPouchLocation(\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n const pouch = await this.createPouch(\n pouchLocation,\n params.options\n );\n await createIndexesOnPouch(pouch, params.schema);\n const pouchInstanceId = openPouchId(\n params.databaseInstanceToken,\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n const instance = new RxStorageInstancePouch(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n pouch,\n pouchInstanceId\n },\n params.options\n );\n OPEN_POUCH_INSTANCES.set(\n pouchInstanceId,\n pouch\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_POUCHDB,\n params,\n instance\n );\n\n return instance;\n }\n}\n\n/**\n * Checks if all is ok with the given adapter,\n * else throws an error.\n */\nexport function checkPouchAdapter(adapter: string | any) {\n if (typeof adapter === 'string') {\n if (!(PouchDB as any).adapters || !(PouchDB as any).adapters[adapter]) {\n throw newRxError('DB9', {\n adapter\n });\n }\n } else {\n isLevelDown(adapter);\n if (!(PouchDB as any).adapters || !(PouchDB as any).adapters.leveldb) {\n throw newRxError('DB10', {\n adapter\n });\n }\n }\n}\n\n/**\n * Creates the indexes of the schema inside of the pouchdb instance.\n * Will skip indexes that already exist.\n */\nexport async function createIndexesOnPouch(\n pouch: PouchDBInstance,\n schema: RxJsonSchema\n): Promise {\n if (!schema.indexes) {\n return;\n }\n const primaryKey = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const before = await pouch.getIndexes();\n const existingIndexes: Set = new Set(\n before.indexes.map(idx => idx.name)\n );\n\n await Promise.all(\n schema.indexes.map((indexMaybeArray) => {\n let indexArray: MaybeReadonly = isMaybeReadonlyArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray];\n\n /**\n * replace primary key with _id\n * because that is the enforced primary key on pouchdb.\n */\n indexArray = indexArray.map(key => {\n if (key === primaryKey) {\n return '_id';\n } else {\n return key;\n }\n });\n\n const indexName = getPouchIndexDesignDocNameByIndex(indexArray);\n if (existingIndexes.has(indexName)) {\n // index already exists\n return;\n }\n\n /**\n * TODO we might have even better performance by doing a pouch.bulkDocs()\n * on index creation\n */\n return pouch.createIndex({\n name: indexName,\n ddoc: indexName,\n index: {\n fields: indexArray\n }\n });\n })\n );\n}\n\n/**\n * returns the pouchdb-database-name\n */\nexport function getPouchLocation(\n dbName: string,\n collectionName: string,\n schemaVersion: number\n): string {\n const prefix = dbName + '-rxdb-' + schemaVersion + '-';\n if (!collectionName.includes('/')) {\n return prefix + collectionName;\n } else {\n // if collectionName is a path, we have to prefix the last part only\n const split = collectionName.split('/');\n const last = split.pop();\n\n let ret = split.join('/');\n ret += '/' + prefix + last;\n return ret;\n }\n}\n\n\nexport function getPouchDBOfRxCollection(\n collection: RxCollection\n): PouchDBInstance {\n const id = openPouchId(\n collection.database.token,\n collection.database.name,\n collection.name,\n collection.schema.version\n );\n const pouch = getFromMapOrThrow(OPEN_POUCH_INSTANCES, id);\n return pouch;\n}\n\n\nlet addedRxDBPouchPlugins = false;\n\n/**\n * @deprecated PouchDB RxStorage is deprecated, see\n * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated\n */\nexport function getRxStoragePouch(\n adapter: any,\n pouchSettings?: PouchSettings\n): RxStoragePouch {\n if (!addedRxDBPouchPlugins) {\n addedRxDBPouchPlugins = true;\n addPouchPlugin(PouchDBFind);\n addCustomEventsPluginToPouch();\n }\n\n if (!adapter) {\n throw new Error('adapter missing');\n }\n const storage = new RxStoragePouch(adapter, pouchSettings);\n return storage;\n}\n"],"mappings":"AAWA,SACIA,aAAa,EACbC,iBAAiB,EACjBC,oBAAoB,QACjB,YAAY;AACnB,SACIC,cAAc,EACdC,WAAW,EACXC,OAAO,QACJ,YAAY;AACnB,SAASC,UAAU,QAAQ,gBAAgB;AAE3C,SAASC,sBAAsB,QAAQ,6BAA6B;AACpE,SACIC,iCAAiC,EACjCC,WAAW,EACXC,oBAAoB,EAEpBC,uBAAuB,QACpB,kBAAkB;AACzB,OAAOC,WAAW,MAAM,cAAc;AACtC,SAASC,qBAAqB,QAAQ,iBAAiB;AACvD,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SAASC,4BAA4B,QAAQ,wBAAwB;AACrE,SAASC,gCAAgC,QAAQ,gCAAgC;AACjF,SAASC,uCAAuC,QAAQ,yBAAyB;AAmHjF;AACA;AACA;AACA;AACA,WAAsBC,oBAAoB,YAApBA,oBAAoB,CACtCC,KAAsB,EACtBC,MAAyB;EAAA,IACZ;IACb,IAAI,CAACA,MAAM,CAACC,OAAO,EAAE;MACjB;IACJ;IACA,IAAMC,UAAU,GAAGR,2BAA2B,CAACM,MAAM,CAACE,UAAU,CAAC;IAAC,uBAC7CH,KAAK,CAACI,UAAU,EAAE,iBAAjCC,MAAM;MACZ,IAAMC,eAA4B,GAAG,IAAIC,GAAG,CACxCF,MAAM,CAACH,OAAO,CAACM,GAAG,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACC,IAAI;MAAA,EAAC,CACtC;MAAC,uBAEIC,OAAO,CAACC,GAAG,CACbX,MAAM,CAACC,OAAO,CAACM,GAAG,CAAC,UAACK,eAAe,EAAK;QACpC,IAAIC,UAAmC,GAAG/B,oBAAoB,CAAC8B,eAAe,CAAC,GAAGA,eAAe,GAAG,CAACA,eAAe,CAAC;;QAErH;A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iB,CAACS,oBAAoB,EAAEqE,EAAE,CAAC;EACzD,OAAO5D,KAAK;AAChB;AAGA,IAAI+D,qBAAqB,GAAG,KAAK;;AAEjC;AACA;AACA;AACA;AACA,OAAO,SAASC,iBAAiB,CAC7BzC,OAAY,EACZC,aAA6B,EACf;EACd,IAAI,CAACuC,qBAAqB,EAAE;IACxBA,qBAAqB,GAAG,IAAI;IAC5B/E,cAAc,CAACS,WAAW,CAAC;IAC3BG,4BAA4B,EAAE;EAClC;EAEA,IAAI,CAAC2B,OAAO,EAAE;IACV,MAAM,IAAI0C,KAAK,CAAC,iBAAiB,CAAC;EACtC;EACA,IAAMC,OAAO,GAAG,IAAI5C,cAAc,CAACC,OAAO,EAAEC,aAAa,CAAC;EAC1D,OAAO0C,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/query-builder/index.js b/dist/es/plugins/query-builder/index.js index 81a529fe6d9..a2f83fc1099 100644 --- a/dist/es/plugins/query-builder/index.js +++ b/dist/es/plugins/query-builder/index.js @@ -1,6 +1,6 @@ import { createQueryBuilder, OTHER_MANGO_ATTRIBUTES, OTHER_MANGO_OPERATORS } from './mquery/nosql-query-builder'; import { RxQueryBase, tunnelQueryCache } from '../../rx-query'; -import { clone } from '../../util'; +import { clone } from '../../plugins/utils'; import { runPluginHooks } from '../../hooks'; // if the query-builder plugin is used, we have to save its last path diff --git a/dist/es/plugins/query-builder/index.js.map b/dist/es/plugins/query-builder/index.js.map index e7d5cdf5f3e..612609d8fb5 100644 --- a/dist/es/plugins/query-builder/index.js.map +++ b/dist/es/plugins/query-builder/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["createQueryBuilder","OTHER_MANGO_ATTRIBUTES","OTHER_MANGO_OPERATORS","RxQueryBase","tunnelQueryCache","clone","runPluginHooks","RXQUERY_OTHER_FLAG","runBuildingStep","rxQuery","functionName","value","queryBuilder","mangoQuery","other","_path","queryBuilderJson","toJSON","op","queryObj","query","collection","newQuery","path","tunneled","applyBuildingStep","proto","RxDBQueryBuilderPlugin","name","rxdb","prototypes","RxQuery","forEach","attribute","operator"],"sources":["../../../../src/plugins/query-builder/index.ts"],"sourcesContent":["import {\n createQueryBuilder,\n OTHER_MANGO_ATTRIBUTES,\n OTHER_MANGO_OPERATORS\n} from './mquery/nosql-query-builder';\nimport type { RxPlugin, RxQuery } from '../../types';\nimport { RxQueryBase, tunnelQueryCache } from '../../rx-query';\nimport { clone } from '../../util';\nimport { runPluginHooks } from '../../hooks';\n\n// if the query-builder plugin is used, we have to save its last path\nconst RXQUERY_OTHER_FLAG = 'queryBuilderPath';\n\nexport function runBuildingStep(\n rxQuery: RxQuery,\n functionName: string,\n value: any\n): RxQuery {\n const queryBuilder = createQueryBuilder(clone(rxQuery.mangoQuery));\n if (rxQuery.other[RXQUERY_OTHER_FLAG]) {\n queryBuilder._path = rxQuery.other[RXQUERY_OTHER_FLAG];\n }\n\n (queryBuilder as any)[functionName](value); // run\n\n const queryBuilderJson = queryBuilder.toJSON();\n\n\n runPluginHooks('preCreateRxQuery', {\n op: rxQuery.op,\n queryObj: queryBuilderJson.query,\n collection: rxQuery.collection\n });\n\n\n const newQuery = new RxQueryBase(\n rxQuery.op,\n queryBuilderJson.query,\n rxQuery.collection\n ) as RxQuery;\n\n\n\n if (queryBuilderJson.path) {\n newQuery.other[RXQUERY_OTHER_FLAG] = queryBuilderJson.path;\n }\n\n const tunneled = tunnelQueryCache(newQuery);\n return tunneled;\n}\n\nexport function applyBuildingStep(\n proto: any,\n functionName: string\n): void {\n proto[functionName] = function (this: RxQuery, value: any) {\n return runBuildingStep(this, functionName, value);\n };\n}\n\nexport * from './mquery/nosql-query-builder';\n\nexport const RxDBQueryBuilderPlugin: RxPlugin = {\n name: 'query-builder',\n rxdb: true,\n prototypes: {\n RxQuery(proto: any) {\n [\n 'where',\n 'equals',\n 'eq',\n 'or',\n 'nor',\n 'and',\n 'mod',\n 'exists',\n 'elemMatch',\n 'sort'\n ].forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_ATTRIBUTES.forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_OPERATORS.forEach(operator => {\n applyBuildingStep(proto, operator);\n });\n }\n }\n};\n"],"mappings":"AAAA,SACIA,kBAAkB,EAClBC,sBAAsB,EACtBC,qBAAqB,QAClB,8BAA8B;AAErC,SAASC,WAAW,EAAEC,gBAAgB,QAAQ,gBAAgB;AAC9D,SAASC,KAAK,QAAQ,YAAY;AAClC,SAASC,cAAc,QAAQ,aAAa;;AAE5C;AACA,IAAMC,kBAAkB,GAAG,kBAAkB;AAE7C,OAAO,SAASC,eAAe,CAC3BC,OAA+C,EAC/CC,YAAoB,EACpBC,KAAU,EAC4B;EACtC,IAAMC,YAAY,GAAGZ,kBAAkB,CAACK,KAAK,CAACI,OAAO,CAACI,UAAU,CAAC,CAAC;EAClE,IAAIJ,OAAO,CAACK,KAAK,CAACP,kBAAkB,CAAC,EAAE;IACnCK,YAAY,CAACG,KAAK,GAAGN,OAAO,CAACK,KAAK,CAACP,kBAAkB,CAAC;EAC1D;EAECK,YAAY,CAASF,YAAY,CAAC,CAACC,KAAK,CAAC,CAAC,CAAC;;EAE5C,IAAMK,gBAAgB,GAAGJ,YAAY,CAACK,MAAM,EAAE;EAG9CX,cAAc,CAAC,kBAAkB,EAAE;IAC/BY,EAAE,EAAET,OAAO,CAACS,EAAE;IACdC,QAAQ,EAAEH,gBAAgB,CAACI,KAAK;IAChCC,UAAU,EAAEZ,OAAO,CAACY;EACxB,CAAC,CAAC;EAGF,IAAMC,QAAQ,GAAG,IAAInB,WAAW,CAC5BM,OAAO,CAACS,EAAE,EACVF,gBAAgB,CAACI,KAAK,EACtBX,OAAO,CAACY,UAAU,CACV;EAIZ,IAAIL,gBAAgB,CAACO,IAAI,EAAE;IACvBD,QAAQ,CAACR,KAAK,CAACP,kBAAkB,CAAC,GAAGS,gBAAgB,CAACO,IAAI;EAC9D;EAEA,IAAMC,QAAQ,GAAGpB,gBAAgB,CAACkB,QAAQ,CAAC;EAC3C,OAAOE,QAAQ;AACnB;AAEA,OAAO,SAASC,iBAAiB,CAC7BC,KAAU,EACVhB,YAAoB,EAChB;EACJgB,KAAK,CAAChB,YAAY,CAAC,GAAG,UAAyBC,KAAU,EAAE;IACvD,OAAOH,eAAe,CAAC,IAAI,EAAEE,YAAY,EAAEC,KAAK,CAAC;EACrD,CAAC;AACL;AAEA,cAAc,8BAA8B;AAE5C,OAAO,IAAMgB,sBAAgC,GAAG;EAC5CC,IAAI,EAAE,eAAe;EACrBC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,OAAO,mBAACL,KAAU,EAAE;MAChB,CACI,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,KAAK,EACL,KAAK,EACL,QAAQ,EACR,WAAW,EACX,MAAM,CACT,CAACM,OAAO,CAAC,UAAAC,SAAS,EAAI;QACnBR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACFhC,sBAAsB,CAAC+B,OAAO,CAAC,UAAAC,SAAS,EAAI;QACxCR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACF/B,qBAAqB,CAAC8B,OAAO,CAAC,UAAAE,QAAQ,EAAI;QACtCT,iBAAiB,CAACC,KAAK,EAAEQ,QAAQ,CAAC;MACtC,CAAC,CAAC;IACN;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["createQueryBuilder","OTHER_MANGO_ATTRIBUTES","OTHER_MANGO_OPERATORS","RxQueryBase","tunnelQueryCache","clone","runPluginHooks","RXQUERY_OTHER_FLAG","runBuildingStep","rxQuery","functionName","value","queryBuilder","mangoQuery","other","_path","queryBuilderJson","toJSON","op","queryObj","query","collection","newQuery","path","tunneled","applyBuildingStep","proto","RxDBQueryBuilderPlugin","name","rxdb","prototypes","RxQuery","forEach","attribute","operator"],"sources":["../../../../src/plugins/query-builder/index.ts"],"sourcesContent":["import {\n createQueryBuilder,\n OTHER_MANGO_ATTRIBUTES,\n OTHER_MANGO_OPERATORS\n} from './mquery/nosql-query-builder';\nimport type { RxPlugin, RxQuery } from '../../types';\nimport { RxQueryBase, tunnelQueryCache } from '../../rx-query';\nimport { clone } from '../../plugins/utils';\nimport { runPluginHooks } from '../../hooks';\n\n// if the query-builder plugin is used, we have to save its last path\nconst RXQUERY_OTHER_FLAG = 'queryBuilderPath';\n\nexport function runBuildingStep(\n rxQuery: RxQuery,\n functionName: string,\n value: any\n): RxQuery {\n const queryBuilder = createQueryBuilder(clone(rxQuery.mangoQuery));\n if (rxQuery.other[RXQUERY_OTHER_FLAG]) {\n queryBuilder._path = rxQuery.other[RXQUERY_OTHER_FLAG];\n }\n\n (queryBuilder as any)[functionName](value); // run\n\n const queryBuilderJson = queryBuilder.toJSON();\n\n\n runPluginHooks('preCreateRxQuery', {\n op: rxQuery.op,\n queryObj: queryBuilderJson.query,\n collection: rxQuery.collection\n });\n\n\n const newQuery = new RxQueryBase(\n rxQuery.op,\n queryBuilderJson.query,\n rxQuery.collection\n ) as RxQuery;\n\n\n\n if (queryBuilderJson.path) {\n newQuery.other[RXQUERY_OTHER_FLAG] = queryBuilderJson.path;\n }\n\n const tunneled = tunnelQueryCache(newQuery);\n return tunneled;\n}\n\nexport function applyBuildingStep(\n proto: any,\n functionName: string\n): void {\n proto[functionName] = function (this: RxQuery, value: any) {\n return runBuildingStep(this, functionName, value);\n };\n}\n\nexport * from './mquery/nosql-query-builder';\n\nexport const RxDBQueryBuilderPlugin: RxPlugin = {\n name: 'query-builder',\n rxdb: true,\n prototypes: {\n RxQuery(proto: any) {\n [\n 'where',\n 'equals',\n 'eq',\n 'or',\n 'nor',\n 'and',\n 'mod',\n 'exists',\n 'elemMatch',\n 'sort'\n ].forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_ATTRIBUTES.forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\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C,iBAAiB,CAC7BC,KAAU,EACVhB,YAAoB,EAChB;EACJgB,KAAK,CAAChB,YAAY,CAAC,GAAG,UAAyBC,KAAU,EAAE;IACvD,OAAOH,eAAe,CAAC,IAAI,EAAEE,YAAY,EAAEC,KAAK,CAAC;EACrD,CAAC;AACL;AAEA,cAAc,8BAA8B;AAE5C,OAAO,IAAMgB,sBAAgC,GAAG;EAC5CC,IAAI,EAAE,eAAe;EACrBC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,OAAO,mBAACL,KAAU,EAAE;MAChB,CACI,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,KAAK,EACL,KAAK,EACL,QAAQ,EACR,WAAW,EACX,MAAM,CACT,CAACM,OAAO,CAAC,UAAAC,SAAS,EAAI;QACnBR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACFhC,sBAAsB,CAAC+B,OAAO,CAAC,UAAAC,SAAS,EAAI;QACxCR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACF/B,qBAAqB,CAAC8B,OAAO,CAAC,UAAAE,QAAQ,EAAI;QACtCT,iBAAiB,CAACC,KAAK,EAAEQ,QAAQ,CAAC;MACtC,CAAC,CAAC;IACN;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/query-builder/mquery/nosql-query-builder.js.map b/dist/es/plugins/query-builder/mquery/nosql-query-builder.js.map index e589b54ff2f..5e68fdfff12 100644 --- a/dist/es/plugins/query-builder/mquery/nosql-query-builder.js.map +++ b/dist/es/plugins/query-builder/mquery/nosql-query-builder.js.map @@ -1 +1 @@ -{"version":3,"file":"nosql-query-builder.js","names":["isObject","merge","newRxTypeError","newRxError","NoSqlQueryBuilderClass","mangoQuery","options","_conditions","_fields","queryBuilder","selector","find","limit","skip","sort","forEach","s","where","_path","_val","arguments","length","type","Array","isArray","path","equals","val","_ensurePath","eq","or","array","$or","push","apply","nor","$nor","and","$and","mod","slice","conds","$mod","exists","$exists","elemMatch","_criteria","fn","criteria","$elemMatch","arg","len","i","_pushArr","split","field","ascend","substring","keys","Object","args","source","canMerge","_distinct","method","toJSON","query","mQuerySortToRxDBSort","entries","map","k","v","direction","part","OTHER_MANGO_ATTRIBUTES","prototype","OTHER_MANGO_OPERATORS","$conditional","opts","value","$meta","String","toLowerCase","test","valueStr","toString","replace","parseInt","createQueryBuilder"],"sources":["../../../../../src/plugins/query-builder/mquery/nosql-query-builder.ts"],"sourcesContent":["/**\n * this is based on\n * @link https://github.com/aheckmann/mquery/blob/master/lib/mquery.js\n */\nimport {\n isObject,\n merge\n} from './mquery-utils';\nimport {\n newRxTypeError,\n newRxError\n} from '../../../rx-error';\nimport type {\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n MangoQuerySortDirection\n} from '../../../types';\n\n\ndeclare type MQueryOptions = {\n limit?: number;\n skip?: number;\n sort?: any;\n};\n\nexport class NoSqlQueryBuilderClass {\n\n public options: MQueryOptions = {};\n public _conditions: MangoQuerySelector = {};\n public _fields: any = {};\n public _path?: any;\n private _distinct: any;\n\n /**\n * MQuery constructor used for building queries.\n *\n * ####Example:\n * var query = new MQuery({ name: 'mquery' });\n * query.where('age').gte(21).exec(callback);\n *\n */\n constructor(\n mangoQuery?: MangoQuery\n ) {\n if (mangoQuery) {\n const queryBuilder: NoSqlQueryBuilder = this as any;\n\n if (mangoQuery.selector) {\n queryBuilder.find(mangoQuery.selector);\n }\n if (mangoQuery.limit) {\n queryBuilder.limit(mangoQuery.limit);\n }\n if (mangoQuery.skip) {\n queryBuilder.skip(mangoQuery.skip);\n }\n if (mangoQuery.sort) {\n mangoQuery.sort.forEach(s => queryBuilder.sort(s));\n }\n }\n }\n\n /**\n * Specifies a `path` for use with chaining.\n */\n where(_path: string, _val?: MangoQuerySelector): NoSqlQueryBuilder {\n if (!arguments.length) return this as any;\n const type = typeof arguments[0];\n if ('string' === type) {\n this._path = arguments[0];\n if (2 === arguments.length) {\n this._conditions[this._path] = arguments[1];\n }\n return this as any;\n }\n\n if ('object' === type && !Array.isArray(arguments[0])) {\n return this.merge(arguments[0]);\n }\n\n throw newRxTypeError('MQ1', {\n path: arguments[0]\n });\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * ####Example\n * User.where('age').equals(49);\n */\n equals(val: any): NoSqlQueryBuilder {\n this._ensurePath('equals');\n const path = this._path;\n this._conditions[path] = val;\n return this as any;\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * This is alias of `equals`\n */\n eq(val: any): NoSqlQueryBuilder {\n this._ensurePath('eq');\n const path = this._path;\n this._conditions[path] = val;\n return this as any;\n }\n\n /**\n * Specifies arguments for an `$or` condition.\n * ####Example\n * query.or([{ color: 'red' }, { status: 'emergency' }])\n */\n or(array: any[]): NoSqlQueryBuilder {\n const or = this._conditions.$or || (this._conditions.$or = []);\n if (!Array.isArray(array)) array = [array];\n or.push.apply(or, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$nor` condition.\n * ####Example\n * query.nor([{ color: 'green' }, { status: 'ok' }])\n */\n nor(array: any[]): NoSqlQueryBuilder {\n const nor = this._conditions.$nor || (this._conditions.$nor = []);\n if (!Array.isArray(array)) array = [array];\n nor.push.apply(nor, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$and` condition.\n * ####Example\n * query.and([{ color: 'green' }, { status: 'ok' }])\n * @see $and http://docs.mongodb.org/manual/reference/operator/and/\n */\n and(array: any[]): NoSqlQueryBuilder {\n const and = this._conditions.$and || (this._conditions.$and = []);\n if (!Array.isArray(array)) array = [array];\n and.push.apply(and, array);\n return this as any;\n }\n\n /**\n * Specifies a `$mod` condition\n */\n mod(_path: string, _val: number): NoSqlQueryBuilder {\n let val;\n let path;\n\n if (1 === arguments.length) {\n this._ensurePath('mod');\n val = arguments[0];\n path = this._path;\n } else if (2 === arguments.length && !Array.isArray(arguments[1])) {\n this._ensurePath('mod');\n val = (arguments as any).slice();\n path = this._path;\n } else if (3 === arguments.length) {\n val = (arguments as any).slice(1);\n path = arguments[0];\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$mod = val;\n return this as any;\n }\n\n /**\n * Specifies an `$exists` condition\n * ####Example\n * // { name: { $exists: true }}\n * Thing.where('name').exists()\n * Thing.where('name').exists(true)\n * Thing.find().exists('name')\n */\n exists(_path: string, _val: number): NoSqlQueryBuilder {\n let path;\n let val;\n if (0 === arguments.length) {\n this._ensurePath('exists');\n path = this._path;\n val = true;\n } else if (1 === arguments.length) {\n if ('boolean' === typeof arguments[0]) {\n this._ensurePath('exists');\n path = this._path;\n val = arguments[0];\n } else {\n path = arguments[0];\n val = true;\n }\n } else if (2 === arguments.length) {\n path = arguments[0];\n val = arguments[1];\n }\n\n const conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$exists = val;\n return this as any;\n }\n\n /**\n * Specifies an `$elemMatch` condition\n * ####Example\n * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})\n * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n * query.elemMatch('comment', function (elem) {\n * elem.where('author').equals('autobot');\n * elem.where('votes').gte(5);\n * })\n * query.where('comment').elemMatch(function (elem) {\n * elem.where({ author: 'autobot' });\n * elem.where('votes').gte(5);\n * })\n */\n elemMatch(_path: string, _criteria: any): NoSqlQueryBuilder {\n if (null === arguments[0])\n throw newRxTypeError('MQ2');\n\n let fn;\n let path;\n let criteria;\n\n if ('function' === typeof arguments[0]) {\n this._ensurePath('elemMatch');\n path = this._path;\n fn = arguments[0];\n } else if (isObject(arguments[0])) {\n this._ensurePath('elemMatch');\n path = this._path;\n criteria = arguments[0];\n } else if ('function' === typeof arguments[1]) {\n path = arguments[0];\n fn = arguments[1];\n } else if (arguments[1] && isObject(arguments[1])) {\n path = arguments[0];\n criteria = arguments[1];\n } else\n throw newRxTypeError('MQ2');\n\n if (fn) {\n criteria = new NoSqlQueryBuilderClass;\n fn(criteria);\n criteria = criteria._conditions;\n }\n\n const conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$elemMatch = criteria;\n return this as any;\n }\n\n /**\n * Sets the sort order\n * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.\n * If a string is passed, it must be a space delimited list of path names.\n * The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n * ####Example\n * query.sort({ field: 'asc', test: -1 });\n * query.sort('field -test');\n * query.sort([['field', 1], ['test', -1]]);\n */\n sort(arg: any): NoSqlQueryBuilder {\n if (!arg) return this as any;\n let len;\n const type = typeof arg;\n // .sort([['field', 1], ['test', -1]])\n if (Array.isArray(arg)) {\n len = arg.length;\n for (let i = 0; i < arg.length; ++i) {\n _pushArr(this.options, arg[i][0], arg[i][1]);\n }\n\n return this as any;\n }\n\n // .sort('field -test')\n if (1 === arguments.length && 'string' === type) {\n arg = arg.split(/\\s+/);\n len = arg.length;\n for (let i = 0; i < len; ++i) {\n let field = arg[i];\n if (!field) continue;\n const ascend = '-' === field[0] ? -1 : 1;\n if (ascend === -1) field = field.substring(1);\n push(this.options, field, ascend);\n }\n\n return this as any;\n }\n\n // .sort({ field: 1, test: -1 })\n if (isObject(arg)) {\n const keys = Object.keys(arg);\n keys.forEach(field => push(this.options, field, arg[field]));\n return this as any;\n }\n\n throw newRxTypeError('MQ3', {\n args: arguments\n });\n }\n\n /**\n * Merges another MQuery or conditions object into this one.\n *\n * When a MQuery is passed, conditions, field selection and options are merged.\n *\n */\n merge(source: any): NoSqlQueryBuilder {\n if (!source) {\n return this as any;\n }\n\n if (!canMerge(source)) {\n throw newRxTypeError('MQ4', {\n source\n });\n }\n\n if (source instanceof NoSqlQueryBuilderClass) {\n // if source has a feature, apply it to ourselves\n\n if (source._conditions)\n merge(this._conditions, source._conditions);\n\n if (source._fields) {\n if (!this._fields) this._fields = {};\n merge(this._fields, source._fields);\n }\n\n if (source.options) {\n if (!this.options) this.options = {};\n merge(this.options, source.options);\n }\n\n if (source._distinct)\n this._distinct = source._distinct;\n\n return this as any;\n }\n\n // plain object\n merge(this._conditions, source);\n\n return this as any;\n }\n\n /**\n * Finds documents.\n * ####Example\n * query.find()\n * query.find({ name: 'Burning Lights' })\n */\n find(criteria: any): NoSqlQueryBuilder {\n if (canMerge(criteria)) {\n this.merge(criteria);\n }\n\n return this as any;\n }\n\n /**\n * Make sure _path is set.\n *\n * @parmam {String} method\n */\n _ensurePath(method: any) {\n if (!this._path) {\n throw newRxError('MQ5', {\n method\n });\n }\n }\n\n toJSON(): {\n query: MangoQuery;\n path?: string;\n } {\n const query: MangoQuery = {\n selector: this._conditions,\n };\n\n if (this.options.skip) {\n query.skip = this.options.skip;\n }\n if (this.options.limit) {\n query.limit = this.options.limit;\n }\n if (this.options.sort) {\n query.sort = mQuerySortToRxDBSort(this.options.sort);\n }\n\n return {\n query,\n path: this._path\n };\n }\n}\n\nexport function mQuerySortToRxDBSort(\n sort: { [k: string]: 1 | -1; }\n): MangoQuerySortPart[] {\n return Object.entries(sort).map(([k, v]) => {\n const direction: MangoQuerySortDirection = v === 1 ? 'asc' : 'desc';\n const part: MangoQuerySortPart = { [k]: direction } as any;\n return part;\n });\n}\n\n/**\n * Because some prototype-methods are generated,\n * we have to define the type of NoSqlQueryBuilder here\n */\n\nexport interface NoSqlQueryBuilder extends NoSqlQueryBuilderClass {\n maxScan: ReturnSelfNumberFunction;\n batchSize: ReturnSelfNumberFunction;\n limit: ReturnSelfNumberFunction;\n skip: ReturnSelfNumberFunction;\n comment: ReturnSelfFunction;\n\n gt: ReturnSelfFunction;\n gte: ReturnSelfFunction;\n lt: ReturnSelfFunction;\n lte: ReturnSelfFunction;\n ne: ReturnSelfFunction;\n in: ReturnSelfFunction;\n nin: ReturnSelfFunction;\n all: ReturnSelfFunction;\n regex: ReturnSelfFunction;\n size: ReturnSelfFunction;\n\n}\n\ndeclare type ReturnSelfFunction = (v: any) => NoSqlQueryBuilder;\ndeclare type ReturnSelfNumberFunction = (v: number | null) => NoSqlQueryBuilder;\n\n/**\n * limit, skip, maxScan, batchSize, comment\n *\n * Sets these associated options.\n *\n * query.comment('feed query');\n */\nexport const OTHER_MANGO_ATTRIBUTES = ['limit', 'skip', 'maxScan', 'batchSize', 'comment'];\nOTHER_MANGO_ATTRIBUTES.forEach(function (method) {\n (NoSqlQueryBuilderClass.prototype as any)[method] = function (v: any) {\n this.options[method] = v;\n return this;\n };\n});\n\n\n/**\n * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance\n *\n * Thing.where('type').nin(array)\n */\nexport const OTHER_MANGO_OPERATORS = [\n 'gt', 'gte', 'lt', 'lte', 'ne',\n 'in', 'nin', 'all', 'regex', 'size'\n];\nOTHER_MANGO_OPERATORS.forEach(function ($conditional) {\n (NoSqlQueryBuilderClass.prototype as any)[$conditional] = function () {\n let path;\n let val;\n if (1 === arguments.length) {\n this._ensurePath($conditional);\n val = arguments[0];\n path = this._path;\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ?\n this._conditions[path] :\n (this._conditions[path] = {});\n conds['$' + $conditional] = val;\n return this;\n };\n});\n\n\nfunction push(opts: any, field: string, value: any) {\n if (Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ6', {\n opts,\n field,\n value\n });\n }\n\n if (value && value.$meta) {\n const sort = opts.sort || (opts.sort = {});\n sort[field] = {\n $meta: value.$meta\n };\n return;\n }\n\n const val = String(value || 1).toLowerCase();\n if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {\n if (Array.isArray(value)) value = '[' + value + ']';\n throw newRxTypeError('MQ7', {\n field,\n value\n });\n }\n // store `sort` in a sane format\n const s = opts.sort || (opts.sort = {});\n const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');\n s[field] = parseInt(valueStr, 10);\n}\n\nfunction _pushArr(opts: any, field: string, value: any) {\n opts.sort = opts.sort || [];\n if (!Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ8', {\n opts,\n field,\n value\n });\n }\n\n /* const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');*/\n opts.sort.push([field, value]);\n}\n\n\n/**\n * Determines if `conds` can be merged using `mquery().merge()`\n */\nexport function canMerge(conds: any): boolean {\n return conds instanceof NoSqlQueryBuilderClass || isObject(conds);\n}\n\n\nexport function createQueryBuilder(query?: MangoQuery): NoSqlQueryBuilder {\n return new NoSqlQueryBuilderClass(query) as NoSqlQueryBuilder;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,SACIA,QAAQ,EACRC,KAAK,IAALA,MAAK,QACF,gBAAgB;AACvB,SACIC,cAAc,EACdC,UAAU,QACP,mBAAmB;AAe1B,WAAaC,sBAAsB;EAQ/B;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACI,gCACIC,UAAgC,EAClC;IAAA,KAhBKC,OAAO,GAAkB,CAAC,CAAC;IAAA,KAC3BC,WAAW,GAAgC,CAAC,CAAC;IAAA,KAC7CC,OAAO,GAAQ,CAAC,CAAC;IAepB,IAAIH,UAAU,EAAE;MACZ,IAAMI,YAAwC,GAAG,IAAW;MAE5D,IAAIJ,UAAU,CAACK,QAAQ,EAAE;QACrBD,YAAY,CAACE,IAAI,CAACN,UAAU,CAACK,QAAQ,CAAC;MAC1C;MACA,IAAIL,UAAU,CAACO,KAAK,EAAE;QAClBH,YAAY,CAACG,KAAK,CAACP,UAAU,CAACO,KAAK,CAAC;MACxC;MACA,IAAIP,UAAU,CAACQ,IAAI,EAAE;QACjBJ,YAAY,CAACI,IAAI,CAACR,UAAU,CAACQ,IAAI,CAAC;MACtC;MACA,IAAIR,UAAU,CAACS,IAAI,EAAE;QACjBT,UAAU,CAACS,IAAI,CAACC,OAAO,CAAC,UAAAC,CAAC;UAAA,OAAIP,YAAY,CAACK,I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,CAAC,KAAK,EAAE,GAAG,CAAC,CACnBA,OAAO,CAAC,WAAW,EAAE,GAAG,CAAC,CACzBA,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CACrBA,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC;EAChCtE,CAAC,CAACuC,KAAK,CAAC,GAAGgC,QAAQ,CAACH,QAAQ,EAAE,EAAE,CAAC;AACrC;AAEA,SAAS/B,QAAQ,CAACyB,IAAS,EAAEvB,KAAa,EAAEwB,KAAU,EAAE;EACpDD,IAAI,CAAChE,IAAI,GAAGgE,IAAI,CAAChE,IAAI,IAAI,EAAE;EAC3B,IAAI,CAACS,KAAK,CAACC,OAAO,CAACsD,IAAI,CAAChE,IAAI,CAAC,EAAE;IAC3B,MAAMZ,cAAc,CAAC,KAAK,EAAE;MACxB4E,IAAI,EAAJA,IAAI;MACJvB,KAAK,EAALA,KAAK;MACLwB,KAAK,EAALA;IACJ,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;AACA;EACID,IAAI,CAAChE,IAAI,CAACmB,IAAI,CAAC,CAACsB,KAAK,EAAEwB,KAAK,CAAC,CAAC;AAClC;;AAGA;AACA;AACA;AACA,OAAO,SAASjB,QAAQ,CAACrB,KAAU,EAAW;EAC1C,OAAOA,KAAK,YAAYrC,sBAAsB,IAAIJ,QAAQ,CAACyC,KAAK,CAAC;AACrE;AAGA,OAAO,SAAS+C,kBAAkB,CAAUtB,KAA2B,EAA8B;EACjG,OAAO,IAAI9D,sBAAsB,CAAC8D,KAAK,CAAC;AAC5C"} \ No newline at end of file +{"version":3,"file":"nosql-query-builder.js","names":["isObject","merge","newRxTypeError","newRxError","NoSqlQueryBuilderClass","mangoQuery","options","_conditions","_fields","queryBuilder","selector","find","limit","skip","sort","forEach","s","where","_path","_val","arguments","length","type","Array","isArray","path","equals","val","_ensurePath","eq","or","array","$or","push","apply","nor","$nor","and","$and","mod","slice","conds","$mod","exists","$exists","elemMatch","_criteria","fn","criteria","$elemMatch","arg","len","i","_pushArr","split","field","ascend","substring","keys","Object","args","source","canMerge","_distinct","method","toJSON","query","mQuerySortToRxDBSort","entries","map","k","v","direction","part","OTHER_MANGO_ATTRIBUTES","prototype","OTHER_MANGO_OPERATORS","$conditional","opts","value","$meta","String","toLowerCase","test","valueStr","toString","replace","parseInt","createQueryBuilder"],"sources":["../../../../../src/plugins/query-builder/mquery/nosql-query-builder.ts"],"sourcesContent":["/**\n * this is based on\n * @link https://github.com/aheckmann/mquery/blob/master/lib/mquery.js\n */\nimport {\n isObject,\n merge\n} from './mquery-utils';\nimport {\n newRxTypeError,\n newRxError\n} from '../../../rx-error';\nimport type {\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n MangoQuerySortDirection\n} from '../../../types';\n\n\ndeclare type MQueryOptions = {\n limit?: number;\n skip?: number;\n sort?: any;\n};\n\nexport class NoSqlQueryBuilderClass {\n\n public options: MQueryOptions = {};\n public _conditions: MangoQuerySelector = {};\n public _fields: any = {};\n public _path?: any;\n private _distinct: any;\n\n /**\n * MQuery constructor used for building queries.\n *\n * ####Example:\n * var query = new MQuery({ name: 'mquery' });\n * query.where('age').gte(21).exec(callback);\n *\n */\n constructor(\n mangoQuery?: MangoQuery\n ) {\n if (mangoQuery) {\n const queryBuilder: NoSqlQueryBuilder = this as any;\n\n if (mangoQuery.selector) {\n queryBuilder.find(mangoQuery.selector);\n }\n if (mangoQuery.limit) {\n queryBuilder.limit(mangoQuery.limit);\n }\n if (mangoQuery.skip) {\n queryBuilder.skip(mangoQuery.skip);\n }\n if (mangoQuery.sort) {\n mangoQuery.sort.forEach(s => queryBuilder.sort(s));\n }\n }\n }\n\n /**\n * Specifies a `path` for use with chaining.\n */\n where(_path: string, _val?: MangoQuerySelector): NoSqlQueryBuilder {\n if (!arguments.length) return this as any;\n const type = typeof arguments[0];\n if ('string' === type) {\n this._path = arguments[0];\n if (2 === arguments.length) {\n (this._conditions as any)[this._path] = arguments[1];\n }\n return this as any;\n }\n\n if ('object' === type && !Array.isArray(arguments[0])) {\n return this.merge(arguments[0]);\n }\n\n throw newRxTypeError('MQ1', {\n path: arguments[0]\n });\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * ####Example\n * User.where('age').equals(49);\n */\n equals(val: any): NoSqlQueryBuilder {\n this._ensurePath('equals');\n const path = this._path;\n (this._conditions as any)[path] = val;\n return this as any;\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * This is alias of `equals`\n */\n eq(val: any): NoSqlQueryBuilder {\n this._ensurePath('eq');\n const path = this._path;\n (this._conditions as any)[path] = val;\n return this as any;\n }\n\n /**\n * Specifies arguments for an `$or` condition.\n * ####Example\n * query.or([{ color: 'red' }, { status: 'emergency' }])\n */\n or(array: any[]): NoSqlQueryBuilder {\n const or = this._conditions.$or || (this._conditions.$or = []);\n if (!Array.isArray(array)) array = [array];\n or.push.apply(or, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$nor` condition.\n * ####Example\n * query.nor([{ color: 'green' }, { status: 'ok' }])\n */\n nor(array: any[]): NoSqlQueryBuilder {\n const nor = this._conditions.$nor || (this._conditions.$nor = []);\n if (!Array.isArray(array)) array = [array];\n nor.push.apply(nor, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$and` condition.\n * ####Example\n * query.and([{ color: 'green' }, { status: 'ok' }])\n * @see $and http://docs.mongodb.org/manual/reference/operator/and/\n */\n and(array: any[]): NoSqlQueryBuilder {\n const and = this._conditions.$and || (this._conditions.$and = []);\n if (!Array.isArray(array)) array = [array];\n and.push.apply(and, array);\n return this as any;\n }\n\n /**\n * Specifies a `$mod` condition\n */\n mod(_path: string, _val: number): NoSqlQueryBuilder {\n let val;\n let path;\n\n if (1 === arguments.length) {\n this._ensurePath('mod');\n val = arguments[0];\n path = this._path;\n } else if (2 === arguments.length && !Array.isArray(arguments[1])) {\n this._ensurePath('mod');\n val = (arguments as any).slice();\n path = this._path;\n } else if (3 === arguments.length) {\n val = (arguments as any).slice(1);\n path = arguments[0];\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = (this._conditions as any)[path] || ((this._conditions as any)[path] = {});\n conds.$mod = val;\n return this as any;\n }\n\n /**\n * Specifies an `$exists` condition\n * ####Example\n * // { name: { $exists: true }}\n * Thing.where('name').exists()\n * Thing.where('name').exists(true)\n * Thing.find().exists('name')\n */\n exists(_path: string, _val: number): NoSqlQueryBuilder {\n let path;\n let val;\n if (0 === arguments.length) {\n this._ensurePath('exists');\n path = this._path;\n val = true;\n } else if (1 === arguments.length) {\n if ('boolean' === typeof arguments[0]) {\n this._ensurePath('exists');\n path = this._path;\n val = arguments[0];\n } else {\n path = arguments[0];\n val = true;\n }\n } else if (2 === arguments.length) {\n path = arguments[0];\n val = arguments[1];\n }\n\n const conds = (this._conditions as any)[path] || ((this._conditions as any)[path] = {});\n conds.$exists = val;\n return this as any;\n }\n\n /**\n * Specifies an `$elemMatch` condition\n * ####Example\n * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})\n * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n * query.elemMatch('comment', function (elem) {\n * elem.where('author').equals('autobot');\n * elem.where('votes').gte(5);\n * })\n * query.where('comment').elemMatch(function (elem) {\n * elem.where({ author: 'autobot' });\n * elem.where('votes').gte(5);\n * })\n */\n elemMatch(_path: string, _criteria: any): NoSqlQueryBuilder {\n if (null === arguments[0])\n throw newRxTypeError('MQ2');\n\n let fn;\n let path;\n let criteria;\n\n if ('function' === typeof arguments[0]) {\n this._ensurePath('elemMatch');\n path = this._path;\n fn = arguments[0];\n } else if (isObject(arguments[0])) {\n this._ensurePath('elemMatch');\n path = this._path;\n criteria = arguments[0];\n } else if ('function' === typeof arguments[1]) {\n path = arguments[0];\n fn = arguments[1];\n } else if (arguments[1] && isObject(arguments[1])) {\n path = arguments[0];\n criteria = arguments[1];\n } else\n throw newRxTypeError('MQ2');\n\n if (fn) {\n criteria = new NoSqlQueryBuilderClass;\n fn(criteria);\n criteria = criteria._conditions;\n }\n\n const conds = (this._conditions as any)[path] || ((this._conditions as any)[path] = {});\n conds.$elemMatch = criteria;\n return this as any;\n }\n\n /**\n * Sets the sort order\n * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.\n * If a string is passed, it must be a space delimited list of path names.\n * The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n * ####Example\n * query.sort({ field: 'asc', test: -1 });\n * query.sort('field -test');\n * query.sort([['field', 1], ['test', -1]]);\n */\n sort(arg: any): NoSqlQueryBuilder {\n if (!arg) return this as any;\n let len;\n const type = typeof arg;\n // .sort([['field', 1], ['test', -1]])\n if (Array.isArray(arg)) {\n len = arg.length;\n for (let i = 0; i < arg.length; ++i) {\n _pushArr(this.options, arg[i][0], arg[i][1]);\n }\n\n return this as any;\n }\n\n // .sort('field -test')\n if (1 === arguments.length && 'string' === type) {\n arg = arg.split(/\\s+/);\n len = arg.length;\n for (let i = 0; i < len; ++i) {\n let field = arg[i];\n if (!field) continue;\n const ascend = '-' === field[0] ? -1 : 1;\n if (ascend === -1) field = field.substring(1);\n push(this.options, field, ascend);\n }\n\n return this as any;\n }\n\n // .sort({ field: 1, test: -1 })\n if (isObject(arg)) {\n const keys = Object.keys(arg);\n keys.forEach(field => push(this.options, field, arg[field]));\n return this as any;\n }\n\n throw newRxTypeError('MQ3', {\n args: arguments\n });\n }\n\n /**\n * Merges another MQuery or conditions object into this one.\n *\n * When a MQuery is passed, conditions, field selection and options are merged.\n *\n */\n merge(source: any): NoSqlQueryBuilder {\n if (!source) {\n return this as any;\n }\n\n if (!canMerge(source)) {\n throw newRxTypeError('MQ4', {\n source\n });\n }\n\n if (source instanceof NoSqlQueryBuilderClass) {\n // if source has a feature, apply it to ourselves\n\n if (source._conditions)\n merge(this._conditions, source._conditions);\n\n if (source._fields) {\n if (!this._fields) this._fields = {};\n merge(this._fields, source._fields);\n }\n\n if (source.options) {\n if (!this.options) this.options = {};\n merge(this.options, source.options);\n }\n\n if (source._distinct)\n this._distinct = source._distinct;\n\n return this as any;\n }\n\n // plain object\n merge(this._conditions, source);\n\n return this as any;\n }\n\n /**\n * Finds documents.\n * ####Example\n * query.find()\n * query.find({ name: 'Burning Lights' })\n */\n find(criteria: any): NoSqlQueryBuilder {\n if (canMerge(criteria)) {\n this.merge(criteria);\n }\n\n return this as any;\n }\n\n /**\n * Make sure _path is set.\n *\n * @parmam {String} method\n */\n _ensurePath(method: any) {\n if (!this._path) {\n throw newRxError('MQ5', {\n method\n });\n }\n }\n\n toJSON(): {\n query: MangoQuery;\n path?: string;\n } {\n const query: MangoQuery = {\n selector: this._conditions,\n };\n\n if (this.options.skip) {\n query.skip = this.options.skip;\n }\n if (this.options.limit) {\n query.limit = this.options.limit;\n }\n if (this.options.sort) {\n query.sort = mQuerySortToRxDBSort(this.options.sort);\n }\n\n return {\n query,\n path: this._path\n };\n }\n}\n\nexport function mQuerySortToRxDBSort(\n sort: { [k: string]: 1 | -1; }\n): MangoQuerySortPart[] {\n return Object.entries(sort).map(([k, v]) => {\n const direction: MangoQuerySortDirection = v === 1 ? 'asc' : 'desc';\n const part: MangoQuerySortPart = { [k]: direction } as any;\n return part;\n });\n}\n\n/**\n * Because some prototype-methods are generated,\n * we have to define the type of NoSqlQueryBuilder here\n */\n\nexport interface NoSqlQueryBuilder extends NoSqlQueryBuilderClass {\n maxScan: ReturnSelfNumberFunction;\n batchSize: ReturnSelfNumberFunction;\n limit: ReturnSelfNumberFunction;\n skip: ReturnSelfNumberFunction;\n comment: ReturnSelfFunction;\n\n gt: ReturnSelfFunction;\n gte: ReturnSelfFunction;\n lt: ReturnSelfFunction;\n lte: ReturnSelfFunction;\n ne: ReturnSelfFunction;\n in: ReturnSelfFunction;\n nin: ReturnSelfFunction;\n all: ReturnSelfFunction;\n regex: ReturnSelfFunction;\n size: ReturnSelfFunction;\n\n}\n\ndeclare type ReturnSelfFunction = (v: any) => NoSqlQueryBuilder;\ndeclare type ReturnSelfNumberFunction = (v: number | null) => NoSqlQueryBuilder;\n\n/**\n * limit, skip, maxScan, batchSize, comment\n *\n * Sets these associated options.\n *\n * query.comment('feed query');\n */\nexport const OTHER_MANGO_ATTRIBUTES = ['limit', 'skip', 'maxScan', 'batchSize', 'comment'];\nOTHER_MANGO_ATTRIBUTES.forEach(function (method) {\n (NoSqlQueryBuilderClass.prototype as any)[method] = function (v: any) {\n this.options[method] = v;\n return this;\n };\n});\n\n\n/**\n * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance\n *\n * Thing.where('type').nin(array)\n */\nexport const OTHER_MANGO_OPERATORS = [\n 'gt', 'gte', 'lt', 'lte', 'ne',\n 'in', 'nin', 'all', 'regex', 'size'\n];\nOTHER_MANGO_OPERATORS.forEach(function ($conditional) {\n (NoSqlQueryBuilderClass.prototype as any)[$conditional] = function () {\n let path;\n let val;\n if (1 === arguments.length) {\n this._ensurePath($conditional);\n val = arguments[0];\n path = this._path;\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ?\n this._conditions[path] :\n (this._conditions[path] = {});\n conds['$' + $conditional] = val;\n return this;\n };\n});\n\n\nfunction push(opts: any, field: string, value: any) {\n if (Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ6', {\n opts,\n field,\n value\n });\n }\n\n if (value && value.$meta) {\n const sort = opts.sort || (opts.sort = {});\n sort[field] = {\n $meta: value.$meta\n };\n return;\n }\n\n const val = String(value || 1).toLowerCase();\n if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {\n if (Array.isArray(value)) value = '[' + value + ']';\n throw newRxTypeError('MQ7', {\n field,\n value\n });\n }\n // store `sort` in a sane format\n const s = opts.sort || (opts.sort = {});\n const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');\n s[field] = parseInt(valueStr, 10);\n}\n\nfunction _pushArr(opts: any, field: string, value: any) {\n opts.sort = opts.sort || [];\n if (!Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ8', {\n opts,\n field,\n value\n });\n }\n\n /* const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');*/\n opts.sort.push([field, value]);\n}\n\n\n/**\n * Determines if `conds` can be merged using `mquery().merge()`\n */\nexport function canMerge(conds: any): boolean {\n return conds instanceof NoSqlQueryBuilderClass || isObject(conds);\n}\n\n\nexport function createQueryBuilder(query?: MangoQuery): NoSqlQueryBuilder {\n return new NoSqlQueryBuilderClass(query) as NoSqlQueryBuilder;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,SACIA,QAAQ,EACRC,KAAK,IAALA,MAAK,QACF,gBAAgB;AACvB,SACIC,cAAc,EACdC,UAAU,QACP,mBAAmB;AAe1B,WAAaC,sBAAsB;EAQ/B;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;EACI,gCACIC,UAAgC,EAClC;IAAA,KAhBKC,OAAO,GAAkB,CAAC,CAAC;IAAA,KAC3BC,WAAW,GAAgC,CAAC,CAAC;IAAA,KAC7CC,OAAO,GAAQ,CAAC,CAAC;IAepB,IAAIH,UAAU,EAAE;MACZ,IAAMI,YAAwC,GAAG,IAAW;MAE5D,IAAIJ,UAAU,CAACK,QAAQ,EAAE;QACrBD,YAAY,CAACE,IAAI,CAACN,UAAU,CAACK,QAAQ,CAAC;MAC1C;MACA,IAAIL,UAAU,CAACO,KAAK,EAAE;QAClBH,YAAY,CAACG,KAAK,CAACP,UAAU,CAACO,KAAK,CAAC;MACxC;MACA,IAAIP,UAAU,CAACQ,IAAI,EAAE;QACjBJ,YAAY,CAACI,IAAI,CAACR,UAAU,CAACQ,IAAI,CAAC;MACtC;MACA,IAAIR,UAAU,CAACS,IAAI,EAAE;QACjBT,UAAU,CAACS,IAAI,CAACC,OAAO,CAAC,UAAAC,CAAC;UAAA,OAAIP,YAAY,CAACK,IAAI,CAACE,CAAC,CAAC;QAAA,EAAC;MACtD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,CAAC,WAAW,EAAE,GAAG,CAAC,CACzBA,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CACrBA,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC;EAChCtE,CAAC,CAACuC,KAAK,CAAC,GAAGgC,QAAQ,CAACH,QAAQ,EAAE,EAAE,CAAC;AACrC;AAEA,SAAS/B,QAAQ,CAACyB,IAAS,EAAEvB,KAAa,EAAEwB,KAAU,EAAE;EACpDD,IAAI,CAAChE,IAAI,GAAGgE,IAAI,CAAChE,IAAI,IAAI,EAAE;EAC3B,IAAI,CAACS,KAAK,CAACC,OAAO,CAACsD,IAAI,CAAChE,IAAI,CAAC,EAAE;IAC3B,MAAMZ,cAAc,CAAC,KAAK,EAAE;MACxB4E,IAAI,EAAJA,IAAI;MACJvB,KAAK,EAALA,KAAK;MACLwB,KAAK,EAALA;IACJ,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;AACA;EACID,IAAI,CAAChE,IAAI,CAACmB,IAAI,CAAC,CAACsB,KAAK,EAAEwB,KAAK,CAAC,CAAC;AAClC;;AAGA;AACA;AACA;AACA,OAAO,SAASjB,QAAQ,CAACrB,KAAU,EAAW;EAC1C,OAAOA,KAAK,YAAYrC,sBAAsB,IAAIJ,QAAQ,CAACyC,KAAK,CAAC;AACrE;AAGA,OAAO,SAAS+C,kBAAkB,CAAUtB,KAA2B,EAA8B;EACjG,OAAO,IAAI9D,sBAAsB,CAAC8D,KAAK,CAAC;AAC5C"} \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb-new/couchdb-helper.js b/dist/es/plugins/replication-couchdb-new/couchdb-helper.js deleted file mode 100644 index 08ead311af4..00000000000 --- a/dist/es/plugins/replication-couchdb-new/couchdb-helper.js +++ /dev/null @@ -1,21 +0,0 @@ -import { pouchSwapIdToPrimary } from '../pouchdb'; -export var COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-'; -export function mergeUrlQueryParams(params) { - return Object.entries(params).filter(function (_ref) { - var _k = _ref[0], - value = _ref[1]; - return typeof value !== 'undefined'; - }).map(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; - return key + '=' + value; - }).join('&'); -} -export function couchDBDocToRxDocData(primaryPath, couchDocData) { - var doc = pouchSwapIdToPrimary(primaryPath, couchDocData); - - // ensure deleted flag is set. - doc._deleted = !!doc._deleted; - return doc; -} -//# sourceMappingURL=couchdb-helper.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb-new/couchdb-helper.js.map b/dist/es/plugins/replication-couchdb-new/couchdb-helper.js.map deleted file mode 100644 index dd6c28b3d6d..00000000000 --- a/dist/es/plugins/replication-couchdb-new/couchdb-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"couchdb-helper.js","names":["pouchSwapIdToPrimary","COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","mergeUrlQueryParams","params","Object","entries","filter","_k","value","map","key","join","couchDBDocToRxDocData","primaryPath","couchDocData","doc","_deleted"],"sources":["../../../../src/plugins/replication-couchdb-new/couchdb-helper.ts"],"sourcesContent":["import { WithDeleted } from '../../types';\nimport { pouchSwapIdToPrimary } from '../pouchdb';\nimport { URLQueryParams } from './couchdb-types';\n\n\nexport const COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-';\n\n\nexport function mergeUrlQueryParams(\n params: URLQueryParams\n): string {\n return Object.entries(params)\n .filter(([_k, value]) => typeof value !== 'undefined')\n .map(([key, value]) => key + '=' + value)\n .join('&');\n}\n\nexport function couchDBDocToRxDocData(\n primaryPath: string,\n couchDocData: any\n): WithDeleted {\n const doc = pouchSwapIdToPrimary(primaryPath, couchDocData);\n\n // ensure deleted flag is set.\n doc._deleted = !!doc._deleted;\n\n return doc;\n}\n"],"mappings":"AACA,SAASA,oBAAoB,QAAQ,YAAY;AAIjD,OAAO,IAAMC,8CAA8C,GAAG,2BAA2B;AAGzF,OAAO,SAASC,mBAAmB,CAC/BC,MAAsB,EAChB;EACN,OAAOC,MAAM,CAACC,OAAO,CAACF,MAAM,CAAC,CACxBG,MAAM,CAAC;IAAA,IAAEC,EAAE;MAAEC,KAAK;IAAA,OAAM,OAAOA,KAAK,KAAK,WAAW;EAAA,EAAC,CACrDC,GAAG,CAAC;IAAA,IAAEC,GAAG;MAAEF,KAAK;IAAA,OAAME,GAAG,GAAG,GAAG,GAAGF,KAAK;EAAA,EAAC,CACxCG,IAAI,CAAC,GAAG,CAAC;AAClB;AAEA,OAAO,SAASC,qBAAqB,CACjCC,WAAmB,EACnBC,YAAiB,EACK;EACtB,IAAMC,GAAG,GAAGf,oBAAoB,CAACa,WAAW,EAAEC,YAAY,CAAC;;EAE3D;EACAC,GAAG,CAACC,QAAQ,GAAG,CAAC,CAACD,GAAG,CAACC,QAAQ;EAE7B,OAAOD,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb-new/couchdb-types.js.map b/dist/es/plugins/replication-couchdb-new/couchdb-types.js.map deleted file mode 100644 index 47c70bf8ac9..00000000000 --- a/dist/es/plugins/replication-couchdb-new/couchdb-types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"couchdb-types.js","names":[],"sources":["../../../../src/plugins/replication-couchdb-new/couchdb-types.ts"],"sourcesContent":["import {\n ById,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nexport type CouchDBCheckpointType = {\n sequence: number;\n};\n\nexport type FetchMethodType = typeof fetch;\nexport type SyncOptionsCouchDBNew = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier' | 'collection'\n> & {\n url: string;\n /**\n * Here you can set a custom fetch method\n * to use http headers or credentials when doing requests.\n */\n fetch?: FetchMethodType;\n pull?: Omit, 'handler' | 'stream$'> & {\n /**\n * Heartbeat time in milliseconds\n * for the long polling of the changestream.\n */\n heartbeat?: number;\n };\n push?: Omit, 'handler'>;\n};\n\n\nexport type URLQueryParams = ById;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb-new/index.js b/dist/es/plugins/replication-couchdb-new/index.js deleted file mode 100644 index cab8055ef3d..00000000000 --- a/dist/es/plugins/replication-couchdb-new/index.js +++ /dev/null @@ -1,378 +0,0 @@ -import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; -/** - * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb - * you can use it to sync collections with a remote CouchDB endpoint. - */ -import { ensureNotFalsy, fastUnsecureHash, flatClone } from '../../util'; -import { RxDBLeaderElectionPlugin } from '../leader-election'; -import { RxReplicationState, startReplicationOnLeaderShip } from '../replication'; -import { addRxPlugin, newRxError } from '../../index'; -import { Subject } from 'rxjs'; -import { couchDBDocToRxDocData, COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX, mergeUrlQueryParams } from './couchdb-helper'; -import { pouchSwapPrimaryToId } from '../pouchdb'; -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -export * from './couchdb-helper'; -export * from './couchdb-types'; -export var RxCouchDBNewReplicationState = /*#__PURE__*/function (_RxReplicationState) { - _inheritsLoose(RxCouchDBNewReplicationState, _RxReplicationState); - function RxCouchDBNewReplicationState(url, fetch, replicationIdentifierHash, collection, pull, push) { - var _this; - var live = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : true; - var retryTime = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 1000 * 5; - var autoStart = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : true; - _this = _RxReplicationState.call(this, replicationIdentifierHash, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; - _this.url = url; - _this.fetch = fetch; - _this.replicationIdentifierHash = replicationIdentifierHash; - _this.collection = collection; - _this.pull = pull; - _this.push = push; - _this.live = live; - _this.retryTime = retryTime; - _this.autoStart = autoStart; - return _this; - } - return RxCouchDBNewReplicationState; -}(RxReplicationState); -export function syncCouchDBNew(options) { - options = flatClone(options); - if (!options.url.endsWith('/')) { - options.url = options.url + '/'; - } - options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership; - var collection = this; - var pullStream$ = new Subject(); - var replicationPrimitivesPull; - if (options.pull) { - replicationPrimitivesPull = { - handler: function handler(lastPulledCheckpoint, batchSize) { - try { - /** - * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html - */ - var _url = options.url + '_changes?' + mergeUrlQueryParams({ - style: 'all_docs', - feed: 'normal', - include_docs: true, - since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0, - heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, - limit: batchSize, - seq_interval: batchSize - }); - return Promise.resolve(replicationState.fetch(_url)).then(function (response) { - return Promise.resolve(response.json()).then(function (jsonResponse) { - var documents = jsonResponse.results.map(function (row) { - return couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)); - }); - return { - documents: documents, - checkpoint: { - sequence: jsonResponse.last_seq - } - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }, - batchSize: ensureNotFalsy(options.pull).batchSize, - modifier: ensureNotFalsy(options.pull).modifier, - stream$: pullStream$.asObservable() - }; - } - var replicationPrimitivesPush; - if (options.push) { - replicationPrimitivesPush = { - handler: function handler(rows) { - try { - /** - * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs - */ - var _url2 = options.url + '_bulk_docs?' + mergeUrlQueryParams({}); - var body = { - docs: rows.map(function (row) { - var sendDoc = flatClone(row.newDocumentState); - if (row.assumedMasterState) { - sendDoc._rev = ensureNotFalsy(row.assumedMasterState._rev); - } - return pouchSwapPrimaryToId(collection.schema.primaryPath, sendDoc); - }) - }; - return Promise.resolve(replicationState.fetch(_url2, { - method: 'POST', - headers: { - 'content-type': 'application/json' - }, - body: JSON.stringify(body) - })).then(function (response) { - return Promise.resolve(response.json()).then(function (responseJson) { - var conflicts = responseJson.filter(function (row) { - var isConflict = row.error === 'conflict'; - if (!row.ok && !isConflict) { - throw newRxError('SNH', { - args: { - row: row - } - }); - } - return isConflict; - }); - if (conflicts.length === 0) { - return []; - } - var getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({ - include_docs: true, - keys: JSON.stringify(conflicts.map(function (c) { - return c.id; - })) - }); - return Promise.resolve(replicationState.fetch(getConflictDocsUrl)).then(function (conflictResponse) { - return Promise.resolve(conflictResponse.json()).then(function (conflictResponseJson) { - var conflictDocsMasterState = conflictResponseJson.rows.map(function (r) { - return couchDBDocToRxDocData(collection.schema.primaryPath, r.doc); - }); - return conflictDocsMasterState; - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }, - batchSize: options.push.batchSize, - modifier: options.push.modifier - }; - } - var replicationState = new RxCouchDBNewReplicationState(options.url, options.fetch ? options.fetch : fetch, COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.url), collection, replicationPrimitivesPull, replicationPrimitivesPush, options.live, options.retryTime, options.autoStart); - - /** - * Use long polling to get live changes for the pull.stream$ - */ - if (options.live && options.pull) { - var startBefore = replicationState.start.bind(replicationState); - replicationState.start = function () { - var since = 'now'; - var batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20; - (function () { - try { - var _temp3 = _for(function () { - return !replicationState.isStopped(); - }, void 0, function () { - function _temp2() { - var documents = jsonResponse.results.map(function (row) { - return couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)); - }); - since = jsonResponse.last_seq; - pullStream$.next({ - documents: documents, - checkpoint: { - sequence: jsonResponse.last_seq - } - }); - } - var url = options.url + '_changes?' + mergeUrlQueryParams({ - style: 'all_docs', - feed: 'longpoll', - since: since, - include_docs: true, - heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, - limit: batchSize, - seq_interval: batchSize - }); - var jsonResponse; - var _temp = _catch(function () { - return Promise.resolve(replicationState.fetch(url)).then(function (_replicationState$fet) { - return Promise.resolve(_replicationState$fet.json()).then(function (_await$replicationSta) { - jsonResponse = _await$replicationSta; - }); - }); - }, function (err) { - pullStream$.error(err); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - return _temp3 && _temp3.then ? _temp3.then(function () {}) : void 0; - } catch (e) { - Promise.reject(e); - } - })(); - return startBefore(); - }; - } - startReplicationOnLeaderShip(options.waitForLeadership, replicationState); - return replicationState; -} -export var RxDBReplicationCouchDBNewPlugin = { - name: 'replication-couchdb-new', - init: function init() { - addRxPlugin(RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncCouchDBNew = syncCouchDBNew; - } - } -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb-new/index.js.map b/dist/es/plugins/replication-couchdb-new/index.js.map deleted file mode 100644 index ef7cfa9b25a..00000000000 --- a/dist/es/plugins/replication-couchdb-new/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["ensureNotFalsy","fastUnsecureHash","flatClone","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","newRxError","Subject","couchDBDocToRxDocData","COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","mergeUrlQueryParams","pouchSwapPrimaryToId","body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","RxCouchDBNewReplicationState","url","fetch","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","syncCouchDBNew","options","endsWith","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","replicationState","response","json","jsonResponse","documents","results","map","row","schema","primaryPath","doc","checkpoint","last_seq","modifier","stream$","asObservable","replicationPrimitivesPush","rows","docs","sendDoc","newDocumentState","assumedMasterState","_rev","method","headers","JSON","stringify","responseJson","conflicts","filter","isConflict","error","ok","args","length","getConflictDocsUrl","keys","c","id","conflictResponse","conflictResponseJson","conflictDocsMasterState","r","startBefore","start","isStopped","next","err","RxDBReplicationCouchDBNewPlugin","name","init","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-couchdb-new/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb\n * you can use it to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n fastUnsecureHash,\n flatClone\n} from '../../util';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n RxPlugin,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n PouchdbChangesResult,\n PouchBulkDocResultRow,\n PouchAllDocsResponse\n} from '../../types';\nimport {\n RxReplicationState, startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDBNew\n} from './couchdb-types';\nimport {\n couchDBDocToRxDocData,\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n mergeUrlQueryParams\n} from './couchdb-helper';\nimport { pouchSwapPrimaryToId } from '../pouchdb';\n\nexport * from './couchdb-helper';\nexport * from './couchdb-types';\n\nexport class RxCouchDBNewReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function syncCouchDBNew(\n this: RxCollection,\n options: SyncOptionsCouchDBNew\n) {\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = this;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: PouchdbChangesResult = await response.json();\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: rows.map(row => {\n const sendDoc = flatClone(row.newDocumentState);\n if (row.assumedMasterState) {\n (sendDoc as any)._rev = ensureNotFalsy((row.assumedMasterState as any)._rev);\n }\n return pouchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: PouchBulkDocResultRow[] = await response.json();\n\n const conflicts = responseJson.filter(row => {\n const isConflict = row.error === 'conflict';\n if (!row.ok && !isConflict) {\n throw newRxError('SNH', { args: { row } });\n }\n return isConflict;\n });\n\n if (conflicts.length === 0) {\n return [];\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflicts.map(c => c.id))\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: PouchAllDocsResponse = await conflictResponse.json();\n const conflictDocsMasterState: WithDeleted[] = conflictResponseJson.rows\n .map(r => couchDBDocToRxDocData(collection.schema.primaryPath, r.doc));\n\n return conflictDocsMasterState;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxCouchDBNewReplicationState(\n options.url,\n options.fetch ? options.fetch : fetch,\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.url),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: PouchdbChangesResult;\n try {\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err) {\n pullStream$.error(err);\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n\n\nexport const RxDBReplicationCouchDBNewPlugin: RxPlugin = {\n name: 'replication-couchdb-new',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncCouchDBNew = syncCouchDBNew;\n }\n }\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,SACIA,cAAc,EACdC,gBAAgB,EAChBC,SAAS,QACN,YAAY;AAEnB,SAASC,wBAAwB,QAAQ,oBAAoB;AAY7D,SACIC,kBAAkB,EAAEC,4BAA4B,QAC7C,gBAAgB;AACvB,SACIC,WAAW,EACXC,UAAU,QAEP,aAAa;AAEpB,SAASC,OAAO,QAAQ,MAAM;AAM9B,S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cACJ,CAAC,CAAC;YAAC;YA1BH,IAAMtC,GAAG,GAAGU,OAAO,CAACV,GAAG,GAAG,WAAW,GAAG/B,mBAAmB,CAAC;cACxDiD,KAAK,EAAE,UAAU;cACjBC,IAAI,EAAE,UAAU;cAChBE,KAAK,EAALA,KAAK;cACLD,YAAY,EAAE,IAAI;cAClBG,SAAS,EAAEb,OAAO,CAACN,IAAI,IAAIM,OAAO,CAACN,IAAI,CAACmB,SAAS,GAAGb,OAAO,CAACN,IAAI,CAACmB,SAAS,GAAG,KAAK;cAClFC,KAAK,EAAEP,SAAS;cAChBQ,YAAY,EAAER;YAClB,CAAC,CAAC;YAEF,IAAIY,YAAkC;YAAC,+BACnC;cAAA,uBAC4BH,gBAAgB,CAACzB,KAAK,CAACD,GAAG,CAAC;gBAAA,uBAAlC,sBAAoC4B,IAAI,EAAE;kBAA/DC,YAAY,wBAAmD;gBAAC;cAAA;YACpE,CAAC,YAAQ4C,GAAG,EAAE;cACV5D,WAAW,CAAC4C,KAAK,CAACgB,GAAG,CAAC;YAE1B,CAAC;YAAA;UAWL,CAAC;UAAA;QACL,CAAC;UAAA;QAAA;MAAA,IAAG;MACJ,OAAOJ,WAAW,EAAE;IACxB,CAAC;EACL;EAEA1G,4BAA4B,CAAC+C,OAAO,CAACE,iBAAiB,EAAEc,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B;AAGA,OAAO,IAAMgD,+BAAyC,GAAG;EACrDC,IAAI,EAAE,yBAAyB;EAC/BC,IAAI,kBAAG;IACHhH,WAAW,CAACH,wBAAwB,CAAC;EACzC,CAAC;EACDoH,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAACvE,cAAc,GAAGA,cAAc;IACzC;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb/couchdb-helper.js b/dist/es/plugins/replication-couchdb/couchdb-helper.js new file mode 100644 index 00000000000..fd29175de80 --- /dev/null +++ b/dist/es/plugins/replication-couchdb/couchdb-helper.js @@ -0,0 +1,56 @@ +import { flatClone } from '../../plugins/utils'; +export var COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-'; +export function mergeUrlQueryParams(params) { + return Object.entries(params).filter(function (_ref) { + var _k = _ref[0], + value = _ref[1]; + return typeof value !== 'undefined'; + }).map(function (_ref2) { + var key = _ref2[0], + value = _ref2[1]; + return key + '=' + value; + }).join('&'); +} +export function couchDBDocToRxDocData(primaryPath, couchDocData) { + var doc = couchSwapIdToPrimary(primaryPath, couchDocData); + + // ensure deleted flag is set. + doc._deleted = !!doc._deleted; + return doc; +} +export function couchSwapIdToPrimary(primaryKey, docData) { + if (primaryKey === '_id' || docData[primaryKey]) { + return docData; + } + docData = flatClone(docData); + docData[primaryKey] = docData._id; + delete docData._id; + return docData; +} + +/** + * Swaps the primaryKey of the document + * to the _id property. + */ +export function couchSwapPrimaryToId(primaryKey, docData) { + // optimisation shortcut + if (primaryKey === '_id') { + return docData; + } + var idValue = docData[primaryKey]; + var ret = flatClone(docData); + delete ret[primaryKey]; + ret._id = idValue; + return ret; +} +export function getDefaultFetch() { + if (typeof window === 'object' && window['fetch']) { + /** + * @link https://stackoverflow.com/a/47180009/3443137 + */ + return window.fetch.bind(window); + } else { + return fetch; + } +} +//# sourceMappingURL=couchdb-helper.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb/couchdb-helper.js.map b/dist/es/plugins/replication-couchdb/couchdb-helper.js.map new file mode 100644 index 00000000000..f977a3dd394 --- /dev/null +++ b/dist/es/plugins/replication-couchdb/couchdb-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"couchdb-helper.js","names":["flatClone","COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","mergeUrlQueryParams","params","Object","entries","filter","_k","value","map","key","join","couchDBDocToRxDocData","primaryPath","couchDocData","doc","couchSwapIdToPrimary","_deleted","primaryKey","docData","_id","couchSwapPrimaryToId","idValue","ret","getDefaultFetch","window","fetch","bind"],"sources":["../../../../src/plugins/replication-couchdb/couchdb-helper.ts"],"sourcesContent":["import type { RxDocumentData, StringKeys, WithDeleted } from '../../types';\nimport { flatClone } from '../../plugins/utils';\nimport { URLQueryParams } from './couchdb-types';\n\n\nexport const COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-';\n\n\nexport function mergeUrlQueryParams(\n params: URLQueryParams\n): string {\n return Object.entries(params)\n .filter(([_k, value]) => typeof value !== 'undefined')\n .map(([key, value]) => key + '=' + value)\n .join('&');\n}\n\nexport function couchDBDocToRxDocData(\n primaryPath: string,\n couchDocData: any\n): WithDeleted {\n const doc = couchSwapIdToPrimary(primaryPath, couchDocData);\n\n // ensure deleted flag is set.\n doc._deleted = !!doc._deleted;\n\n return doc;\n}\n\n\nexport function couchSwapIdToPrimary(\n primaryKey: StringKeys>,\n docData: any\n): any {\n if (primaryKey === '_id' || docData[primaryKey]) {\n return docData;\n }\n docData = flatClone(docData);\n docData[primaryKey] = docData._id;\n delete docData._id;\n\n return docData;\n}\n\n/**\n * Swaps the primaryKey of the document\n * to the _id property.\n */\nexport function couchSwapPrimaryToId(\n primaryKey: StringKeys>,\n docData: any\n): RxDocType & { _id: string; } {\n // optimisation shortcut\n if (primaryKey === '_id') {\n return docData;\n }\n\n const idValue = docData[primaryKey];\n const ret = flatClone(docData);\n delete ret[primaryKey];\n ret._id = idValue;\n return ret;\n}\n\n\nexport function getDefaultFetch() {\n if (\n typeof window === 'object' &&\n (window as any)['fetch']\n ) {\n /**\n * @link https://stackoverflow.com/a/47180009/3443137\n */\n return window.fetch.bind(window);\n } else {\n return fetch;\n }\n}\n"],"mappings":"AACA,SAASA,SAAS,QAAQ,qBAAqB;AAI/C,OAAO,IAAMC,8CAA8C,GAAG,2BAA2B;AAGzF,OAAO,SAASC,mBAAmB,CAC/BC,MAAsB,EAChB;EACN,OAA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,QAAQ,IACzBA,MAAM,CAAS,OAAO,CAAC,EAC1B;IACE;AACR;AACA;IACQ,OAAOA,MAAM,CAACC,KAAK,CAACC,IAAI,CAACF,MAAM,CAAC;EACpC,CAAC,MAAM;IACH,OAAOC,KAAK;EAChB;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb-new/couchdb-types.js b/dist/es/plugins/replication-couchdb/couchdb-types.js similarity index 100% rename from dist/es/plugins/replication-couchdb-new/couchdb-types.js rename to dist/es/plugins/replication-couchdb/couchdb-types.js diff --git a/dist/es/plugins/replication-couchdb/couchdb-types.js.map b/dist/es/plugins/replication-couchdb/couchdb-types.js.map new file mode 100644 index 00000000000..338944e2b7d --- /dev/null +++ b/dist/es/plugins/replication-couchdb/couchdb-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"couchdb-types.js","names":[],"sources":["../../../../src/plugins/replication-couchdb/couchdb-types.ts"],"sourcesContent":["import {\n ById,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nexport type CouchDBCheckpointType = {\n sequence: number;\n};\n\nexport type FetchMethodType = typeof fetch;\nexport type SyncOptionsCouchDB = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier'\n> & {\n url: string;\n /**\n * Here you can set a custom fetch method\n * to use http headers or credentials when doing requests.\n */\n fetch?: FetchMethodType;\n pull?: Omit, 'handler' | 'stream$'> & {\n /**\n * Heartbeat time in milliseconds\n * for the long polling of the changestream.\n */\n heartbeat?: number;\n };\n push?: Omit, 'handler'>;\n};\n\n\nexport type URLQueryParams = ById;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb/index.js b/dist/es/plugins/replication-couchdb/index.js index 59eb6d2ebd8..69c43d33252 100644 --- a/dist/es/plugins/replication-couchdb/index.js +++ b/dist/es/plugins/replication-couchdb/index.js @@ -1,302 +1,263 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** - * this plugin adds the RxCollection.sync()-function to rxdb - * you can use it to sync collections with remote or local couchdb-instances + * This plugin can be used to sync collections with a remote CouchDB endpoint. */ - -import PouchReplicationPlugin from 'pouchdb-replication'; -import { BehaviorSubject, Subject, fromEvent, firstValueFrom } from 'rxjs'; -import { skipUntil, filter, first, mergeMap } from 'rxjs/operators'; -import { promiseWait, flatClone, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, ensureNotFalsy } from '../../util'; -import { newRxError } from '../../rx-error'; -import { isInstanceOf as isInstanceOfPouchDB, addPouchPlugin, getPouchDBOfRxCollection } from '../../plugins/pouchdb'; -import { isRxCollection } from '../../rx-collection'; -/** - * Contains all pouchdb instances that - * are used inside of RxDB by collections or databases. - * Used to ensure the remote of a replication cannot be an internal pouchdb. - */ -var INTERNAL_POUCHDBS = new WeakSet(); -export var RxCouchDBReplicationStateBase = /*#__PURE__*/function () { - function RxCouchDBReplicationStateBase(collection, syncOptions) { - var _this = this; - this._subs = []; - this._subjects = { - change: new Subject(), - docs: new Subject(), - denied: new Subject(), - active: new BehaviorSubject(false), - complete: new BehaviorSubject(false), - alive: new BehaviorSubject(false), - error: new Subject() - }; - this.canceled = false; - this.collection = collection; - this.syncOptions = syncOptions; - // create getters - Object.keys(this._subjects).forEach(function (key) { - Object.defineProperty(_this, key + '$', { - get: function get() { - return this._subjects[key].asObservable(); - } - }); - }); - } - var _proto = RxCouchDBReplicationStateBase.prototype; - _proto.awaitInitialReplication = function awaitInitialReplication() { - if (this.syncOptions.options && this.syncOptions.options.live) { - throw newRxError('RC4', { - database: this.collection.database.name, - collection: this.collection.name - }); - } - if (this.collection.database.multiInstance && this.syncOptions.waitForLeadership) { - throw newRxError('RC5', { - database: this.collection.database.name, - collection: this.collection.name - }); - } - var that = this; - return firstValueFrom(that.complete$.pipe(filter(function (x) { - return !!x; - }))); - } - - /** - * Returns false when the replication has already been canceled - */; - _proto.cancel = function cancel() { - var _this2 = this; - if (this.canceled) { - return PROMISE_RESOLVE_FALSE; - } - this.canceled = true; - var ret = PROMISE_RESOLVE_TRUE; - if (this._pouchEventEmitterObject) { - /** - * Calling cancel() does not return a promise, - * so we have to await the complete event - * to know that everything is cleaned up properly. - */ - ret = new Promise(function (res) { - ensureNotFalsy(_this2._pouchEventEmitterObject).on('complete', function () { - res(true); - }); - }); - this._pouchEventEmitterObject.cancel(); - } - this._subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - return ret; - }; - return RxCouchDBReplicationStateBase; -}(); -export function setPouchEventEmitter(rxRepState, evEmitter) { - if (rxRepState._pouchEventEmitterObject) { - throw newRxError('RC1'); - } - rxRepState._pouchEventEmitterObject = evEmitter; - - // change - rxRepState._subs.push(fromEvent(evEmitter, 'change').subscribe(function (ev) { - rxRepState._subjects.change.next(ev); - })); - - // denied - rxRepState._subs.push(fromEvent(evEmitter, 'denied').subscribe(function (ev) { - return rxRepState._subjects.denied.next(ev); - })); - - // docs - rxRepState._subs.push(fromEvent(evEmitter, 'change').subscribe(function (ev) { - if (rxRepState._subjects.docs.observers.length === 0 || ev.direction !== 'pull') return; - ev.change.docs.filter(function (doc) { - return doc.language !== 'query'; - }) // remove internal docs - // do primary-swap and keycompression - .forEach(function (doc) { - return rxRepState._subjects.docs.next(doc); - }); - })); - - // error - rxRepState._subs.push(fromEvent(evEmitter, 'error').subscribe(function (ev) { - return rxRepState._subjects.error.next(ev); - })); - - // active - rxRepState._subs.push(fromEvent(evEmitter, 'active').subscribe(function () { - return rxRepState._subjects.active.next(true); - })); - rxRepState._subs.push(fromEvent(evEmitter, 'paused').subscribe(function () { - return rxRepState._subjects.active.next(false); - })); - - // complete - rxRepState._subs.push(fromEvent(evEmitter, 'complete').subscribe(function (info) { - try { - /** - * when complete fires, it might be that not all changeEvents - * have passed through, because of the delay of .wachtForChanges() - * Therefore we have to first ensure that all previous changeEvents have been handled - */ - return Promise.resolve(promiseWait(100)).then(function () { - rxRepState._subjects.complete.next(info); - }); - } catch (e) { - return Promise.reject(e); - } - })); - // auto-cancel one-time replications on complelete to not cause memory leak - if (!rxRepState.syncOptions.options || !rxRepState.syncOptions.options.live) { - rxRepState._subs.push(rxRepState.complete$.pipe(filter(function (x) { - return !!x; - }), first(), mergeMap(function () { - return rxRepState.collection.database.requestIdlePromise().then(function () { - return rxRepState.cancel(); - }); - })).subscribe()); - } - function getIsAlive(emitter) { - // "state" will live in emitter.state if single direction replication - // or in emitter.push.state & emitter.pull.state when syncing for both - var state = emitter.state; - if (!state) { - state = [emitter.pull.state, emitter.push.state].reduce(function (acc, val) { - if (acc === 'active' || val === 'active') return 'active'; - return acc === 'stopped' ? acc : val; - }, ''); - } - - // If it's active, we can't determine whether the connection is active - // or not yet - if (state === 'active') { - return promiseWait(15).then(function () { - return getIsAlive(emitter); - }); - } - var isAlive = state !== 'stopped'; - return Promise.resolve(isAlive); - } - rxRepState._subs.push(fromEvent(evEmitter, 'paused').pipe(skipUntil(fromEvent(evEmitter, 'active'))).subscribe(function () { - getIsAlive(rxRepState._pouchEventEmitterObject).then(function (isAlive) { - return rxRepState._subjects.alive.next(isAlive); - }); - })); -} -export function createRxCouchDBReplicationState(collection, syncOptions) { - return new RxCouchDBReplicationStateBase(collection, syncOptions); -} - -/** - * get the correct function-name for pouchdb-replication - */ -export function pouchReplicationFunction(pouch, _ref) { - var _ref$pull = _ref.pull, - pull = _ref$pull === void 0 ? true : _ref$pull, - _ref$push = _ref.push, - push = _ref$push === void 0 ? true : _ref$push; - if (pull && push) { - return pouch.sync.bind(pouch); +import { ensureNotFalsy, errorToPlainJson, fastUnsecureHash, flatClone } from '../../plugins/utils'; +import { RxDBLeaderElectionPlugin } from '../leader-election'; +import { RxReplicationState, startReplicationOnLeaderShip } from '../replication'; +import { addRxPlugin, newRxError } from '../../index'; +import { Subject } from 'rxjs'; +import { couchDBDocToRxDocData, COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX, mergeUrlQueryParams, couchSwapPrimaryToId, getDefaultFetch } from './couchdb-helper'; +export * from './couchdb-helper'; +export * from './couchdb-types'; +export var RxCouchDBReplicationState = /*#__PURE__*/function (_RxReplicationState) { + _inheritsLoose(RxCouchDBReplicationState, _RxReplicationState); + function RxCouchDBReplicationState(url, fetch, replicationIdentifierHash, collection, pull, push) { + var _this; + var live = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : true; + var retryTime = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 1000 * 5; + var autoStart = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : true; + _this = _RxReplicationState.call(this, replicationIdentifierHash, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; + _this.url = url; + _this.fetch = fetch; + _this.replicationIdentifierHash = replicationIdentifierHash; + _this.collection = collection; + _this.pull = pull; + _this.push = push; + _this.live = live; + _this.retryTime = retryTime; + _this.autoStart = autoStart; + return _this; } - if (!pull && push) { - return pouch.replicate.to.bind(pouch); + return RxCouchDBReplicationState; +}(RxReplicationState); +export function replicateCouchDB(options) { + var collection = options.collection; + addRxPlugin(RxDBLeaderElectionPlugin); + options = flatClone(options); + if (!options.url.endsWith('/')) { + options.url = options.url + '/'; } - if (pull && !push) { - return pouch.replicate.from.bind(pouch); - } - if (!pull && !push) { - throw newRxError('UT3', { - pull: pull, - push: push - }); + options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership; + var pullStream$ = new Subject(); + var replicationPrimitivesPull; + if (options.pull) { + replicationPrimitivesPull = { + handler: function () { + var _handler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(lastPulledCheckpoint, batchSize) { + var url, response, jsonResponse, documents; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html + */ + url = options.url + '_changes?' + mergeUrlQueryParams({ + style: 'all_docs', + feed: 'normal', + include_docs: true, + since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0, + heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, + limit: batchSize, + seq_interval: batchSize + }); + _context.next = 3; + return replicationState.fetch(url); + case 3: + response = _context.sent; + _context.next = 6; + return response.json(); + case 6: + jsonResponse = _context.sent; + documents = jsonResponse.results.map(function (row) { + return couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)); + }); + return _context.abrupt("return", { + documents: documents, + checkpoint: { + sequence: jsonResponse.last_seq + } + }); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + function handler(_x, _x2) { + return _handler.apply(this, arguments); + } + return handler; + }(), + batchSize: ensureNotFalsy(options.pull).batchSize, + modifier: ensureNotFalsy(options.pull).modifier, + stream$: pullStream$.asObservable() + }; } -} -export function syncCouchDB(_ref2) { - var _this3 = this; - var remote = _ref2.remote, - _ref2$waitForLeadersh = _ref2.waitForLeadership, - waitForLeadership = _ref2$waitForLeadersh === void 0 ? true : _ref2$waitForLeadersh, - _ref2$direction = _ref2.direction, - direction = _ref2$direction === void 0 ? { - pull: true, - push: true - } : _ref2$direction, - _ref2$options = _ref2.options, - options = _ref2$options === void 0 ? { - live: true, - retry: true - } : _ref2$options, - query = _ref2.query; - var useOptions = flatClone(options); - - // prevent #641 by not allowing internal pouchdbs as remote - if (isInstanceOfPouchDB(remote) && INTERNAL_POUCHDBS.has(remote)) { - throw newRxError('RC3', { - database: this.database.name, - collection: this.name - }); + var replicationPrimitivesPush; + if (options.push) { + replicationPrimitivesPush = { + handler: function () { + var _handler2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rows) { + var url, body, response, responseJson, conflicts, getConflictDocsUrl, conflictResponse, conflictResponseJson, conflictDocsMasterState; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + /** + * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs + */ + url = options.url + '_bulk_docs?' + mergeUrlQueryParams({}); + body = { + docs: rows.map(function (row) { + var sendDoc = flatClone(row.newDocumentState); + if (row.assumedMasterState) { + sendDoc._rev = ensureNotFalsy(row.assumedMasterState._rev); + } + return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc); + }) + }; + _context2.next = 4; + return replicationState.fetch(url, { + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify(body) + }); + case 4: + response = _context2.sent; + _context2.next = 7; + return response.json(); + case 7: + responseJson = _context2.sent; + conflicts = responseJson.filter(function (row) { + var isConflict = row.error === 'conflict'; + if (!row.ok && !isConflict) { + throw newRxError('SNH', { + args: { + row: row + } + }); + } + return isConflict; + }); + if (!(conflicts.length === 0)) { + _context2.next = 11; + break; + } + return _context2.abrupt("return", []); + case 11: + getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({ + include_docs: true, + keys: JSON.stringify(conflicts.map(function (c) { + return c.id; + })) + }); + _context2.next = 14; + return replicationState.fetch(getConflictDocsUrl); + case 14: + conflictResponse = _context2.sent; + _context2.next = 17; + return conflictResponse.json(); + case 17: + conflictResponseJson = _context2.sent; + conflictDocsMasterState = conflictResponseJson.rows.map(function (r) { + return couchDBDocToRxDocData(collection.schema.primaryPath, r.doc); + }); + return _context2.abrupt("return", conflictDocsMasterState); + case 20: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x3) { + return _handler2.apply(this, arguments); + } + return handler; + }(), + batchSize: options.push.batchSize, + modifier: options.push.modifier + }; } + var replicationState = new RxCouchDBReplicationState(options.url, options.fetch ? options.fetch : getDefaultFetch(), COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.url), collection, replicationPrimitivesPull, replicationPrimitivesPush, options.live, options.retryTime, options.autoStart); - // if remote is RxCollection, get internal pouchdb - if (isRxCollection(remote)) { - remote = remote.storageInstance.internals.pouch; - } - if (query && this !== query.collection) { - throw newRxError('RC2', { - query: query - }); - } - var pouch = getPouchDBOfRxCollection(this); - var syncFun = pouchReplicationFunction(pouch, direction); - if (query) { - useOptions.selector = query.getPreparedQuery().selector; + /** + * Use long polling to get live changes for the pull.stream$ + */ + if (options.live && options.pull) { + var startBefore = replicationState.start.bind(replicationState); + replicationState.start = function () { + var since = 'now'; + var batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20; + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var _url, jsonResponse, documents; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (replicationState.isStopped()) { + _context3.next = 22; + break; + } + _url = options.url + '_changes?' + mergeUrlQueryParams({ + style: 'all_docs', + feed: 'longpoll', + since: since, + include_docs: true, + heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, + limit: batchSize, + seq_interval: batchSize + }); + jsonResponse = void 0; + _context3.prev = 3; + _context3.next = 6; + return replicationState.fetch(_url); + case 6: + _context3.next = 8; + return _context3.sent.json(); + case 8: + jsonResponse = _context3.sent; + _context3.next = 17; + break; + case 11: + _context3.prev = 11; + _context3.t0 = _context3["catch"](3); + pullStream$.error(newRxError('RC_STREAM', { + args: { + url: _url + }, + error: errorToPlainJson(_context3.t0) + })); + // await next tick here otherwise we could go in to a 100% CPU blocking cycle. + _context3.next = 16; + return collection.promiseWait(0); + case 16: + return _context3.abrupt("continue", 0); + case 17: + documents = jsonResponse.results.map(function (row) { + return couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)); + }); + since = jsonResponse.last_seq; + pullStream$.next({ + documents: documents, + checkpoint: { + sequence: jsonResponse.last_seq + } + }); + _context3.next = 0; + break; + case 22: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[3, 11]]); + }))(); + return startBefore(); + }; } - var repState = createRxCouchDBReplicationState(this, { - remote: remote, - waitForLeadership: waitForLeadership, - direction: direction, - options: options, - query: query - }); - - // run internal so .sync() does not have to be async - var waitTillRun = waitForLeadership && this.database.multiInstance // do not await leadership if not multiInstance - ? this.database.waitForLeadership() : promiseWait(0); - waitTillRun.then(function () { - if (_this3.destroyed || repState.canceled) { - return; - } - var pouchSync = syncFun(remote, useOptions); - setPouchEventEmitter(repState, pouchSync); - _this3.onDestroy.push(function () { - return repState.cancel(); - }); - }); - return repState; + startReplicationOnLeaderShip(options.waitForLeadership, replicationState); + return replicationState; } -export var RxDBReplicationCouchDBPlugin = { - name: 'replication-couchdb', - rxdb: true, - init: function init() { - // add pouchdb-replication-plugin - addPouchPlugin(PouchReplicationPlugin); - }, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncCouchDB = syncCouchDB; - } - }, - hooks: { - createRxCollection: { - after: function after(args) { - var collection = args.collection; - var pouch = collection.storageInstance.internals.pouch; - if (pouch) { - INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch); - } - } - } - } -}; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-couchdb/index.js.map b/dist/es/plugins/replication-couchdb/index.js.map index d760666a672..d40b1e789fe 100644 --- a/dist/es/plugins/replication-couchdb/index.js.map +++ b/dist/es/plugins/replication-couchdb/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["PouchReplicationPlugin","BehaviorSubject","Subject","fromEvent","firstValueFrom","skipUntil","filter","first","mergeMap","promiseWait","flatClone","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","ensureNotFalsy","newRxError","isInstanceOf","isInstanceOfPouchDB","addPouchPlugin","getPouchDBOfRxCollection","isRxCollection","INTERNAL_POUCHDBS","WeakSet","RxCouchDBReplicationStateBase","collection","syncOptions","_subs","_subjects","change","docs","denied","active","complete","alive","error","canceled","Object","keys","forEach","key","defineProperty","get","asObservable","awaitInitialReplication","options","live","database","name","multiInstance","waitForLeadership","that","complete$","pipe","x","cancel","ret","_pouchEventEmitterObject","Promise","res","on","sub","unsubscribe","setPouchEventEmitter","rxRepState","evEmitter","push","subscribe","ev","next","observers","length","direction","doc","language","info","requestIdlePromise","then","getIsAlive","emitter","state","pull","reduce","acc","val","isAlive","resolve","createRxCouchDBReplicationState","pouchReplicationFunction","pouch","sync","bind","replicate","to","from","syncCouchDB","remote","retry","query","useOptions","has","storageInstance","internals","syncFun","selector","getPreparedQuery","repState","waitTillRun","destroyed","pouchSync","onDestroy","RxDBReplicationCouchDBPlugin","rxdb","init","prototypes","RxCollection","proto","hooks","createRxCollection","after","args","add"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.sync()-function to rxdb\n * you can use it to sync collections with remote or local couchdb-instances\n */\n\nimport PouchReplicationPlugin from 'pouchdb-replication';\nimport {\n BehaviorSubject,\n Subject,\n fromEvent,\n Subscription,\n Observable,\n firstValueFrom\n} from 'rxjs';\nimport {\n skipUntil,\n filter,\n first,\n mergeMap\n} from 'rxjs/operators';\n\nimport {\n promiseWait,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n ensureNotFalsy\n} from '../../util';\nimport {\n newRxError\n} from '../../rx-error';\nimport {\n isInstanceOf as isInstanceOfPouchDB,\n addPouchPlugin,\n getPouchDBOfRxCollection\n} from '../../plugins/pouchdb';\n\nimport {\n isRxCollection\n} from '../../rx-collection';\nimport type {\n RxCollection,\n PouchSyncHandler,\n PouchReplicationOptions,\n RxPlugin,\n SyncOptions,\n PouchDBInstance\n} from '../../types';\n\n/**\n * Contains all pouchdb instances that\n * are used inside of RxDB by collections or databases.\n * Used to ensure the remote of a replication cannot be an internal pouchdb.\n */\nconst INTERNAL_POUCHDBS = new WeakSet();\n\nexport class RxCouchDBReplicationStateBase {\n public _subs: Subscription[] = [];\n\n // can be used for debugging or custom event-handling\n // will be set some time after sync() is called\n public _pouchEventEmitterObject?: PouchSyncHandler | null;\n public _subjects = {\n change: new Subject(),\n docs: new Subject(),\n denied: new Subject(),\n active: new BehaviorSubject(false),\n complete: new BehaviorSubject(false),\n alive: new BehaviorSubject(false),\n error: new Subject(),\n };\n\n public canceled: boolean = false;\n\n constructor(\n public readonly collection: RxCollection,\n public readonly syncOptions: SyncOptions\n ) {\n // create getters\n Object.keys(this._subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this._subjects[key].asObservable();\n }\n });\n });\n }\n\n awaitInitialReplication(): Promise {\n if (this.syncOptions.options && this.syncOptions.options.live) {\n throw newRxError('RC4', {\n database: this.collection.database.name,\n collection: this.collection.name\n });\n }\n if (this.collection.database.multiInstance && this.syncOptions.waitForLeadership) {\n throw newRxError('RC5', {\n database: this.collection.database.name,\n collection: this.collection.name\n });\n }\n\n const that: RxCouchDBReplicationState = this as any;\n return firstValueFrom(\n that.complete$.pipe(\n filter(x => !!x)\n )\n );\n }\n\n /**\n * Returns false when the replication has already been canceled\n */\n cancel(): Promise {\n if (this.canceled) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.canceled = true;\n let ret = PROMISE_RESOLVE_TRUE;\n if (this._pouchEventEmitterObject) {\n /**\n * Calling cancel() does not return a promise,\n * so we have to await the complete event\n * to know that everything is cleaned up properly.\n */\n ret = new Promise(res => {\n ensureNotFalsy(this._pouchEventEmitterObject)\n .on('complete', () => {\n res(true);\n });\n });\n this._pouchEventEmitterObject.cancel();\n }\n this._subs.forEach(sub => sub.unsubscribe());\n return ret;\n }\n}\n\nexport type RxCouchDBReplicationState = RxCouchDBReplicationStateBase & {\n change$: Observable;\n docs$: Observable;\n denied$: Observable;\n active$: Observable;\n alive$: Observable;\n complete$: Observable;\n error$: Observable;\n};\n\nexport function setPouchEventEmitter(\n rxRepState: RxCouchDBReplicationState,\n evEmitter: PouchSyncHandler\n) {\n if (rxRepState._pouchEventEmitterObject) {\n throw newRxError('RC1');\n }\n rxRepState._pouchEventEmitterObject = evEmitter;\n\n // change\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'change')\n .subscribe(ev => {\n rxRepState._subjects.change.next(ev);\n })\n );\n\n // denied\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'denied')\n .subscribe(ev => rxRepState._subjects.denied.next(ev))\n );\n\n // docs\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'change')\n .subscribe(ev => {\n if (\n rxRepState._subjects.docs.observers.length === 0 ||\n (ev as any).direction !== 'pull'\n ) return;\n\n (ev as any).change.docs\n .filter((doc: any) => doc.language !== 'query') // remove internal docs\n // do primary-swap and keycompression\n .forEach((doc: any) => rxRepState._subjects.docs.next(doc));\n }));\n\n // error\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'error')\n .subscribe(ev => rxRepState._subjects.error.next(ev))\n );\n\n // active\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'active')\n .subscribe(() => rxRepState._subjects.active.next(true))\n );\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'paused')\n .subscribe(() => rxRepState._subjects.active.next(false))\n );\n\n // complete\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'complete')\n .subscribe(async (info: any) => {\n /**\n * when complete fires, it might be that not all changeEvents\n * have passed through, because of the delay of .wachtForChanges()\n * Therefore we have to first ensure that all previous changeEvents have been handled\n */\n await promiseWait(100);\n rxRepState._subjects.complete.next(info);\n })\n );\n // auto-cancel one-time replications on complelete to not cause memory leak\n if (\n !rxRepState.syncOptions.options ||\n !rxRepState.syncOptions.options.live\n ) {\n rxRepState._subs.push(\n rxRepState.complete$.pipe(\n filter(x => !!x),\n first(),\n mergeMap(() => {\n return rxRepState.collection.database\n .requestIdlePromise()\n .then(() => rxRepState.cancel());\n })\n ).subscribe()\n );\n }\n\n function getIsAlive(emitter: any): Promise {\n // \"state\" will live in emitter.state if single direction replication\n // or in emitter.push.state & emitter.pull.state when syncing for both\n let state = emitter.state;\n if (!state) {\n state = [emitter.pull.state, emitter.push.state]\n .reduce((acc, val) => {\n if (acc === 'active' || val === 'active') return 'active';\n return acc === 'stopped' ? acc : val;\n }, '');\n }\n\n // If it's active, we can't determine whether the connection is active\n // or not yet\n if (state === 'active') {\n return promiseWait(15).then(() => getIsAlive(emitter));\n }\n\n const isAlive = state !== 'stopped';\n return Promise.resolve(isAlive);\n }\n\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'paused')\n .pipe(\n skipUntil(fromEvent(evEmitter as any, 'active'))\n ).subscribe(() => {\n getIsAlive(rxRepState._pouchEventEmitterObject)\n .then(isAlive => rxRepState._subjects.alive.next(isAlive));\n })\n );\n}\n\nexport function createRxCouchDBReplicationState(\n collection: RxCollection,\n syncOptions: SyncOptions\n): RxCouchDBReplicationState {\n return new RxCouchDBReplicationStateBase(\n collection,\n syncOptions\n ) as RxCouchDBReplicationState;\n}\n\n/**\n * get the correct function-name for pouchdb-replication\n */\nexport function pouchReplicationFunction(\n pouch: PouchDBInstance,\n {\n pull = true,\n push = true\n }\n): any {\n if (pull && push) {\n return pouch.sync.bind(pouch);\n }\n if (!pull && push) {\n return (pouch.replicate as any).to.bind(pouch);\n }\n if (pull && !push) {\n return (pouch.replicate as any).from.bind(pouch);\n }\n if (!pull && !push) {\n throw newRxError('UT3', {\n pull,\n push\n });\n }\n}\n\nexport function syncCouchDB(\n this: RxCollection,\n {\n remote,\n waitForLeadership = true,\n direction = {\n pull: true,\n push: true\n },\n options = {\n live: true,\n retry: true\n },\n query\n }: SyncOptions) {\n const useOptions: PouchReplicationOptions & { selector: any; } = flatClone(options) as any;\n\n // prevent #641 by not allowing internal pouchdbs as remote\n if (\n isInstanceOfPouchDB(remote) &&\n INTERNAL_POUCHDBS.has(remote)\n ) {\n throw newRxError('RC3', {\n database: this.database.name,\n collection: this.name\n });\n }\n\n // if remote is RxCollection, get internal pouchdb\n if (isRxCollection(remote)) {\n remote = (remote as RxCollection).storageInstance.internals.pouch;\n }\n\n if (query && this !== query.collection) {\n throw newRxError('RC2', {\n query\n });\n }\n\n const pouch = getPouchDBOfRxCollection(this);\n const syncFun = pouchReplicationFunction(pouch, direction);\n if (query) {\n useOptions.selector = query.getPreparedQuery().selector;\n }\n\n const repState: any = createRxCouchDBReplicationState(\n this,\n {\n remote,\n waitForLeadership,\n direction,\n options,\n query\n }\n );\n\n // run internal so .sync() does not have to be async\n const waitTillRun = (\n waitForLeadership &&\n this.database.multiInstance // do not await leadership if not multiInstance\n ) ? this.database.waitForLeadership() : promiseWait(0);\n (waitTillRun as any).then(() => {\n if (this.destroyed || repState.canceled) {\n return;\n }\n const pouchSync = syncFun(remote, useOptions);\n setPouchEventEmitter(repState, pouchSync);\n\n this.onDestroy.push(() => repState.cancel());\n });\n\n return repState;\n}\n\n\n\nexport const RxDBReplicationCouchDBPlugin: RxPlugin = {\n name: 'replication-couchdb',\n rxdb: true,\n init() {\n // add pouchdb-replication-plugin\n addPouchPlugin(PouchReplicationPlugin);\n },\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncCouchDB = syncCouchDB;\n }\n },\n hooks: {\n createRxCollection: {\n after: args => {\n const collection = args.collection;\n const pouch: PouchDBInstance | undefined = collection.storageInstance.internals.pouch;\n if (pouch) {\n INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch);\n }\n }\n }\n }\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAEA,OAAOA,sBAAsB,MAAM,qBAAqB;AACxD,SACIC,eAAe,EACfC,OAAO,EACPC,SAAS,EAGTC,cAAc,QACX,MAAM;AACb,SACIC,SAAS,EACTC,MAAM,EACNC,KAAK,EACLC,QAAQ,QACL,gBAAgB;AAEvB,SACIC,WAAW,EACXC,SAAS,EACTC,qBAAqB,EACrBC,oBAAoB,EACpBC,cAAc,QACX,YAAY;AACnB,SACIC,UAAU,QACP,gBAAgB;AACvB,SACIC,YAAY,IAAIC,mBAAmB,EACnCC,cAAc,EACdC,wBAAwB,QACrB,uBAAuB;AAE9B,SACIC,cAAc,QACX,qBAAqB;AAU5B;AACA;AACA;AACA;AACA;AACA,IAAMC,iBAAiB,GAAG,IAAIC,OAAO,EAAE;AAEvC,WAAaC,6BAA6B;EAkBtC,uCACoBC,UAA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AAI,CAAC;MAAA,OAAMwC,QAAQ,CAACnD,MAAM,EAAE;IAAA,EAAC;EAChD,CAAC,CAAC;EAEF,OAAOmD,QAAQ;AACnB;AAIA,OAAO,IAAMK,4BAAsC,GAAG;EAClD/D,IAAI,EAAE,qBAAqB;EAC3BgE,IAAI,EAAE,IAAI;EACVC,IAAI,kBAAG;IACH;IACA9F,cAAc,CAACjB,sBAAsB,CAAC;EAC1C,CAAC;EACDgH,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAACrB,WAAW,GAAGA,WAAW;IACnC;EACJ,CAAC;EACDsB,KAAK,EAAE;IACHC,kBAAkB,EAAE;MAChBC,KAAK,EAAE,eAAAC,IAAI,EAAI;QACX,IAAM/F,UAAU,GAAG+F,IAAI,CAAC/F,UAAU;QAClC,IAAMgE,KAAkC,GAAGhE,UAAU,CAAC4E,eAAe,CAACC,SAAS,CAACb,KAAK;QACrF,IAAIA,KAAK,EAAE;UACPnE,iBAAiB,CAACmG,GAAG,CAAChG,UAAU,CAAC4E,eAAe,CAACC,SAAS,CAACb,KAAK,CAAC;QACrE;MACJ;IACJ;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ensureNotFalsy","errorToPlainJson","fastUnsecureHash","flatClone","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","newRxError","Subject","couchDBDocToRxDocData","COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","mergeUrlQueryParams","couchSwapPrimaryToId","getDefaultFetch","RxCouchDBReplicationState","url","fetch","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","replicateCouchDB","options","endsWith","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","replicationState","response","json","jsonResponse","documents","results","map","row","schema","primaryPath","doc","checkpoint","last_seq","modifier","stream$","asObservable","replicationPrimitivesPush","rows","body","docs","sendDoc","newDocumentState","assumedMasterState","_rev","method","headers","JSON","stringify","responseJson","conflicts","filter","isConflict","error","ok","args","length","getConflictDocsUrl","keys","c","id","conflictResponse","conflictResponseJson","conflictDocsMasterState","r","startBefore","start","bind","isStopped","promiseWait","next"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * This plugin can be used to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n fastUnsecureHash,\n flatClone\n} from '../../plugins/utils';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n CouchdbChangesResult,\n CouchBulkDocResultRow,\n CouchAllDocsResponse\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDB\n} from './couchdb-types';\nimport {\n couchDBDocToRxDocData,\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n mergeUrlQueryParams,\n couchSwapPrimaryToId,\n getDefaultFetch\n} from './couchdb-helper';\n\nexport * from './couchdb-helper';\nexport * from './couchdb-types';\n\nexport class RxCouchDBReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateCouchDB(\n options: SyncOptionsCouchDB\n) {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: CouchdbChangesResult = await response.json();\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: rows.map(row => {\n const sendDoc = flatClone(row.newDocumentState);\n if (row.assumedMasterState) {\n (sendDoc as any)._rev = ensureNotFalsy((row.assumedMasterState as any)._rev);\n }\n return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: CouchBulkDocResultRow[] = await response.json();\n\n const conflicts = responseJson.filter(row => {\n const isConflict = row.error === 'conflict';\n if (!row.ok && !isConflict) {\n throw newRxError('SNH', { args: { row } });\n }\n return isConflict;\n });\n\n if (conflicts.length === 0) {\n return [];\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflicts.map(c => c.id))\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: CouchAllDocsResponse = await conflictResponse.json();\n const conflictDocsMasterState: WithDeleted[] = conflictResponseJson.rows\n .map(r => couchDBDocToRxDocData(collection.schema.primaryPath, r.doc));\n\n return conflictDocsMasterState;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxCouchDBReplicationState(\n options.url,\n options.fetch ? options.fetch : getDefaultFetch(),\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.url),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: CouchdbChangesResult;\n try {\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err: any) {\n pullStream$.error(newRxError('RC_STREAM', {\n args: { url },\n error: errorToPlainJson(err)\n }));\n // await next tick here otherwise we could go in to a 100% CPU blocking cycle.\n await collection.promiseWait(0);\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;AAAA;AACA;AACA;AACA,SACIA,cAAc,EACdC,gBAAgB,EAChBC,gBAAgB,EAChBC,SAAS,QACN,qBAAqB;AAE5B,SAASC,wBAAwB,QAAQ,oBAAoB;AAW7D,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,gBAAgB;AACvB,SACIC,WAAW,EACXC,UAAU,QAEP,aAAa;AAEpB,SAASC,OAAO,QAAQ,MAAM;AAM9B,SACIC,qBAAqB,EACrBC,8CAA8C,EAC9CC,mBAAmB,EACnBC,oBAAoB,EACpBC,eAAe,QACZ,kBAAkB;AAEzB,cAAc,kBAAkB;AAChC,cAAc,iBAAiB;AAE/B,WAAaC,yBAAyB;EAAA;EAClC,mCACoBC,GAAW,EACpBC,KAAsB,EACbC,yBAAiC,EACjCC,UAAmC,EACnCC,IAA+D,EAC/DC,IAAwC,EAI1D;IAAA;IAAA,IAHkBC,IAAa,uEAAG,IAAI;IAAA,IAC7BC,SAAiB,uEAAG,IAAI,GAAG,CAAC;IAAA,IAC5BC,SAAkB,uEAAG,IAAI;IAEhC,uCACIN,yBAAyB,EACzBC,UAAU,EACV,UAAU,EACVC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SAAS,CACZ;IAAC,MAnBcR,GAAW,GAAXA,GAAW;IAAA,MACpBC,KAAsB,GAAtBA,KAAsB;IAAA,MACbC,yBAAiC,GAAjCA,yBAAiC;IAAA,MACjCC,UAAmC,GAAnCA,UAAmC;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AI,CAAC;gBACb7C,SAAS,EAATA,SAAS;gBACTO,UAAU,EAAE;kBACRf,QAAQ,EAAEO,YAAY,CAACS;gBAC3B;cACJ,CAAC,CAAC;cAAC;cAAA;YAAA;YAAA;cAAA;UAAA;QAAA;MAAA,CAEV,IAAG;MACJ,OAAOgC,WAAW,EAAE;IACxB,CAAC;EACL;EAEAhF,4BAA4B,CAACoB,OAAO,CAACE,iBAAiB,EAAEc,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"} \ No newline at end of file diff --git a/dist/es/plugins/replication-firestore/firestore-helper.js b/dist/es/plugins/replication-firestore/firestore-helper.js index f2e0d546cf3..1a889b1e481 100644 --- a/dist/es/plugins/replication-firestore/firestore-helper.js +++ b/dist/es/plugins/replication-firestore/firestore-helper.js @@ -1,5 +1,5 @@ import { Timestamp } from 'firebase/firestore'; -import { flatClone, now } from '../../util'; +import { flatClone, now } from '../../plugins/utils'; export var FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-firestore-'; export function getFirestoreSortFieldValue(docData, primaryKey) { var timeString = now() + ''; diff --git a/dist/es/plugins/replication-firestore/firestore-helper.js.map b/dist/es/plugins/replication-firestore/firestore-helper.js.map index 6184b3c3c4c..69adba77b41 100644 --- a/dist/es/plugins/replication-firestore/firestore-helper.js.map +++ b/dist/es/plugins/replication-firestore/firestore-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"firestore-helper.js","names":["Timestamp","flatClone","now","FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","getFirestoreSortFieldValue","docData","primaryKey","timeString","padStart","stripServerTimestampField","serverTimestampField","data","serverTimestampToIsoString","timestamp","date","toDate","toISOString","isoStringToServerTimestamp","isoString","Date","fromDate","firestoreRowToDocData","primaryPath","row","id","stripPrimaryKey"],"sources":["../../../../src/plugins/replication-firestore/firestore-helper.ts"],"sourcesContent":["import {\n QueryDocumentSnapshot,\n Timestamp\n} from 'firebase/firestore';\nimport type {\n WithDeleted\n} from '../../types';\nimport { flatClone, now } from '../../util';\n\nexport const FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-firestore-';\n\n\nexport function getFirestoreSortFieldValue(docData: any, primaryKey: string): string {\n const timeString = now() + '';\n return 'rxdb-' + timeString.padStart(15, '0') + '-' + docData[primaryKey];\n}\n\nexport function stripServerTimestampField(\n serverTimestampField: string,\n docData: RxDocType\n): WithDeleted {\n const data = flatClone(docData);\n delete (data as any)[serverTimestampField];\n return data as any;\n}\n\n\nexport function serverTimestampToIsoString(serverTimestampField: string, docData: any): string {\n const timestamp = (docData as any)[serverTimestampField];\n const date: Date = timestamp.toDate();\n return date.toISOString();\n}\n\nexport function isoStringToServerTimestamp(isoString: string): Timestamp {\n const date = new Date(isoString);\n return Timestamp.fromDate(date);\n}\n\nexport function firestoreRowToDocData(\n serverTimestampField: string,\n primaryPath: string,\n row: QueryDocumentSnapshot\n): WithDeleted {\n const docData = stripServerTimestampField(\n serverTimestampField,\n row.data()\n );\n (docData as any)[primaryPath] = row.id;\n return docData;\n}\n\nexport function stripPrimaryKey(\n primaryPath: string,\n docData: any\n): any {\n docData = flatClone(docData);\n delete (docData as any)[primaryPath];\n return docData;\n}\n"],"mappings":"AAAA,SAEIA,SAAS,QACN,oBAAoB;AAI3B,SAASC,SAAS,EAAEC,GAAG,QAAQ,YAAY;AAE3C,OAAO,IAAMC,4CAA4C,GAAG,6BAA6B;AAGzF,OAAO,SAASC,0BAA0B,CAACC,OAAY,EAAEC,UAAkB,EAAU;EACjF,IAAMC,UAAU,GAAGL,GAAG,EAAE,GAAG,EAAE;EAC7B,OAAO,OAAO,GAAGK,UAAU,CAACC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,GAAG,GAAG,GAAGH,OAAO,CAACC,UAAU,CAAC;AAC7E;AAEA,OAAO,SAASG,yBAAyB,CACrCC,oBAA4B,EAC5BL,OAAkB,EACI;EACtB,IAAMM,IAAI,GAAGV,SAAS,CAACI,OAAO,CAAC;EAC/B,OAAQM,IAAI,CAASD,oBAAoB,CAAC;EAC1C,OAAOC,IAAI;AACf;AAGA,OAAO,SAASC,0BAA0B,CAACF,oBAA4B,EAAEL,OAAY,EAAU;EAC3F,IAAMQ,SAAS,GAAIR,OAAO,CAASK,oBAAoB,CAAC;EACxD,IAAMI,IAAU,GAAGD,SAAS,CAACE,MAAM,EAAE;EACrC,OAAOD,IAAI,CAACE,WAAW,EAAE;AAC7B;AAEA,OAAO,SAASC,0BAA0B,CAACC,SAAiB,EAAa;EACrE,IAAMJ,IAAI,GAAG,IAAIK,IAAI,CAACD,SAAS,CAAC;EAChC,OAAOlB,SAAS,CAACoB,QAAQ,CAACN,IAAI,CAAC;AACnC;AAEA,OAAO,SAASO,qBAAqB,CACjCX,oBAA4B,EAC5BY,WAAmB,EACnBC,GAAqC,EACf;EACtB,IAAMlB,OAAO,GAAGI,yBAAyB,CACrCC,oBAAoB,EACpBa,GAAG,CAACZ,IAAI,EAAE,CACb;EACAN,OAAO,CAASiB,WAAW,CAAC,GAAGC,GAAG,CAACC,EAAE;EACtC,OAAOnB,OAAO;AAClB;AAEA,OAAO,SAASoB,eAAe,CAC3BH,WAAmB,EACnBjB,OAAY,EACT;EACHA,OAAO,GAAGJ,SAAS,CAACI,OAAO,CAAC;EAC5B,OAAQA,OAAO,CAASiB,WAAW,CAAC;EACpC,OAAOjB,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"firestore-helper.js","names":["Timestamp","flatClone","now","FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","getFirestoreSortFieldValue","docData","primaryKey","timeString","padStart","stripServerTimestampField","serverTimestampField","data","serverTimestampToIsoString","timestamp","date","toDate","toISOString","isoStringToServerTimestamp","isoString","Date","fromDate","firestoreRowToDocData","primaryPath","row","id","stripPrimaryKey"],"sources":["../../../../src/plugins/replication-firestore/firestore-helper.ts"],"sourcesContent":["import {\n QueryDocumentSnapshot,\n Timestamp\n} from 'firebase/firestore';\nimport type {\n WithDeleted\n} from '../../types';\nimport { flatClone, now } from '../../plugins/utils';\n\nexport const FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-firestore-';\n\n\nexport function getFirestoreSortFieldValue(docData: any, primaryKey: string): string {\n const timeString = now() + '';\n return 'rxdb-' + timeString.padStart(15, '0') + '-' + docData[primaryKey];\n}\n\nexport function stripServerTimestampField(\n serverTimestampField: string,\n docData: RxDocType\n): WithDeleted {\n const data = flatClone(docData);\n delete (data as any)[serverTimestampField];\n return data as any;\n}\n\n\nexport function serverTimestampToIsoString(serverTimestampField: string, docData: any): string {\n const timestamp = (docData as any)[serverTimestampField];\n const date: Date = timestamp.toDate();\n return date.toISOString();\n}\n\nexport function isoStringToServerTimestamp(isoString: string): Timestamp {\n const date = new Date(isoString);\n return Timestamp.fromDate(date);\n}\n\nexport function firestoreRowToDocData(\n serverTimestampField: string,\n primaryPath: string,\n row: QueryDocumentSnapshot\n): WithDeleted {\n const docData = stripServerTimestampField(\n serverTimestampField,\n row.data()\n );\n (docData as any)[primaryPath] = row.id;\n return docData;\n}\n\nexport function stripPrimaryKey(\n primaryPath: string,\n docData: any\n): any {\n docData = flatClone(docData);\n delete (docData as any)[primaryPath];\n return docData;\n}\n"],"mappings":"AAAA,SAEIA,SAAS,QACN,oBAAoB;AAI3B,SAASC,SAAS,EAAEC,GAAG,QAAQ,qBAAqB;AAEpD,OAAO,IAAMC,4CAA4C,GAAG,6BAA6B;AAGzF,OAAO,SAASC,0BAA0B,CAACC,OAAY,EAAEC,UAAkB,EAAU;EACjF,IAAMC,UAAU,GAAGL,GAAG,EAAE,GAAG,EAAE;EAC7B,OAAO,OAAO,GAAGK,UAAU,CAACC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,GAAG,GAAG,GAAGH,OAAO,CAACC,UAAU,CAAC;AAC7E;AAEA,OAAO,SAASG,yBAAyB,CACrCC,oBAA4B,EAC5BL,OAAkB,EACI;EACtB,IAAMM,IAAI,GAAGV,SAAS,CAACI,OAAO,CAAC;EAC/B,OAAQM,IAAI,CAASD,oBAAoB,CAAC;EAC1C,OAAOC,IAAI;AACf;AAGA,OAAO,SAASC,0BAA0B,CAACF,oBAA4B,EAAEL,OAAY,EAAU;EAC3F,IAAMQ,SAAS,GAAIR,OAAO,CAASK,oBAAoB,CAAC;EACxD,IAAMI,IAAU,GAAGD,SAAS,CAACE,MAAM,EAAE;EACrC,OAAOD,IAAI,CAACE,WAAW,EAAE;AAC7B;AAEA,OAAO,SAASC,0BAA0B,CAACC,SAAiB,EAAa;EACrE,IAAMJ,IAAI,GAAG,IAAIK,IAAI,CAACD,SAAS,CAAC;EAChC,OAAOlB,SAAS,CAACoB,QAAQ,CAACN,IAAI,CAAC;AACnC;AAEA,OAAO,SAASO,qBAAqB,CACjCX,oBAA4B,EAC5BY,WAAmB,EACnBC,GAAqC,EACf;EACtB,IAAMlB,OAAO,GAAGI,yBAAyB,CACrCC,oBAAoB,EACpBa,GAAG,CAACZ,IAAI,EAAE,CACb;EACAN,OAAO,CAASiB,WAAW,CAAC,GAAGC,GAAG,CAACC,EAAE;EACtC,OAAOnB,OAAO;AAClB;AAEA,OAAO,SAASoB,eAAe,CAC3BH,WAAmB,EACnBjB,OAAY,EACT;EACHA,OAAO,GAAGJ,SAAS,CAACI,OAAO,CAAC;EAC5B,OAAQA,OAAO,CAASiB,WAAW,CAAC;EACpC,OAAOjB,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/replication-firestore/firestore-types.js.map b/dist/es/plugins/replication-firestore/firestore-types.js.map index 9660465da16..53c6362ddd6 100644 --- a/dist/es/plugins/replication-firestore/firestore-types.js.map +++ b/dist/es/plugins/replication-firestore/firestore-types.js.map @@ -1 +1 @@ -{"version":3,"file":"firestore-types.js","names":[],"sources":["../../../../src/plugins/replication-firestore/firestore-types.ts"],"sourcesContent":["import {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nimport {\n CollectionReference,\n Firestore\n} from 'firebase/firestore';\n\nexport type FirestoreCheckpointType = {\n id: string;\n /**\n * Firestore internally sets the time to an object like\n * {\n * \"seconds\": 1669807105,\n * \"nanoseconds\": 476000000\n * }\n * But to be able to query that, we have to use a date string\n * like '2022-11-30T11:18:25.141Z'\n * so we store that string instead.\n */\n serverTimestamp: string;\n};\nexport type FirestoreCollection = CollectionReference;\n\nexport type FirestoreOptions = {\n projectId: string;\n collection: FirestoreCollection;\n database: Firestore;\n};\n\nexport type SyncOptionsFirestore = Omit<\n ReplicationOptions,\n 'pull' | 'push' | 'replicationIdentifier' | 'collection'\n> & {\n firestore: FirestoreOptions;\n /**\n * In firestore it is not possible to read out\n * the internally used write timestamp.\n * Even if we could read it out, it is not indexed which\n * is required for fetch 'changes-since-x'.\n * So instead we have to rely on a custom user defined field\n * that contains the server time which is set by firestore via serverTimestamp()\n * IMPORTANT: The serverTimestampField MUST NOT be part of the collections RxJsonSchema!\n * [default='serverTimestamp']\n * @link https://groups.google.com/g/firebase-talk/c/tAmPzPei-mE\n */\n serverTimestampField?: string;\n pull?: Omit, 'handler' | 'stream$'>;\n push?: Omit, 'handler'>;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"firestore-types.js","names":[],"sources":["../../../../src/plugins/replication-firestore/firestore-types.ts"],"sourcesContent":["import {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nimport {\n CollectionReference,\n Firestore\n} from 'firebase/firestore';\n\nexport type FirestoreCheckpointType = {\n id: string;\n /**\n * Firestore internally sets the time to an object like\n * {\n * \"seconds\": 1669807105,\n * \"nanoseconds\": 476000000\n * }\n * But to be able to query that, we have to use a date string\n * like '2022-11-30T11:18:25.141Z'\n * so we store that string instead.\n */\n serverTimestamp: string;\n};\nexport type FirestoreCollection = CollectionReference;\n\nexport type FirestoreOptions = {\n projectId: string;\n collection: FirestoreCollection;\n database: Firestore;\n};\n\nexport type SyncOptionsFirestore = Omit<\n ReplicationOptions,\n 'pull' | 'push' | 'replicationIdentifier'\n> & {\n firestore: FirestoreOptions;\n /**\n * In firestore it is not possible to read out\n * the internally used write timestamp.\n * Even if we could read it out, it is not indexed which\n * is required for fetch 'changes-since-x'.\n * So instead we have to rely on a custom user defined field\n * that contains the server time which is set by firestore via serverTimestamp()\n * IMPORTANT: The serverTimestampField MUST NOT be part of the collections RxJsonSchema!\n * [default='serverTimestamp']\n * @link https://groups.google.com/g/firebase-talk/c/tAmPzPei-mE\n */\n serverTimestampField?: string;\n pull?: Omit, 'handler' | 'stream$'>;\n push?: Omit, 'handler'>;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/replication-firestore/index.js b/dist/es/plugins/replication-firestore/index.js index c1f52f9af3d..e812007bd77 100644 --- a/dist/es/plugins/replication-firestore/index.js +++ b/dist/es/plugins/replication-firestore/index.js @@ -1,164 +1,13 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; -/** - * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb - * you can use it to sync collections with a remote CouchDB endpoint. - */ -import { ensureNotFalsy, fastUnsecureHash, flatClone, lastOfArray } from '../../util'; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { ensureNotFalsy, errorToPlainJson, fastUnsecureHash, flatClone, lastOfArray } from '../../plugins/utils'; import { doc, query, where, orderBy, limit, getDocs, onSnapshot, runTransaction, writeBatch, serverTimestamp, waitForPendingWrites, documentId } from 'firebase/firestore'; import { RxDBLeaderElectionPlugin } from '../leader-election'; import { RxReplicationState, startReplicationOnLeaderShip } from '../replication'; import { addRxPlugin, getSchemaByObjectPath, newRxError } from '../../'; import { Subject } from 'rxjs'; import { firestoreRowToDocData, FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX, isoStringToServerTimestamp, serverTimestampToIsoString, stripPrimaryKey, stripServerTimestampField } from './firestore-helper'; -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} export * from './firestore-helper'; export * from './firestore-types'; export var RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationState) { @@ -181,8 +30,9 @@ export var RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationSt } return RxFirestoreReplicationState; }(RxReplicationState); -export function syncFirestore(options) { - var collection = this; +export function replicateFirestore(options) { + var collection = options.collection; + addRxPlugin(RxDBLeaderElectionPlugin); var pullStream$ = new Subject(); var replicationPrimitivesPull; options.live = typeof options.live === 'undefined' ? true : options.live; @@ -194,92 +44,118 @@ export function syncFirestore(options) { /** * The serverTimestampField MUST NOT be part of the collections RxJsonSchema. */ - var schemaPart = getSchemaByObjectPath(this.schema.jsonSchema, serverTimestampField); + var schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField); if (schemaPart || // also must not be nested. serverTimestampField.includes('.')) { throw newRxError('RC6', { field: serverTimestampField, - schema: this.schema.jsonSchema + schema: collection.schema.jsonSchema }); } if (options.pull) { replicationPrimitivesPull = { - handler: function handler(lastPulledCheckpoint, batchSize) { - try { - var _temp2 = function _temp2() { - if (useDocs.length === 0) { - return { - checkpoint: lastPulledCheckpoint, - documents: [] - }; - } - var lastDoc = ensureNotFalsy(lastOfArray(useDocs)); - var documents = useDocs.map(function (row) { - return firestoreRowToDocData(serverTimestampField, primaryPath, row); - }); - var newCheckpoint = { - id: lastDoc.id, - serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data()) - }; - var ret = { - documents: documents, - checkpoint: newCheckpoint - }; - return ret; - }; - var newerQuery; - var sameTimeQuery; - if (lastPulledCheckpoint) { - var lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp); - newerQuery = query(options.firestore.collection, where(serverTimestampField, '>', lastServerTimestamp), orderBy(serverTimestampField, 'asc'), limit(batchSize)); - sameTimeQuery = query(options.firestore.collection, where(serverTimestampField, '==', lastServerTimestamp), where(primaryPath, '>', lastPulledCheckpoint.id), orderBy(primaryPath, 'asc'), orderBy(serverTimestampField, 'asc'), limit(batchSize)); - } else { - newerQuery = query(options.firestore.collection, orderBy(serverTimestampField, 'asc'), limit(batchSize)); - } - var mustsReRun = true; - var useDocs = []; - var _temp = _for(function () { - return !!mustsReRun; - }, void 0, function () { - /** - * Local writes that have not been persisted to the server - * are in pending state and do not have a correct serverTimestamp set. - * We have to ensure we only use document states that are in sync with the server. - * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b - */ - return Promise.resolve(waitForPendingWrites(options.firestore.database)).then(function () { - return Promise.resolve(runTransaction(options.firestore.database, function (_tx) { - try { - useDocs = []; - return Promise.resolve(Promise.all([getDocs(newerQuery), sameTimeQuery ? getDocs(sameTimeQuery) : undefined])).then(function (_ref) { - var newerQueryResult = _ref[0], - sameTimeQueryResult = _ref[1]; - if (newerQueryResult.metadata.hasPendingWrites || sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites) {} else { - mustsReRun = false; - if (sameTimeQuery) { - useDocs = ensureNotFalsy(sameTimeQueryResult).docs; - } - var missingAmount = batchSize - useDocs.length; - if (missingAmount > 0) { - var additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(function (x) { - return !!x; - }); - useDocs = useDocs.concat(additonalDocs); + handler: function () { + var _handler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(lastPulledCheckpoint, batchSize) { + var newerQuery, sameTimeQuery, lastServerTimestamp, mustsReRun, useDocs, lastDoc, documents, newCheckpoint, ret; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (lastPulledCheckpoint) { + lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp); + newerQuery = query(options.firestore.collection, where(serverTimestampField, '>', lastServerTimestamp), orderBy(serverTimestampField, 'asc'), limit(batchSize)); + sameTimeQuery = query(options.firestore.collection, where(serverTimestampField, '==', lastServerTimestamp), where(primaryPath, '>', lastPulledCheckpoint.id), orderBy(primaryPath, 'asc'), orderBy(serverTimestampField, 'asc'), limit(batchSize)); + } else { + newerQuery = query(options.firestore.collection, orderBy(serverTimestampField, 'asc'), limit(batchSize)); + } + mustsReRun = true; + useDocs = []; + case 3: + if (!mustsReRun) { + _context2.next = 10; + break; + } + _context2.next = 6; + return waitForPendingWrites(options.firestore.database); + case 6: + _context2.next = 8; + return runTransaction(options.firestore.database, /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_tx) { + var _yield$Promise$all, newerQueryResult, sameTimeQueryResult, missingAmount, additonalDocs; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + useDocs = []; + _context.next = 3; + return Promise.all([getDocs(newerQuery), sameTimeQuery ? getDocs(sameTimeQuery) : undefined]); + case 3: + _yield$Promise$all = _context.sent; + newerQueryResult = _yield$Promise$all[0]; + sameTimeQueryResult = _yield$Promise$all[1]; + if (!(newerQueryResult.metadata.hasPendingWrites || sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)) { + _context.next = 10; + break; + } + return _context.abrupt("return"); + case 10: + mustsReRun = false; + if (sameTimeQuery) { + useDocs = ensureNotFalsy(sameTimeQueryResult).docs; + } + missingAmount = batchSize - useDocs.length; + if (missingAmount > 0) { + additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(function (x) { + return !!x; + }); + useDocs = useDocs.concat(additonalDocs); + } + case 14: + case "end": + return _context.stop(); } - } - }); - } catch (e) { - return Promise.reject(e); + }, _callee); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + case 8: + _context2.next = 3; + break; + case 10: + if (!(useDocs.length === 0)) { + _context2.next = 12; + break; } - })).then(function () {}); - }); - }); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); + return _context2.abrupt("return", { + checkpoint: lastPulledCheckpoint, + documents: [] + }); + case 12: + lastDoc = ensureNotFalsy(lastOfArray(useDocs)); + documents = useDocs.map(function (row) { + return firestoreRowToDocData(serverTimestampField, primaryPath, row); + }); + newCheckpoint = { + id: lastDoc.id, + serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data()) + }; + ret = { + documents: documents, + checkpoint: newCheckpoint + }; + return _context2.abrupt("return", ret); + case 17: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x, _x2) { + return _handler.apply(this, arguments); } - }, + return handler; + }(), batchSize: ensureNotFalsy(options.pull).batchSize, modifier: ensureNotFalsy(options.pull).modifier, stream$: pullStream$.asObservable() @@ -288,100 +164,150 @@ export function syncFirestore(options) { var replicationPrimitivesPush; if (options.push) { replicationPrimitivesPush = { - handler: function handler(rows) { - try { - var writeRowsById = {}; - var docIds = rows.map(function (row) { - var docId = row.newDocumentState[primaryPath]; - writeRowsById[docId] = row; - return docId; - }); - return Promise.resolve(waitForPendingWrites(options.firestore.database)).then(function () { - var conflicts = []; - - /** - * Everything must run INSIDE of the transaction - * because on tx-errors, firebase will re-run the transaction on some cases. - * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure - * @link https://firebase.google.com/docs/firestore/manage-data/transactions - */ - return Promise.resolve(runTransaction(options.firestore.database, function (_tx) { - try { - conflicts = []; // reset in case the tx has re-run. + handler: function () { + var _handler2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(rows) { + var writeRowsById, docIds, conflicts; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + writeRowsById = {}; + docIds = rows.map(function (row) { + var docId = row.newDocumentState[primaryPath]; + writeRowsById[docId] = row; + return docId; + }); + _context5.next = 4; + return waitForPendingWrites(options.firestore.database); + case 4: + conflicts = []; /** - * @link https://stackoverflow.com/a/48423626/3443137 + * Everything must run INSIDE of the transaction + * because on tx-errors, firebase will re-run the transaction on some cases. + * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure + * @link https://firebase.google.com/docs/firestore/manage-data/transactions */ - return Promise.resolve(getDocs(query(options.firestore.collection, where(documentId(), 'in', docIds)))).then(function (docsInDbResult) { - var docsInDbById = {}; - docsInDbResult.docs.forEach(function (row) { - var docDataInDb = stripServerTimestampField(serverTimestampField, row.data()); - var docId = row.id; - docDataInDb[primaryPath] = docId; - docsInDbById[docId] = docDataInDb; - }); + _context5.next = 7; + return runTransaction(options.firestore.database, /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_tx) { + var docsInDbResult, docsInDbById, batch, hasWrite; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + conflicts = []; // reset in case the tx has re-run. + /** + * @link https://stackoverflow.com/a/48423626/3443137 + */ + _context4.next = 3; + return getDocs(query(options.firestore.collection, where(documentId(), 'in', docIds))); + case 3: + docsInDbResult = _context4.sent; + docsInDbById = {}; + docsInDbResult.docs.forEach(function (row) { + var docDataInDb = stripServerTimestampField(serverTimestampField, row.data()); + var docId = row.id; + docDataInDb[primaryPath] = docId; + docsInDbById[docId] = docDataInDb; + }); - /** - * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes - */ - var batch = writeBatch(options.firestore.database); - var hasWrite = false; - return Promise.resolve(Promise.all(Object.entries(writeRowsById).map(function (_ref2) { - try { - var _temp4 = function _temp4(_collection$conflictH) { - if (docInDb && (_writeRow$assumedMast || _collection$conflictH.isEqual === false)) { - // conflict - conflicts.push(docInDb); - } else { - // no conflict - hasWrite = true; - var docRef = doc(options.firestore.collection, docId); - var writeDocData = flatClone(writeRow.newDocumentState); - writeDocData[serverTimestampField] = serverTimestamp(); - if (!docInDb) { - // insert - batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData)); - } else { - // update - batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData)); + /** + * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes + */ + batch = writeBatch(options.firestore.database); + hasWrite = false; + _context4.next = 10; + return Promise.all(Object.entries(writeRowsById).map( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(_ref3) { + var docId, writeRow, docInDb, docRef, writeDocData; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + docId = _ref3[0], writeRow = _ref3[1]; + docInDb = docsInDbById[docId]; + _context3.t0 = docInDb; + if (!_context3.t0) { + _context3.next = 11; + break; + } + _context3.t1 = !writeRow.assumedMasterState; + if (_context3.t1) { + _context3.next = 10; + break; + } + _context3.next = 8; + return collection.conflictHandler({ + newDocumentState: docInDb, + realMasterState: writeRow.assumedMasterState + }, 'replication-firestore-push'); + case 8: + _context3.t2 = _context3.sent.isEqual; + _context3.t1 = _context3.t2 === false; + case 10: + _context3.t0 = _context3.t1; + case 11: + if (!_context3.t0) { + _context3.next = 15; + break; + } + // conflict + conflicts.push(docInDb); + _context3.next = 20; + break; + case 15: + // no conflict + hasWrite = true; + docRef = doc(options.firestore.collection, docId); + writeDocData = flatClone(writeRow.newDocumentState); + writeDocData[serverTimestampField] = serverTimestamp(); + if (!docInDb) { + // insert + batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData)); + } else { + // update + batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData)); + } + case 20: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x6) { + return _ref4.apply(this, arguments); + }; + }())); + case 10: + if (!hasWrite) { + _context4.next = 13; + break; } - } - }; - var docId = _ref2[0], - writeRow = _ref2[1]; - var docInDb = docsInDbById[docId]; - var _writeRow$assumedMast = !writeRow.assumedMasterState; - return Promise.resolve(!docInDb || _writeRow$assumedMast ? _temp4(docInDb && (_writeRow$assumedMast || collection.conflictHandler({ - newDocumentState: docInDb, - realMasterState: writeRow.assumedMasterState - }, 'replication-firestore-push'))) : Promise.resolve(docInDb && (_writeRow$assumedMast || collection.conflictHandler({ - newDocumentState: docInDb, - realMasterState: writeRow.assumedMasterState - }, 'replication-firestore-push'))).then(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp3 = function () { - if (hasWrite) { - return Promise.resolve(batch.commit()).then(function () {}); + _context4.next = 13; + return batch.commit(); + case 13: + case "end": + return _context4.stop(); } - }(); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return Promise.resolve(waitForPendingWrites(options.firestore.database)).then(function () { - return conflicts; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + }, _callee4); + })); + return function (_x5) { + return _ref2.apply(this, arguments); + }; + }()); + case 7: + _context5.next = 9; + return waitForPendingWrites(options.firestore.database); + case 9: + return _context5.abrupt("return", conflicts); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function handler(_x4) { + return _handler2.apply(this, arguments); } - }, + return handler; + }(), batchSize: options.push.batchSize, modifier: options.push.modifier }; @@ -405,7 +331,7 @@ export function syncFirestore(options) { replicationState.reSync(); }, function (error) { replicationState.subjects.error.next(newRxError('RC_STREAM', { - error: error + error: errorToPlainJson(error) })); }); replicationState.cancel = function () { @@ -418,16 +344,4 @@ export function syncFirestore(options) { startReplicationOnLeaderShip(options.waitForLeadership, replicationState); return replicationState; } -export var RxDBReplicationFirestorePlugin = { - name: 'replication-firestore', - init: function init() { - addRxPlugin(RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncFirestore = syncFirestore; - } - } -}; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-firestore/index.js.map b/dist/es/plugins/replication-firestore/index.js.map index c784615d778..21cc50dbb81 100644 --- a/dist/es/plugins/replication-firestore/index.js.map +++ b/dist/es/plugins/replication-firestore/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ensureNotFalsy","fastUnsecureHash","flatClone","lastOfArray","doc","query","where","orderBy","limit","getDocs","onSnapshot","runTransaction","writeBatch","serverTimestamp","waitForPendingWrites","documentId","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","getSchemaByObjectPath","newRxError","Subject","firestoreRowToDocData","FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","isoStringToServerTimestamp","serverTimestampToIsoString","stripPrimaryKey","stripServerTimestampField","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","RxFirestoreReplicationState","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","syncFirestore","options","pullStream$","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","jsonSchema","includes","field","handler","lastPulledCheckpoint","batchSize","useDocs","length","checkpoint","documents","lastDoc","map","row","newCheckpoint","id","data","ret","newerQuery","sameTimeQuery","lastServerTimestamp","mustsReRun","database","_tx","Promise","all","undefined","newerQueryResult","sameTimeQueryResult","metadata","hasPendingWrites","docs","missingAmount","additonalDocs","slice","filter","x","concat","modifier","stream$","asObservable","replicationPrimitivesPush","rows","writeRowsById","docIds","docId","newDocumentState","conflicts","docsInDbResult","docsInDbById","forEach","docDataInDb","batch","hasWrite","Object","entries","docInDb","isEqual","docRef","writeDocData","writeRow","set","assumedMasterState","conflictHandler","realMasterState","commit","replicationState","projectId","startBefore","start","cancelBefore","cancel","lastChangeQuery","unsubscribe","_querySnapshot","reSync","error","subjects","next","RxDBReplicationFirestorePlugin","name","init","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb\n * you can use it to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n fastUnsecureHash,\n flatClone,\n lastOfArray\n} from '../../util';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n RxPlugin,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper';\n\nexport * from './firestore-helper';\nexport * from './firestore-types';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function syncFirestore(\n this: RxCollection,\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = this;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(this.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: this.schema.jsonSchema\n });\n }\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(options.firestore.collection,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(options.firestore.collection,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(options.firestore.collection,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n useDocs = useDocs.concat(additonalDocs as any);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n const docsInDbResult = await getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', docIds)\n )\n );\n const docsInDbById: ById = {};\n docsInDbResult.docs.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.firestore.projectId),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n options.firestore.collection,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n\nexport const RxDBReplicationFirestorePlugin: RxPlugin = {\n name: 'replication-firestore',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncFirestore = syncFirestore;\n }\n }\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,SACIA,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,WAAW,QACR,YAAY;AAEnB,SACIC,GAAG,EACHC,KAAK,EACLC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,UAAU,EACVC,cAAc,EACdC,UAAU,EACVC,eAAe,EAEfC,oBAAoB,EACpBC,UAAU,QACP,oBAAoB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C,CAAC,CACX;MACD,IAAM0I,WAAW,GAAGxI,UAAU,CAC1BuI,eAAe,EACf,UAACE,cAAc,EAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBR,gBAAgB,CAACS,MAAM,EAAE;MAC7B,CAAC,EACD,UAACC,KAAK,EAAK;QACPV,gBAAgB,CAACW,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChClI,UAAU,CAAC,WAAW,EAAE;UAAEgI,KAAK,EAALA;QAAM,CAAC,CAAC,CACrC;MACL,CAAC,CACJ;MACDV,gBAAgB,CAACK,MAAM,GAAG,YAAM;QAC5BE,WAAW,EAAE;QACb,OAAOH,YAAY,EAAE;MACzB,CAAC;MACD,OAAOF,WAAW,EAAE;IACxB,CAAC;EACL;EAEA3H,4BAA4B,CAACgD,OAAO,CAACG,iBAAiB,EAAEsE,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B;AAEA,OAAO,IAAMa,8BAAwC,GAAG;EACpDC,IAAI,EAAE,uBAAuB;EAC7BC,IAAI,kBAAG;IACHvI,WAAW,CAACH,wBAAwB,CAAC;EACzC,CAAC;EACD2I,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAAC7F,aAAa,GAAGA,aAAa;IACvC;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ensureNotFalsy","errorToPlainJson","fastUnsecureHash","flatClone","lastOfArray","doc","query","where","orderBy","limit","getDocs","onSnapshot","runTransaction","writeBatch","serverTimestamp","waitForPendingWrites","documentId","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","getSchemaByObjectPath","newRxError","Subject","firestoreRowToDocData","FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","isoStringToServerTimestamp","serverTimestampToIsoString","stripPrimaryKey","stripServerTimestampField","RxFirestoreReplicationState","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","replicateFirestore","options","pullStream$","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","jsonSchema","includes","field","handler","lastPulledCheckpoint","batchSize","lastServerTimestamp","newerQuery","sameTimeQuery","id","mustsReRun","useDocs","database","_tx","Promise","all","undefined","newerQueryResult","sameTimeQueryResult","metadata","hasPendingWrites","docs","missingAmount","length","additonalDocs","slice","filter","x","concat","checkpoint","documents","lastDoc","map","row","newCheckpoint","data","ret","modifier","stream$","asObservable","replicationPrimitivesPush","rows","writeRowsById","docIds","docId","newDocumentState","conflicts","docsInDbResult","docsInDbById","forEach","docDataInDb","batch","hasWrite","Object","entries","writeRow","docInDb","assumedMasterState","conflictHandler","realMasterState","isEqual","docRef","writeDocData","set","update","commit","replicationState","projectId","startBefore","start","bind","cancelBefore","cancel","lastChangeQuery","unsubscribe","_querySnapshot","reSync","error","subjects","next"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n errorToPlainJson,\n fastUnsecureHash,\n flatClone,\n lastOfArray\n} from '../../plugins/utils';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper';\n\nexport * from './firestore-helper';\nexport * from './firestore-types';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateFirestore(\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: collection.schema.jsonSchema\n });\n }\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(options.firestore.collection,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(options.firestore.collection,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(options.firestore.collection,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n useDocs = useDocs.concat(additonalDocs as any);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n const docsInDbResult = await getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', docIds)\n )\n );\n const docsInDbById: ById = {};\n docsInDbResult.docs.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.firestore.projectId),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n options.firestore.collection,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error: errorToPlainJson(error) })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;AAAA,SACIA,cAAc,EACdC,gBAAgB,EAChBC,gBAAgB,EAChBC,SAAS,EACTC,WAAW,QACR,qBAAqB;AAE5B,SACIC,GAAG,EACHC,KAAK,EACLC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,UAAU,EACVC,cAAc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IAAIE,OAAO,CAACJ,IAAI,IAAII,OAAO,CAACN,IAAI,EAAE;IAC9B,IAAMkF,WAAW,GAAGF,gBAAgB,CAACG,KAAK,CAACC,IAAI,CAACJ,gBAAgB,CAAC;IACjE,IAAMK,YAAY,GAAGL,gBAAgB,CAACM,MAAM,CAACF,IAAI,CAACJ,gBAAgB,CAAC;IACnEA,gBAAgB,CAACG,KAAK,GAAG,YAAM;MAC3B,IAAMI,eAAe,GAAGnH,KAAK,CACzBkC,OAAO,CAACT,SAAS,CAACE,UAAU,EAC5BzB,OAAO,CAACoC,oBAAoB,EAAE,MAAM,CAAC,EACrCnC,KAAK,CAAC,CAAC,CAAC,CACX;MACD,IAAMiH,WAAW,GAAG/G,UAAU,CAC1B8G,eAAe,EACf,UAACE,cAAc,EAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBT,gBAAgB,CAACU,MAAM,EAAE;MAC7B,CAAC,EACD,UAACC,KAAK,EAAK;QACPX,gBAAgB,CAACY,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChCzG,UAAU,CAAC,WAAW,EAAE;UAAEuG,KAAK,EAAE5H,gBAAgB,CAAC4H,KAAK;QAAE,CAAC,CAAC,CAC9D;MACL,CAAC,CACJ;MACDX,gBAAgB,CAACM,MAAM,GAAG,YAAM;QAC5BE,WAAW,EAAE;QACb,OAAOH,YAAY,EAAE;MACzB,CAAC;MACD,OAAOH,WAAW,EAAE;IACxB,CAAC;EACL;EAEAjG,4BAA4B,CAACqB,OAAO,CAACG,iBAAiB,EAAEuE,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"} \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js index 2d5924d41c9..922a7334a4e 100644 --- a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js +++ b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js @@ -1,6 +1,6 @@ import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema'; import { fillWithDefaultSettings } from '../../rx-schema-helper'; -import { clone, ensureNotFalsy, flatClone, ucfirst } from '../../util'; +import { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils'; // we use two spaces because get-graphql-from-jsonschema does also export var SPACING = ' '; diff --git a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map index 9d90c341ff6..798457a44fc 100644 --- a/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map +++ b/dist/es/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["getGraphqlSchemaFromJsonSchema","fillWithDefaultSettings","clone","ensureNotFalsy","flatClone","ucfirst","SPACING","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ucCollectionName","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","keys","startsWith","deletedField","withRevisions","strip","cloned","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../util';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":"AAAA,SAASA,8BAA8B,QAAQ,6BAA6B;AAE5E,SAASC,uBAAuB,QAAQ,wBAAwB;AAGhE,SAASC,KAAK,EAAEC,cAAc,EAAEC,SAAS,EAAEC,OAAO,QAAQ,YAAY;AAsDtE;AACA,OAAO,IAAMC,OAAO,GAAG,IAAI;;AAE3B;AACA;AACA;AACA,OAAO,SAASC,yBAAyB,CACrCC,KAAqC,EACN;EAC/B,IAAMC,GAAoC,GAAG;IACzCC,QAAQ,EAAE,EAAE;IACZC,OAAO,EAAE,EAAE;IACXC,SAAS,EAAE,EAAE;IACbC,aAAa,EAAE,EAAE;IACjBC,MAAM,EAAE,EAAE;IACVC,KAAK,EAAE;EACX,CAAC;EAEDC,MAAM,CAACC,OAAO,CAACT,KAAK,CAAC,CAACU,OAAO,CAAC,gBAA0C;IAAA,IAAxCC,cAAc;MAAEC,kBAAkB;IAC9DA,kBAAkB,GAAGC,eAAe,CAACD,kBAAkB,CAAC;IAExD,IAAME,MAAM,GAAGF,kBAAkB,CAACE,MAAM;IACxC,IAAMC,QAAkB,GAAGpB,cAAc,CAACiB,kBAAkB,CAACG,QAAQ,CAAC;IACtE,IAAMC,gBAAgB,G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EAAE;IACpBzC,QAAQ,CAACyC,QAAQ,GAAG,UAAU;EAClC;EACA,IAAI,CAACzC,QAAQ,CAACqD,MAAM,EAAE;IAClBrD,QAAQ,CAACqD,MAAM,GAAG,QAAQ;EAC9B;EACA,IAAI,CAACrD,QAAQ,CAACiC,OAAO,EAAE;IACnBjC,QAAQ,CAACiC,OAAO,GAAG,SAAS;EAChC;EACA,IAAI,CAAChD,KAAK,CAAC6C,YAAY,EAAE;IACrB7C,KAAK,CAAC6C,YAAY,GAAG,EAAE;EAC3B;EAGA,IAAI,CAAC7C,KAAK,CAAC+E,aAAa,EAAE;IACtB/E,KAAK,CAAC+E,aAAa,GAAG,KAAK;EAC/B;EAEA,IAAI,CAAC/E,KAAK,CAACoB,eAAe,EAAE;IACxBpB,KAAK,CAACoB,eAAe,GAAG,EAAE;EAC9B;EACA,IAAI,CAACpB,KAAK,CAACoD,gBAAgB,EAAE;IACzBpD,KAAK,CAACoD,gBAAgB,GAAG,EAAE;EAC/B;EAEA,OAAOpD,KAAK;AAChB;AAEA,SAASmB,mBAAmB,CAAIL,MAAuB,EAAEkE,KAAe,EAA4B;EAChG,IAAMC,MAAW,GAAGvF,KAAK,CAACoB,MAAM,CAAC;EACjCkE,KAAK,CAACtE,OAAO,CAAC,UAAAwB,GAAG,EAAI;IACjB,OAAO+C,MAAM,CAACtD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAO+C,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAAStC,uBAAuB,CAACD,GAAW,EAAE1B,gBAAwB,EAAU;EAC5E,OAAO0B,GAAG,CAACwC,OAAO,CAAC,GAAG,GAAGlE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file +{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["getGraphqlSchemaFromJsonSchema","fillWithDefaultSettings","clone","ensureNotFalsy","flatClone","ucfirst","SPACING","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ucCollectionName","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","keys","startsWith","deletedField","withRevisions","strip","cloned","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":"AAAA,SAASA,8BAA8B,QAAQ,6BA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ACpB,KAAK,CAACoD,gBAAgB,EAAE;IACzBpD,KAAK,CAACoD,gBAAgB,GAAG,EAAE;EAC/B;EAEA,OAAOpD,KAAK;AAChB;AAEA,SAASmB,mBAAmB,CAAIL,MAAuB,EAAEkE,KAAe,EAA4B;EAChG,IAAMC,MAAW,GAAGvF,KAAK,CAACoB,MAAM,CAAC;EACjCkE,KAAK,CAACtE,OAAO,CAAC,UAAAwB,GAAG,EAAI;IACjB,OAAO+C,MAAM,CAACtD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAO+C,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAAStC,uBAAuB,CAACD,GAAW,EAAE1B,gBAAwB,EAAU;EAC5E,OAAO0B,GAAG,CAACwC,OAAO,CAAC,GAAG,GAAGlE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/graphql-websocket.js b/dist/es/plugins/replication-graphql/graphql-websocket.js index 7c04389a9a4..68b4170b153 100644 --- a/dist/es/plugins/replication-graphql/graphql-websocket.js +++ b/dist/es/plugins/replication-graphql/graphql-websocket.js @@ -1,5 +1,5 @@ import { createClient } from 'graphql-ws'; -import { getFromMapOrThrow } from '../../util'; +import { getFromMapOrThrow } from '../../plugins/utils'; import ws from 'isomorphic-ws'; var IsomorphicWebSocket = ws.WebSocket; export var GRAPHQL_WEBSOCKET_BY_URL = new Map(); diff --git a/dist/es/plugins/replication-graphql/graphql-websocket.js.map b/dist/es/plugins/replication-graphql/graphql-websocket.js.map index 4cd4e38ee59..024915a32a8 100644 --- a/dist/es/plugins/replication-graphql/graphql-websocket.js.map +++ b/dist/es/plugins/replication-graphql/graphql-websocket.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-websocket.js","names":["createClient","getFromMapOrThrow","ws","IsomorphicWebSocket","WebSocket","GRAPHQL_WEBSOCKET_BY_URL","Map","getGraphQLWebSocket","url","has","get","wsClient","shouldRetry","webSocketImpl","socket","refCount","set","removeGraphQLWebSocketRef","obj","dispose"],"sources":["../../../../src/plugins/replication-graphql/graphql-websocket.ts"],"sourcesContent":["import { Client, createClient } from 'graphql-ws';\nimport { getFromMapOrThrow } from '../../util';\nimport ws from 'isomorphic-ws';\n\nconst { WebSocket: IsomorphicWebSocket } = ws;\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: Client;\n refCount: number;\n};\n\nexport const GRAPHQL_WEBSOCKET_BY_URL: Map = new Map();\n\n\nexport function getGraphQLWebSocket(\n url: string\n): Client {\n let has = GRAPHQL_WEBSOCKET_BY_URL.get(url);\n if (!has) {\n const wsClient = createClient({\n url,\n shouldRetry: () => true,\n webSocketImpl: IsomorphicWebSocket,\n });\n has = {\n url,\n socket: wsClient,\n refCount: 1\n };\n GRAPHQL_WEBSOCKET_BY_URL.set(url, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n return has.socket;\n}\n\n\nexport function removeGraphQLWebSocketRef(\n url: string\n) {\n const obj = getFromMapOrThrow(GRAPHQL_WEBSOCKET_BY_URL, url);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n GRAPHQL_WEBSOCKET_BY_URL.delete(url);\n obj.socket.dispose();\n }\n}\n"],"mappings":"AAAA,SAAiBA,YAAY,QAAQ,YAAY;AACjD,SAASC,iBAAiB,QAAQ,YAAY;AAC9C,OAAOC,EAAE,MAAM,eAAe;AAE9B,IAAmBC,mBAAmB,GAAKD,EAAE,CAArCE,SAAS;AAQjB,OAAO,IAAMC,wBAA4D,GAAG,IAAIC,GAAG,EAAE;AAGrF,OAAO,SAASC,mBAAmB,CAC/BC,GAAW,EACL;EACN,IAAIC,GAAG,GAAGJ,wBAAwB,CAACK,GAAG,CAACF,GAAG,CAAC;EAC3C,IAAI,CAACC,GAAG,EAAE;IACN,IAAME,QAAQ,GAAGX,YAAY,CAAC;MAC1BQ,GAAG,EAAHA,GAAG;MACHI,WAAW,EAAE;QAAA,OAAM,IAAI;MAAA;MACvBC,aAAa,EAAEV;IACnB,CAAC,CAAC;IACFM,GAAG,GAAG;MACFD,GAAG,EAAHA,GAAG;MACHM,MAAM,EAAEH,QAAQ;MAChBI,QAAQ,EAAE;IACd,CAAC;IACDV,wBAAwB,CAACW,GAAG,CAACR,GAAG,EAAEC,GAAG,CAAC;EAC1C,CAAC,MAAM;IACHA,GAAG,CAACM,QAAQ,GAAGN,GAAG,CAACM,QAAQ,GAAG,CAAC;EACnC;EACA,OAAON,GAAG,CAACK,MAAM;AACrB;AAGA,OAAO,SAASG,yBAAyB,CACrCT,GAAW,EACb;EACE,IAAMU,GAAG,GAAGjB,iBAAiB,CAACI,wBAAwB,EAAEG,GAAG,CAAC;EAC5DU,GAAG,CAACH,QAAQ,GAAGG,GAAG,CAACH,QAAQ,GAAG,CAAC;EAC/B,IAAIG,GAAG,CAACH,QAAQ,KAAK,CAAC,EAAE;IACpBV,wBAAwB,UAAO,CAACG,GAAG,CAAC;IACpCU,GAAG,CAACJ,MAAM,CAACK,OAAO,EAAE;EACxB;AACJ"} \ No newline at end of file +{"version":3,"file":"graphql-websocket.js","names":["createClient","getFromMapOrThrow","ws","IsomorphicWebSocket","WebSocket","GRAPHQL_WEBSOCKET_BY_URL","Map","getGraphQLWebSocket","url","has","get","wsClient","shouldRetry","webSocketImpl","socket","refCount","set","removeGraphQLWebSocketRef","obj","dispose"],"sources":["../../../../src/plugins/replication-graphql/graphql-websocket.ts"],"sourcesContent":["import { Client, createClient } from 'graphql-ws';\nimport { getFromMapOrThrow } from '../../plugins/utils';\nimport ws from 'isomorphic-ws';\n\nconst { WebSocket: IsomorphicWebSocket } = ws;\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: Client;\n refCount: number;\n};\n\nexport const GRAPHQL_WEBSOCKET_BY_URL: Map = new Map();\n\n\nexport function getGraphQLWebSocket(\n url: string\n): Client {\n let has = GRAPHQL_WEBSOCKET_BY_URL.get(url);\n if (!has) {\n const wsClient = createClient({\n url,\n shouldRetry: () => true,\n webSocketImpl: IsomorphicWebSocket,\n });\n has = {\n url,\n socket: wsClient,\n refCount: 1\n };\n GRAPHQL_WEBSOCKET_BY_URL.set(url, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n return has.socket;\n}\n\n\nexport function removeGraphQLWebSocketRef(\n url: string\n) {\n const obj = getFromMapOrThrow(GRAPHQL_WEBSOCKET_BY_URL, url);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n GRAPHQL_WEBSOCKET_BY_URL.delete(url);\n obj.socket.dispose();\n }\n}\n"],"mappings":"AAAA,SAAiBA,YAAY,QAAQ,YAAY;AACjD,SAASC,iBAAiB,QAAQ,qBAAqB;AACvD,OAAOC,EAAE,MAAM,eAAe;AAE9B,IAAmBC,mBAAmB,GAAKD,EAAE,CAArCE,SAAS;AAQjB,OAAO,IAAMC,wBAA4D,GAAG,IAAIC,GAAG,EAAE;AAGrF,OAAO,SAASC,mBAAmB,CAC/BC,GAAW,EACL;EACN,IAAIC,GAAG,GAAGJ,wBAAwB,CAACK,GAAG,CAACF,GAAG,CAAC;EAC3C,IAAI,CAACC,GAAG,EAAE;IACN,IAAME,QAAQ,GAAGX,YAAY,CAAC;MAC1BQ,GAAG,EAAHA,GAAG;MACHI,WAAW,EAAE;QAAA,OAAM,IAAI;MAAA;MACvBC,aAAa,EAAEV;IACnB,CAAC,CAAC;IACFM,GAAG,GAAG;MACFD,GAAG,EAAHA,GAAG;MACHM,MAAM,EAAEH,QAAQ;MAChBI,QAAQ,EAAE;IACd,CAAC;IACDV,wBAAwB,CAACW,GAAG,CAACR,GAAG,EAAEC,GAAG,CAAC;EAC1C,CAAC,MAAM;IACHA,GAAG,CAACM,QAAQ,GAAGN,GAAG,CAACM,QAAQ,GAAG,CAAC;EACnC;EACA,OAAON,GAAG,CAACK,MAAM;AACrB;AAGA,OAAO,SAASG,yBAAyB,CACrCT,GAAW,EACb;EACE,IAAMU,GAAG,GAAGjB,iBAAiB,CAACI,wBAAwB,EAAEG,GAAG,CAAC;EAC5DU,GAAG,CAACH,QAAQ,GAAGG,GAAG,CAACH,QAAQ,GAAG,CAAC;EAC/B,IAAIG,GAAG,CAACH,QAAQ,KAAK,CAAC,EAAE;IACpBV,wBAAwB,UAAO,CAACG,GAAG,CAAC;IACpCU,GAAG,CAACJ,MAAM,CAACK,OAAO,EAAE;EACxB;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/helper.js b/dist/es/plugins/replication-graphql/helper.js index 9c50bbca5ff..40d3de8f9df 100644 --- a/dist/es/plugins/replication-graphql/helper.js +++ b/dist/es/plugins/replication-graphql/helper.js @@ -1,4 +1,4 @@ -import { ensureNotFalsy } from '../../util'; +import { ensureNotFalsy } from '../../plugins/utils'; export var GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-graphql-'; export function graphQLRequest(httpUrl, clientState, queryParams) { var headers = new Headers(clientState.headers || {}); diff --git a/dist/es/plugins/replication-graphql/helper.js.map b/dist/es/plugins/replication-graphql/helper.js.map index 0d70e5d70be..6bd11806aad 100644 --- a/dist/es/plugins/replication-graphql/helper.js.map +++ b/dist/es/plugins/replication-graphql/helper.js.map @@ -1 +1 @@ -{"version":3,"file":"helper.js","names":["ensureNotFalsy","GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","graphQLRequest","httpUrl","clientState","queryParams","headers","Headers","append","req","Request","method","body","JSON","stringify","credentials","fetch","then","res","json"],"sources":["../../../../src/plugins/replication-graphql/helper.ts"],"sourcesContent":["import { RxGraphQLReplicationClientState, RxGraphQLReplicationQueryBuilderResponseObject } from '../../types';\nimport { ensureNotFalsy } from '../../util';\n\nexport const GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-graphql-';\n\nexport interface GraphQLError {\n message: string;\n locations: Array<{\n line: number;\n column: number;\n }>;\n path: string[];\n}\nexport type GraphQLErrors = Array;\n\n\n\nexport function graphQLRequest(\n httpUrl: string,\n clientState: RxGraphQLReplicationClientState,\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n) {\n\n const headers = new Headers(clientState.headers || {});\n headers.append('Content-Type', 'application/json');\n\n const req = new Request(\n ensureNotFalsy(httpUrl),\n {\n method: 'POST',\n body: JSON.stringify(queryParams),\n headers,\n credentials: clientState.credentials,\n }\n );\n return fetch(req)\n .then((res) => res.json())\n .then((body) => {\n return body;\n });\n}\n"],"mappings":"AACA,SAASA,cAAc,QAAQ,YAAY;AAE3C,OAAO,IAAMC,0CAA0C,GAAG,2BAA2B;AAcrF,OAAO,SAASC,cAAc,CAC1BC,OAAe,EACfC,WAA4C,EAC5CC,WAA2D,EAC7D;EAEE,IAAMC,OAAO,GAAG,IAAIC,OAAO,CAACH,WAAW,CAACE,OAAO,IAAI,CAAC,CAAC,CAAC;EACtDA,OAAO,CAACE,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC;EAElD,IAAMC,GAAG,GAAG,IAAIC,OAAO,CACnBV,cAAc,CAACG,OAAO,CAAC,EACvB;IACIQ,MAAM,EAAE,MAAM;IACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAACT,WAAW,CAAC;IACjCC,OAAO,EAAPA,OAAO;IACPS,WAAW,EAAEX,WAAW,CAACW;EAC7B,CAAC,CACJ;EACD,OAAOC,KAAK,CAACP,GAAG,CAAC,CACZQ,IAAI,CAAC,UAACC,GAAG;IAAA,OAAKA,GAAG,CAACC,IAAI,EAAE;EAAA,EAAC,CACzBF,IAAI,CAAC,UAACL,IAAI,EAAK;IACZ,OAAOA,IAAI;EACf,CAAC,CAAC;AACV"} \ No newline at end of file +{"version":3,"file":"helper.js","names":["ensureNotFalsy","GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","graphQLRequest","httpUrl","clientState","queryParams","headers","Headers","append","req","Request","method","body","JSON","stringify","credentials","fetch","then","res","json"],"sources":["../../../../src/plugins/replication-graphql/helper.ts"],"sourcesContent":["import { RxGraphQLReplicationClientState, RxGraphQLReplicationQueryBuilderResponseObject } from '../../types';\nimport { ensureNotFalsy } from '../../plugins/utils';\n\nexport const GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-graphql-';\n\nexport interface GraphQLError {\n message: string;\n locations: Array<{\n line: number;\n column: number;\n }>;\n path: string[];\n}\nexport type GraphQLErrors = Array;\n\n\n\nexport function graphQLRequest(\n httpUrl: string,\n clientState: RxGraphQLReplicationClientState,\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n) {\n\n const headers = new Headers(clientState.headers || {});\n headers.append('Content-Type', 'application/json');\n\n const req = new Request(\n ensureNotFalsy(httpUrl),\n {\n method: 'POST',\n body: JSON.stringify(queryParams),\n headers,\n credentials: clientState.credentials,\n }\n );\n return fetch(req)\n .then((res) => res.json())\n .then((body) => {\n return body;\n });\n}\n"],"mappings":"AACA,SAASA,cAAc,QAAQ,qBAAqB;AAEpD,OAAO,IAAMC,0CAA0C,GAAG,2BAA2B;AAcrF,OAAO,SAASC,cAAc,CAC1BC,OAAe,EACfC,WAA4C,EAC5CC,WAA2D,EAC7D;EAEE,IAAMC,OAAO,GAAG,IAAIC,OAAO,CAACH,WAAW,CAACE,OAAO,IAAI,CAAC,CAAC,CAAC;EACtDA,OAAO,CAACE,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC;EAElD,IAAMC,GAAG,GAAG,IAAIC,OAAO,CACnBV,cAAc,CAACG,OAAO,CAAC,EACvB;IACIQ,MAAM,EAAE,MAAM;IACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAACT,WAAW,CAAC;IACjCC,OAAO,EAAPA,OAAO;IACPS,WAAW,EAAEX,WAAW,CAACW;EAC7B,CAAC,CACJ;EACD,OAAOC,KAAK,CAACP,GAAG,CAAC,CACZQ,IAAI,CAAC,UAACC,GAAG;IAAA,OAAKA,GAAG,CAACC,IAAI,EAAE;EAAA,EAAC,CACzBF,IAAI,CAAC,UAACL,IAAI,EAAK;IACZ,OAAOA,IAAI;EACf,CAAC,CAAC;AACV"} \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/index.js b/dist/es/plugins/replication-graphql/index.js index 88fde6e4eb7..5df6b7ecaf5 100644 --- a/dist/es/plugins/replication-graphql/index.js +++ b/dist/es/plugins/replication-graphql/index.js @@ -1,10 +1,12 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * this plugin adds the RxCollection.syncGraphQl()-function to rxdb * you can use it to sync collections with a remote graphql endpoint. */ import objectPath from 'object-path'; -import { ensureNotFalsy, fastUnsecureHash } from '../../util'; +import { ensureNotFalsy, fastUnsecureHash } from '../../plugins/utils'; import { graphQLRequest as _graphQLRequest, GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX } from './helper'; import { RxDBLeaderElectionPlugin } from '../leader-election'; import { RxReplicationState, startReplicationOnLeaderShip } from '../replication'; @@ -40,8 +42,9 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function (_RxReplicationStat }; return RxGraphQLReplicationState; }(RxReplicationState); -export function syncGraphQL(_ref) { - var url = _ref.url, +export function replicateGraphQL(_ref) { + var collection = _ref.collection, + url = _ref.url, _ref$headers = _ref.headers, headers = _ref$headers === void 0 ? {} : _ref$headers, credentials = _ref.credentials, @@ -57,8 +60,7 @@ export function syncGraphQL(_ref) { retryTime = _ref$retryTime === void 0 ? 1000 * 5 : _ref$retryTime, _ref$autoStart = _ref.autoStart, autoStart = _ref$autoStart === void 0 ? true : _ref$autoStart; - var collection = this; - + addRxPlugin(RxDBLeaderElectionPlugin); /** * We use this object to store the GraphQL client * so we can later swap out the client inside of the replication handlers. @@ -72,37 +74,54 @@ export function syncGraphQL(_ref) { if (pull) { var pullBatchSize = pull.batchSize ? pull.batchSize : 20; replicationPrimitivesPull = { - handler: function handler(lastPulledCheckpoint) { - try { - return Promise.resolve(pull.queryBuilder(lastPulledCheckpoint, pullBatchSize)).then(function (pullGraphQL) { - return Promise.resolve(graphqlReplicationState.graphQLRequest(pullGraphQL)).then(function (result) { - function _temp2() { - var docsData = data.documents; - var newCheckpoint = data.checkpoint; - return { - documents: docsData, - checkpoint: newCheckpoint - }; - } - if (result.errors) { + handler: function () { + var _handler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(lastPulledCheckpoint) { + var pullGraphQL, result, dataPath, data, docsData, newCheckpoint; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return pull.queryBuilder(lastPulledCheckpoint, pullBatchSize); + case 2: + pullGraphQL = _context.sent; + _context.next = 5; + return graphqlReplicationState.graphQLRequest(pullGraphQL); + case 5: + result = _context.sent; + if (!result.errors) { + _context.next = 8; + break; + } throw result.errors; - } - var dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]]; - var data = objectPath.get(result, dataPath); - var _temp = function () { - if (pull.responseModifier) { - return Promise.resolve(pull.responseModifier(data, 'handler', lastPulledCheckpoint)).then(function (_pull$responseModifie) { - data = _pull$responseModifie; - }); + case 8: + dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]]; + data = objectPath.get(result, dataPath); + if (!pull.responseModifier) { + _context.next = 14; + break; } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - }); - } catch (e) { - return Promise.reject(e); + _context.next = 13; + return pull.responseModifier(data, 'handler', lastPulledCheckpoint); + case 13: + data = _context.sent; + case 14: + docsData = data.documents; + newCheckpoint = data.checkpoint; + return _context.abrupt("return", { + documents: docsData, + checkpoint: newCheckpoint + }); + case 17: + case "end": + return _context.stop(); + } + }, _callee); + })); + function handler(_x) { + return _handler.apply(this, arguments); } - }, + return handler; + }(), batchSize: pull.batchSize, modifier: pull.modifier, stream$: pullStream$.asObservable() @@ -111,22 +130,40 @@ export function syncGraphQL(_ref) { var replicationPrimitivesPush; if (push) { replicationPrimitivesPush = { - handler: function handler(rows) { - try { - return Promise.resolve(push.queryBuilder(rows)).then(function (pushObj) { - return Promise.resolve(graphqlReplicationState.graphQLRequest(pushObj)).then(function (result) { - if (result.errors) { + handler: function () { + var _handler2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rows) { + var pushObj, result, dataPath, data; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return push.queryBuilder(rows); + case 2: + pushObj = _context2.sent; + _context2.next = 5; + return graphqlReplicationState.graphQLRequest(pushObj); + case 5: + result = _context2.sent; + if (!result.errors) { + _context2.next = 8; + break; + } throw result.errors; - } - var dataPath = Object.keys(result.data)[0]; - var data = objectPath.get(result.data, dataPath); - return data; - }); - }); - } catch (e) { - return Promise.reject(e); + case 8: + dataPath = Object.keys(result.data)[0]; + data = objectPath.get(result.data, dataPath); + return _context2.abrupt("return", data); + case 11: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x2) { + return _handler2.apply(this, arguments); } - }, + return handler; + }(), batchSize: push.batchSize, modifier: push.modifier }; @@ -142,25 +179,35 @@ export function syncGraphQL(_ref) { }); var query = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers); wsClient.subscribe(query, { - next: function (streamResponse) { - try { - var _temp4 = function _temp4() { - pullStream$.next(_data); - }; - var firstField = Object.keys(streamResponse.data)[0]; - var _data = streamResponse.data[firstField]; - var _temp3 = function () { - if (pull.responseModifier) { - return Promise.resolve(pull.responseModifier(_data, 'stream')).then(function (_pull$responseModifie2) { - _data = _pull$responseModifie2; - }); + next: function () { + var _next = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(streamResponse) { + var firstField, data; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + firstField = Object.keys(streamResponse.data)[0]; + data = streamResponse.data[firstField]; + if (!pull.responseModifier) { + _context3.next = 6; + break; + } + _context3.next = 5; + return pull.responseModifier(data, 'stream'); + case 5: + data = _context3.sent; + case 6: + pullStream$.next(data); + case 7: + case "end": + return _context3.stop(); } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); + }, _callee3); + })); + function next(_x3) { + return _next.apply(this, arguments); } - }, + return next; + }(), error: function error(_error) { pullStream$.error(_error); }, @@ -186,16 +233,4 @@ export * from './helper'; export * from './graphql-schema-from-rx-schema'; export * from './query-builder-from-rx-schema'; export * from './graphql-websocket'; -export var RxDBReplicationGraphQLPlugin = { - name: 'replication-graphql', - init: function init() { - addRxPlugin(RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncGraphQL = syncGraphQL; - } - } -}; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/index.js.map b/dist/es/plugins/replication-graphql/index.js.map index ebe5879f043..5dabd6d7773 100644 --- a/dist/es/plugins/replication-graphql/index.js.map +++ b/dist/es/plugins/replication-graphql/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["objectPath","ensureNotFalsy","fastUnsecureHash","graphQLRequest","GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","removeGraphQLWebSocketRef","getGraphQLWebSocket","Subject","RxGraphQLReplicationState","url","clientState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","setHeaders","headers","setCredentials","credentials","queryParams","http","syncGraphQL","waitForLeadership","mutateableClientState","pullStream$","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","queryBuilder","pullGraphQL","graphqlReplicationState","result","docsData","data","documents","newCheckpoint","checkpoint","errors","dataPath","Object","keys","get","responseModifier","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","ws","mustUseSocket","streamQueryBuilder","startBefore","start","bind","wsClient","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","RxDBReplicationGraphQLPlugin","name","init","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport objectPath from 'object-path';\nimport {\n ensureNotFalsy,\n fastUnsecureHash\n} from '../../util';\n\nimport {\n graphQLRequest,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX\n} from './helper';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n RxPlugin,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean\n ) {\n super(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: { [k: string]: string; }): void {\n this.clientState.headers = headers;\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\n\nexport function syncGraphQL(\n this: RxCollection,\n {\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n const collection = this;\n\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = objectPath.get(result, dataPath);\n\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = Object.keys(result.data)[0];\n const data: any = objectPath.get(result.data, dataPath);\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(url.http ? url.http : url.ws as any),\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws));\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper';\nexport * from './graphql-schema-from-rx-schema';\nexport * from './query-builder-from-rx-schema';\nexport * from './graphql-websocket';\n\nexport const RxDBReplicationGraphQLPlugin: RxPlugin = {\n name: 'replication-graphql',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncGraphQL = syncGraphQL;\n }\n }\n};\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,O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,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAACrD,WAAW,GAAGA,WAAW;IACnC;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["objectPath","ensureNotFalsy","fastUnsecureHash","graphQLRequest","GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","removeGraphQLWebSocketRef","getGraphQLWebSocket","Subject","RxGraphQLReplicationState","url","clientState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","setHeaders","headers","setCredentials","credentials","queryParams","http","replicateGraphQL","waitForLeadership","mutateableClientState","pullStream$","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","queryBuilder","pullGraphQL","graphqlReplicationState","result","errors","dataPath","Object","keys","data","get","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","ws","mustUseSocket","streamQueryBuilder","startBefore","start","bind","wsClient","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport objectPath from 'object-path';\nimport {\n ensureNotFalsy,\n fastUnsecureHash\n} from '../../plugins/utils';\n\nimport {\n graphQLRequest,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX\n} from './helper';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean\n ) {\n super(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: { [k: string]: string; }): void {\n this.clientState.headers = headers;\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = objectPath.get(result, dataPath);\n\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = Object.keys(result.data)[0];\n const data: any = objectPath.get(result.data, dataPath);\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(url.http ? url.http : url.ws as any),\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws));\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper';\nexport * from './graphql-schema-from-rx-schema';\nexport * from './query-builder-from-rx-schema';\nexport * from './graphql-websocket';\n"],"mappings":";;;AAAA;AACA;AACA;AACA;AACA,OAAOA,UAAU,MAAM,aAAa;AACpC,SACIC,cAAc,EACdC,gBAAgB,QACb,qBAAqB;AAE5B,SACIC,cAAc,IAAdA,eAAc,EACdC,0CAA0C,QACvC,UAAU;AAEjB,SAASC,wBAAwB,QAAQ,oBAAoB;AAW7D,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,gBAAgB;AACvB,SACIC,WAAW,QAGR,aAAa;AAEpB,SACIC,yBAAyB,EACzBC,mBAAmB,QAChB,qBAAqB;AAC5B,SAASC,OAAO,QAAQ,MAAM;AAK9B,WAAaC,yBAAyB;EAAA;EAClC,mCACoBC,GAAqB,EACrBC,WAA4C,EAC5CC,yBAAiC,EACjCC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EAC5B;IAAA;IACE,uCACIP,yBAAyB,EACzBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SAAS,CACZ;IAAC,MApBcT,GAAqB,GAArBA,GAAqB;IAAA,MACrBC,WAA4C,GAA5CA,WAA4C;IAAA,MAC5CC,yBAAiC,GAAjCA,yBAAiC;IAAA,MACjCC,UAAmC,GAAnCA,UAAmC;IAAA,MACnCC,YAAoB,G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E;EACxB,CAAC;EAED,IAAMY,YAAY,GAAGlC,uBAAuB,CAACmC,MAAM,CAACX,IAAI,CAACxB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACmC,MAAM,GAAG,YAAM;IACnC3C,WAAW,CAACyC,QAAQ,EAAE;IACtB,IAAIb,aAAa,EAAE;MACfnD,yBAAyB,CAACR,cAAc,CAACY,GAAG,CAAC8C,EAAE,CAAC,CAAC;IACrD;IACA,OAAOe,YAAY,EAAE;EACzB,CAAC;EAEDnE,4BAA4B,CAACuB,iBAAiB,EAAEU,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC;AAEA,cAAc,UAAU;AACxB,cAAc,iCAAiC;AAC/C,cAAc,gCAAgC;AAC9C,cAAc,qBAAqB"} \ No newline at end of file diff --git a/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js b/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js index 304933f89a6..e9f3246b3e1 100644 --- a/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js +++ b/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js @@ -1,5 +1,5 @@ import { fillUpOptionals, SPACING } from './graphql-schema-from-rx-schema'; -import { ensureNotFalsy, ucfirst } from '../../util'; +import { ensureNotFalsy, ucfirst } from '../../plugins/utils'; export function pullQueryBuilderFromRxSchema(collectionName, input) { input = fillUpOptionals(input); var schema = input.schema; diff --git a/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js.map b/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js.map index 0deb96268aa..7cec7666469 100644 --- a/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js.map +++ b/dist/es/plugins/replication-graphql/query-builder-from-rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"query-builder-from-rx-schema.js","names":["fillUpOptionals","SPACING","ensureNotFalsy","ucfirst","pullQueryBuilderFromRxSchema","collectionName","input","schema","prefixes","ucCollectionName","queryName","pull","outputFields","Object","keys","properties","filter","k","ignoreOutputKeys","includes","checkpointInputName","checkpoint","builder","limit","query","join","checkpointFields","variables","pullStreamBuilderFromRxSchema","headersName","headers","stream","pushQueryBuilderFromRxSchema","push","variableName","pushRow","returnFields","pushRows","sendRows","transformPushDoc","doc","sendDoc","entries","forEach","v","ignoreInputKeys","newRow","newDocumentState","assumedMasterState","undefined"],"sources":["../../../../src/plugins/replication-graphql/query-builder-from-rx-schema.ts"],"sourcesContent":["import {\n GraphQLSchemaFromRxSchemaInputSingleCollection,\n fillUpOptionals,\n Prefixes,\n SPACING\n} from './graphql-schema-from-rx-schema';\nimport { ensureNotFalsy, ucfirst } from '../../util';\nimport type {\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLReplicationPullStreamQueryBuilder,\n RxGraphQLReplicationPushQueryBuilder,\n WithDeleted\n} from '../../types';\n\nexport function pullQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n): RxGraphQLReplicationPullQueryBuilder {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.pull + ucCollectionName;\n\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n // outputFields.push(input.deletedField);\n\n const checkpointInputName = ucCollectionName + 'Input' + prefixes.checkpoint;\n\n const builder: RxGraphQLReplicationPullQueryBuilder = (checkpoint: any, limit: number) => {\n const query = 'query ' + ucfirst(queryName) + '($checkpoint: ' + checkpointInputName + ', $limit: Int!) {\\n' +\n SPACING + SPACING + queryName + '(checkpoint: $checkpoint, limit: $limit) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + '}\\n' +\n '}';\n return {\n query,\n variables: {\n checkpoint,\n limit\n }\n };\n };\n\n return builder;\n}\n\nexport function pullStreamBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n) {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n\n const headersName = ucCollectionName + 'Input' + prefixes.headers;\n\n const query = 'subscription on' + ucfirst(ensureNotFalsy(prefixes.stream)) + '($headers: ' + headersName + ') {\\n' +\n SPACING + prefixes.stream + ucCollectionName + '(headers: $headers) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + '}' +\n '}';\n\n const builder: RxGraphQLReplicationPullStreamQueryBuilder = (headers: any) => {\n return {\n query,\n variables: {\n headers\n }\n };\n };\n return builder;\n}\n\n\nexport function pushQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): RxGraphQLReplicationPushQueryBuilder {\n input = fillUpOptionals(input);\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.push + ucCollectionName;\n\n const variableName = collectionName + prefixes.pushRow;\n\n\n const returnFields: string[] = Object.keys(input.schema.properties);\n\n const builder: RxGraphQLReplicationPushQueryBuilder = (pushRows) => {\n const query = '' +\n 'mutation ' + prefixes.push + ucCollectionName + '($' + variableName + ': [' + ucCollectionName + 'Input' + prefixes.pushRow + '!]) {\\n' +\n SPACING + queryName + '(' + variableName + ': $' + variableName + ') {\\n' +\n SPACING + SPACING + returnFields.join(',\\n' + SPACING + SPACING) + '\\n' +\n SPACING + '}\\n' +\n '}';\n\n const sendRows: typeof pushRows = [];\n function transformPushDoc(doc: WithDeleted) {\n const sendDoc: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (\n // skip if in ignoreInputKeys list\n !(input.ignoreInputKeys as string[]).includes(k) &&\n // only use properties that are in the schema\n input.schema.properties[k]\n ) {\n sendDoc[k] = v;\n }\n });\n return sendDoc;\n }\n pushRows.forEach(pushRow => {\n const newRow: typeof pushRow = {\n newDocumentState: transformPushDoc(pushRow.newDocumentState),\n assumedMasterState: pushRow.assumedMasterState ? transformPushDoc(pushRow.assumedMasterState) : undefined\n };\n sendRows.push(newRow);\n });\n const variables = {\n [variableName]: sendRows\n };\n return {\n query,\n variables\n };\n };\n\n return builder;\n}\n"],"mappings":"AAAA,SAEIA,eAAe,EAEfC,OAAO,QACJ,iCAAiC;AACxC,SAASC,cAAc,EAAEC,OAAO,QAAQ,YAAY;AAQpD,OAAO,SAASC,4BAA4B,CACxCC,cAAsB,EACtBC,KAAqD,EACZ;EACzCA,KAAK,GAAGN,eAAe,CAACM,KAAK,CAAC;EAC9B,IAAMC,MAAM,GAAGD,KAAK,CAACC,MAAM;EAC3B,IAAMC,QAAkB,GAAGF,KAAK,CAACE,QAAe;EAEhD,IAAMC,gBAAgB,GAAGN,OAAO,CAACE,cAAc,CAAC;EAChD,IAAMK,SAAS,GAAGF,QAAQ,CAACG,IAAI,GAAGF,gBAAgB;EAElD,IAAMG,YAAY,GAAGC,MAAM,CAACC,IAAI,CAACP,MAAM,CAACQ,UAAU,CAAC,CAACC,MAAM,CAAC,UAAAC,CAAC;IAAA,OAAI,CAAEX,KAAK,CAACY,gBAAgB,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C6B,OAAO,CAACF,GAAG,CAAC,CAACG,OAAO,CAAC,gBAAY;QAAA,IAAV1B,CAAC;UAAE2B,CAAC;QAC9B;QACI;QACA,CAAEtC,KAAK,CAACuC,eAAe,CAAc1B,QAAQ,CAACF,CAAC,CAAC;QAChD;QACAX,KAAK,CAACC,MAAM,CAACQ,UAAU,CAACE,CAAC,CAAC,EAC5B;UACEwB,OAAO,CAACxB,CAAC,CAAC,GAAG2B,CAAC;QAClB;MACJ,CAAC,CAAC;MACF,OAAOH,OAAO;IAClB;IACAJ,QAAQ,CAACM,OAAO,CAAC,UAAAR,OAAO,EAAI;MACxB,IAAMW,MAAsB,GAAG;QAC3BC,gBAAgB,EAAER,gBAAgB,CAACJ,OAAO,CAACY,gBAAgB,CAAC;QAC5DC,kBAAkB,EAAEb,OAAO,CAACa,kBAAkB,GAAGT,gBAAgB,CAACJ,OAAO,CAACa,kBAAkB,CAAC,GAAGC;MACpG,CAAC;MACDX,QAAQ,CAACL,IAAI,CAACa,MAAM,CAAC;IACzB,CAAC,CAAC;IACF,IAAMnB,SAAS,gCACVO,YAAY,IAAGI,QAAQ,aAC3B;IACD,OAAO;MACHd,KAAK,EAALA,KAAK;MACLG,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAED,OAAOL,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"query-builder-from-rx-schema.js","names":["fillUpOptionals","SPACING","ensureNotFalsy","ucfirst","pullQueryBuilderFromRxSchema","collectionName","input","schema","prefixes","ucCollectionName","queryName","pull","outputFields","Object","keys","properties","filter","k","ignoreOutputKeys","includes","checkpointInputName","checkpoint","builder","limit","query","join","checkpointFields","variables","pullStreamBuilderFromRxSchema","headersName","headers","stream","pushQueryBuilderFromRxSchema","push","variableName","pushRow","returnFields","pushRows","sendRows","transformPushDoc","doc","sendDoc","entries","forEach","v","ignoreInputKeys","newRow","newDocumentState","assumedMasterState","undefined"],"sources":["../../../../src/plugins/replication-graphql/query-builder-from-rx-schema.ts"],"sourcesContent":["import {\n GraphQLSchemaFromRxSchemaInputSingleCollection,\n fillUpOptionals,\n Prefixes,\n SPACING\n} from './graphql-schema-from-rx-schema';\nimport { ensureNotFalsy, ucfirst } from '../../plugins/utils';\nimport type {\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLReplicationPullStreamQueryBuilder,\n RxGraphQLReplicationPushQueryBuilder,\n WithDeleted\n} from '../../types';\n\nexport function pullQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n): RxGraphQLReplicationPullQueryBuilder {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.pull + ucCollectionName;\n\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n // outputFields.push(input.deletedField);\n\n const checkpointInputName = ucCollectionName + 'Input' + prefixes.checkpoint;\n\n const builder: RxGraphQLReplicationPullQueryBuilder = (checkpoint: any, limit: number) => {\n const query = 'query ' + ucfirst(queryName) + '($checkpoint: ' + checkpointInputName + ', $limit: Int!) {\\n' +\n SPACING + SPACING + queryName + '(checkpoint: $checkpoint, limit: $limit) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + '}\\n' +\n '}';\n return {\n query,\n variables: {\n checkpoint,\n limit\n }\n };\n };\n\n return builder;\n}\n\nexport function pullStreamBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n) {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n\n const headersName = ucCollectionName + 'Input' + prefixes.headers;\n\n const query = 'subscription on' + ucfirst(ensureNotFalsy(prefixes.stream)) + '($headers: ' + headersName + ') {\\n' +\n SPACING + prefixes.stream + ucCollectionName + '(headers: $headers) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + '}' +\n '}';\n\n const builder: RxGraphQLReplicationPullStreamQueryBuilder = (headers: any) => {\n return {\n query,\n variables: {\n headers\n }\n };\n };\n return builder;\n}\n\n\nexport function pushQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): RxGraphQLReplicationPushQueryBuilder {\n input = fillUpOptionals(input);\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.push + ucCollectionName;\n\n const variableName = collectionName + prefixes.pushRow;\n\n\n const returnFields: string[] = Object.keys(input.schema.properties);\n\n const builder: RxGraphQLReplicationPushQueryBuilder = (pushRows) => {\n const query = '' +\n 'mutation ' + prefixes.push + ucCollectionName + '($' + variableName + ': [' + ucCollectionName + 'Input' + prefixes.pushRow + '!]) {\\n' +\n SPACING + queryName + '(' + variableName + ': $' + variableName + ') {\\n' +\n SPACING + SPACING + returnFields.join(',\\n' + SPACING + SPACING) + '\\n' +\n SPACING + '}\\n' +\n '}';\n\n const sendRows: typeof pushRows = [];\n function transformPushDoc(doc: WithDeleted) {\n const sendDoc: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (\n // skip if in ignoreInputKeys list\n !(input.ignoreInputKeys as string[]).includes(k) &&\n // only use properties that are in the schema\n input.schema.properties[k]\n ) {\n sendDoc[k] = v;\n }\n });\n return sendDoc;\n }\n pushRows.forEach(pushRow => {\n const newRow: typeof pushRow = {\n newDocumentState: transformPushDoc(pushRow.newDocumentState),\n assumedMasterState: pushRow.assumedMasterState ? transformPushDoc(pushRow.assumedMasterState) : undefined\n };\n sendRows.push(newRow);\n });\n const variables = {\n [variableName]: sendRows\n };\n return {\n query,\n variables\n };\n };\n\n return builder;\n}\n"],"mappings":"AAAA,SAEIA,eAAe,EAEfC,OAAO,QACJ,iCAAiC;AACxC,SAASC,cAAc,EAAEC,OAAO,QAAQ,qBAAqB;AAQ7D,OAAO,SAASC,4BAA4B,CACxCC,cAAsB,EACtBC,KAAqD,EACZ;EACzCA,KAAK,GAAGN,eAAe,CAACM,KAAK,CAAC;EAC9B,IAAMC,MAAM,GAAGD,KAAK,CAACC,MAAM;EAC3B,IAAMC,QAAkB,GAAGF,KAAK,CAACE,QAAe;EAEhD,IAAMC,gBAAgB,GAAGN,OAAO,CAACE,cAAc,CAAC;EAChD,IAAMK,SAAS,GAAGF,QAAQ,CAACG,IAAI,GAAGF,gBAAgB;EAElD,IAAMG,YAAY,GAAGC,MAAM,CAACC,IAAI,CAACP,MAAM,CAACQ,UAAU,CAAC,CAACC,MAAM,CAAC,UAAAC,CAAC;IAAA,OAAI,CAAEX,KAAK,CAACY,gBAAgB,CAAcC,QAAQ,CAACF,CAAC,CAAC;EAAA,EAAC;EAClH;;EAEA,IAAMG,mBAAmB,GAAGX,gBAAgB,GAAG,OAAO,GAAGD,QAAQ,CAACa,UAAU;EAE5E,IAAMC,OAAkD,GAAG,SAArDA,OAAkD,CAAID,UAAe,EAAEE,KAAa,EAAK;IAC3F,IAAMC,KAAK,GAAG,QAAQ,GAAGrB,OAAO,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CAACxB,CAAC,CAAC,GAAG2B,CAAC;QAClB;MACJ,CAAC,CAAC;MACF,OAAOH,OAAO;IAClB;IACAJ,QAAQ,CAACM,OAAO,CAAC,UAAAR,OAAO,EAAI;MACxB,IAAMW,MAAsB,GAAG;QAC3BC,gBAAgB,EAAER,gBAAgB,CAACJ,OAAO,CAACY,gBAAgB,CAAC;QAC5DC,kBAAkB,EAAEb,OAAO,CAACa,kBAAkB,GAAGT,gBAAgB,CAACJ,OAAO,CAACa,kBAAkB,CAAC,GAAGC;MACpG,CAAC;MACDX,QAAQ,CAACL,IAAI,CAACa,MAAM,CAAC;IACzB,CAAC,CAAC;IACF,IAAMnB,SAAS,gCACVO,YAAY,IAAGI,QAAQ,aAC3B;IACD,OAAO;MACHd,KAAK,EAALA,KAAK;MACLG,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAED,OAAOL,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js b/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js index a7c472a4fd8..1f8ea28c006 100644 --- a/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js +++ b/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js @@ -1,5 +1,7 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { Subject } from 'rxjs'; -import { getFromMapOrThrow, PROMISE_RESOLVE_VOID, randomCouchString } from '../../util'; +import { getFromMapOrThrow, PROMISE_RESOLVE_VOID, randomCouchString } from '../../plugins/utils'; import { default as Peer } from 'simple-peer'; import { newRxError } from '../../rx-error'; @@ -78,13 +80,24 @@ export function getConnectionHandlerSimplePeer(serverUrl, wrtc) { disconnect$: disconnect$, message$: message$, response$: response$, - send: function send(peer, message) { - try { - return Promise.resolve(peer.send(JSON.stringify(message))).then(function () {}); - } catch (e) { - return Promise.reject(e); + send: function () { + var _send = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(peer, message) { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return peer.send(JSON.stringify(message)); + case 2: + case "end": + return _context.stop(); + } + }, _callee); + })); + function send(_x, _x2) { + return _send.apply(this, arguments); } - }, + return send; + }(), destroy: function destroy() { socket.close(); error$.complete(); diff --git a/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js.map b/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js.map index ac3bc251d95..a0a2d96c107 100644 --- a/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js.map +++ b/dist/es/plugins/replication-p2p/connection-handler-simple-peer.js.map @@ -1 +1 @@ -{"version":3,"file":"connection-handler-simple-peer.js","names":["Subject","getFromMapOrThrow","PROMISE_RESOLVE_VOID","randomCouchString","default","Peer","newRxError","getConnectionHandlerSimplePeer","serverUrl","wrtc","io","require","creator","options","socket","peerId","emit","room","topic","connect$","disconnect$","message$","response$","error$","peers","Map","on","roomPeerIds","forEach","remotePeerId","has","newPeer","initiator","trickle","set","messageOrResponse","JSON","parse","toString","result","next","peer","response","message","signal","from","to","error","data","handler","send","stringify","destroy","close","complete"],"sources":["../../../../src/plugins/replication-p2p/connection-handler-simple-peer.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport { getFromMapOrThrow, PROMISE_RESOLVE_VOID, randomCouchString } from '../../util';\nimport type {\n P2PConnectionHandler,\n P2PConnectionHandlerCreator,\n P2PMessage,\n P2PPeer,\n PeerWithMessage,\n PeerWithResponse\n} from './p2p-types';\n\nimport {\n Instance as SimplePeer,\n default as Peer\n} from 'simple-peer';\nimport { RxError, RxTypeError } from '../../types';\nimport { newRxError } from '../../rx-error';\n\n/**\n * Returns a connection handler that uses simple-peer and the signaling server.\n */\nexport function getConnectionHandlerSimplePeer(\n serverUrl: string,\n wrtc?: any\n): P2PConnectionHandlerCreator {\n const io = require('socket.io-client');\n\n\n const creator: P2PConnectionHandlerCreator = (options) => {\n const socket = io(serverUrl);\n\n const peerId = randomCouchString(10);\n socket.emit('join', {\n room: options.topic,\n peerId\n });\n\n const connect$ = new Subject();\n const disconnect$ = new Subject();\n const message$ = new Subject();\n const response$ = new Subject();\n const error$ = new Subject();\n\n const peers = new Map();\n\n socket.on('joined', (roomPeerIds: string[]) => {\n roomPeerIds.forEach(remotePeerId => {\n if (\n remotePeerId === peerId ||\n peers.has(remotePeerId)\n ) {\n return;\n }\n // console.log('other user joined room ' + remotePeerId);\n const newPeer: SimplePeer = new Peer({\n initiator: remotePeerId > peerId,\n wrtc,\n trickle: true\n }) as any;\n peers.set(remotePeerId, newPeer);\n\n\n newPeer.on('data', (messageOrResponse: any) => {\n messageOrResponse = JSON.parse(messageOrResponse.toString());\n // console.log('got a message from peer3: ' + messageOrResponse)\n if (messageOrResponse.result) {\n response$.next({\n peer: newPeer as any,\n response: messageOrResponse\n });\n } else {\n message$.next({\n peer: newPeer as any,\n message: messageOrResponse\n });\n }\n });\n\n newPeer.on('signal', (signal: any) => {\n // console.log('emit signal from ' + peerId + ' to ' + remotePeerId);\n socket.emit('signal', {\n from: peerId,\n to: remotePeerId,\n room: options.topic,\n signal\n });\n });\n\n newPeer.on('error', (error) => {\n error$.next(newRxError('RC_P2P_PEER', {\n error\n }));\n });\n\n newPeer.on('connect', () => {\n connect$.next(newPeer as any);\n });\n\n });\n });\n\n socket.on('signal', (data: any) => {\n // console.log('got signal(' + peerId + ') ' + data.from + ' -> ' + data.to);\n const peer = getFromMapOrThrow(peers, data.from);\n peer.signal(data.signal);\n });\n\n const handler: P2PConnectionHandler = {\n error$,\n connect$,\n disconnect$,\n message$,\n response$,\n async send(peer: P2PPeer, message: P2PMessage) {\n await (peer as any).send(JSON.stringify(message));\n },\n destroy() {\n socket.close();\n error$.complete();\n connect$.complete();\n disconnect$.complete();\n message$.complete();\n response$.complete();\n return PROMISE_RESOLVE_VOID;\n }\n };\n return handler;\n };\n return creator;\n}\n"],"mappings":"AAAA,SAASA,OAA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,CAAC;MAChDJ,IAAI,CAACG,MAAM,CAACI,IAAI,CAACJ,MAAM,CAAC;IAC5B,CAAC,CAAC;IAEF,IAAMK,OAA6B,GAAG;MAClC1B,MAAM,EAANA,MAAM;MACNJ,QAAQ,EAARA,QAAQ;MACRC,WAAW,EAAXA,WAAW;MACXC,QAAQ,EAARA,QAAQ;MACRC,SAAS,EAATA,SAAS;MACH4B,IAAI,gBAACT,IAAa,EAAEE,OAAmB;QAAA,IAAE;UAAA,uBACpCF,IAAI,CAASS,IAAI,CAACd,IAAI,CAACe,SAAS,CAACR,OAAO,CAAC,CAAC;QACrD,CAAC;UAAA;QAAA;MAAA;MACDS,OAAO,qBAAG;QACNtC,MAAM,CAACuC,KAAK,EAAE;QACd9B,MAAM,CAAC+B,QAAQ,EAAE;QACjBnC,QAAQ,CAACmC,QAAQ,EAAE;QACnBlC,WAAW,CAACkC,QAAQ,EAAE;QACtBjC,QAAQ,CAACiC,QAAQ,EAAE;QACnBhC,SAAS,CAACgC,QAAQ,EAAE;QACpB,OAAOpD,oBAAoB;MAC/B;IACJ,CAAC;IACD,OAAO+C,OAAO;EAClB,CAAC;EACD,OAAOrC,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"connection-handler-simple-peer.js","names":["Subject","getFromMapOrThrow","PROMISE_RESOLVE_VOID","randomCouchString","default","Peer","newRxError","getConnectionHandlerSimplePeer","serverUrl","wrtc","io","require","creator","options","socket","peerId","emit","room","topic","connect$","disconnect$","message$","response$","error$","peers","Map","on","roomPeerIds","forEach","remotePeerId","has","newPeer","initiator","trickle","set","messageOrResponse","JSON","parse","toString","result","next","peer","response","message","signal","from","to","error","data","handler","send","stringify","destroy","close","complete"],"sources":["../../../../src/plugins/replication-p2p/connection-handler-simple-peer.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport { getFromMapOrThrow, PROMISE_RESOLVE_VOID, randomCouchString } from '../../plugins/utils';\nimport type {\n P2PConnectionHandler,\n P2PConnectionHandlerCreator,\n P2PMessage,\n P2PPeer,\n PeerWithMessage,\n PeerWithResponse\n} from './p2p-types';\n\nimport {\n Instance as SimplePeer,\n default as Peer\n} from 'simple-peer';\nimport { RxError, RxTypeError } from '../../types';\nimport { newRxError } from '../../rx-error';\n\n/**\n * Returns a connection handler that uses simple-peer and the signaling server.\n */\nexport function getConnectionHandlerSimplePeer(\n serverUrl: string,\n wrtc?: any\n): P2PConnectionHandlerCreator {\n const io = require('socket.io-client');\n\n\n const creator: P2PConnectionHandlerCreator = (options) => {\n const socket = io(serverUrl);\n\n const peerId = randomCouchString(10);\n socket.emit('join', {\n room: options.topic,\n peerId\n });\n\n const connect$ = new Subject();\n const disconnect$ = new Subject();\n const message$ = new Subject();\n const response$ = new Subject();\n const error$ = new Subject();\n\n const peers = new Map();\n\n socket.on('joined', (roomPeerIds: string[]) => {\n roomPeerIds.forEach(remotePeerId => {\n if (\n remotePeerId === peerId ||\n peers.has(remotePeerId)\n ) {\n return;\n }\n // console.log('other user joined room ' + remotePeerId);\n const newPeer: SimplePeer = new Peer({\n initiator: remotePeerId > peerId,\n wrtc,\n trickle: true\n }) as any;\n peers.set(remotePeerId, newPeer);\n\n\n newPeer.on('data', (messageOrResponse: any) => {\n messageOrResponse = JSON.parse(messageOrResponse.toString());\n // console.log('got a message from peer3: ' + messageOrResponse)\n if (messageOrResponse.result) {\n response$.next({\n peer: newPeer as any,\n response: messageOrResponse\n });\n } else {\n message$.next({\n peer: newPeer as any,\n message: messageOrResponse\n });\n }\n });\n\n newPeer.on('signal', (signal: any) => {\n // console.log('emit signal from ' + peerId + ' to ' + remotePeerId);\n socket.emit('signal', {\n from: peerId,\n to: remotePeerId,\n room: options.topic,\n signal\n });\n });\n\n newPeer.on('error', (error) => {\n error$.next(newRxError('RC_P2P_PEER', {\n error\n }));\n });\n\n newPeer.on('connect', () => {\n connect$.next(newPeer as any);\n });\n\n });\n });\n\n socket.on('signal', (data: any) => {\n // console.log('got signal(' + peerId + ') ' + data.from + ' -> ' + data.to);\n const peer = getFromMapOrThrow(peers, data.from);\n peer.signal(data.signal);\n });\n\n const handler: P2PConnectionHandler = {\n error$,\n connect$,\n disconnect$,\n message$,\n response$,\n async send(peer: P2PPeer, message: P2PMessage) {\n await (peer as any).send(JSON.stringify(message));\n },\n destroy() {\n socket.close();\n error$.complete();\n connect$.complete();\n disconnect$.complete();\n message$.complete();\n response$.complete();\n return PROMISE_RESOLVE_VOID;\n }\n };\n return handler;\n };\n return creator;\n}\n"],"mappings":";;AAAA,SAASA,OAAO,QAAQ,MAAM;AAC9B,SAASC,iBAAiB,EAAEC,oBAAoB,EAAEC,iBAAiB,QAAQ,qBAAqB;AAUhG,SAEIC,OAAO,IAAIC,IAAI,QACZ,aAAa;AAEpB,SAASC,UAAU,QAAQ,gBAAgB;;AAE3C;AACA;AACA;AACA,OAAO,SAASC,8BAA8B,CAC1CC,SAAiB,EACjBC,IAAU,EACiB;EAC3B,IAAMC,EAAE,GAAGC,OAAO,CAAC,kBAAkB,CAAC;EAGtC,IAAMC,OAAoC,GAAG,SAAvCA,OAAoC,CAAIC,OAAO,EAAK;IACtD,IAAMC,MAAM,GAAGJ,EAAE,CAACF,SAAS,CAAC;IAE5B,IAAMO,MAAM,GAAGZ,iBAAiB,CAAC,EAAE,CAAC;IACpCW,MAAM,CAACE,IAAI,CAAC,MAAM,EAAE;MAChBC,IAAI,EAAEJ,OAAO,CAACK,KAAK;MACnBH,MAAM,EAANA;IACJ,CAAC,CAAC;IAEF,IAAMI,QAAQ,GAAG,IAAInB,OAAO,EAAW;IACvC,IAAMoB,WAAW,GAAG,IAAIpB,OAAO,EAAW;IAC1C,IAAMqB,QAAQ,GAAG,IAAIrB,OAAO,EAAmB;IAC/C,IAAMsB,SAAS,GAAG,IAAItB,OAAO,EAAoB;IACjD,IAAMuB,MAAM,GAAG,IAAIvB,OAAO,EAAyB;IAEnD,IAAMwB,KAAK,GAAG,IAAIC,GAAG,EAAsB;IAE3CX,MAAM,CAACY,EAAE,CAAC,QAAQ,EAAE,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;QACP,CAAC,CAAC;QAEFhB,OAAO,CAACL,EAAE,CAAC,SAAS,EAAE,YAAM;UACxBP,QAAQ,CAACqB,IAAI,CAACT,OAAO,CAAQ;QACjC,CAAC,CAAC;MAEN,CAAC,CAAC;IACN,CAAC,CAAC;IAEFjB,MAAM,CAACY,EAAE,CAAC,QAAQ,EAAE,UAACsB,IAAS,EAAK;MAC/B;MACA,IAAMP,IAAI,GAAGxC,iBAAiB,CAACuB,KAAK,EAAEwB,IAAI,CAACH,IAAI,CAAC;MAChDJ,IAAI,CAACG,MAAM,CAACI,IAAI,CAACJ,MAAM,CAAC;IAC5B,CAAC,CAAC;IAEF,IAAMK,OAA6B,GAAG;MAClC1B,MAAM,EAANA,MAAM;MACNJ,QAAQ,EAARA,QAAQ;MACRC,WAAW,EAAXA,WAAW;MACXC,QAAQ,EAARA,QAAQ;MACRC,SAAS,EAATA,SAAS;MACH4B,IAAI;QAAA,sFAACT,IAAa,EAAEE,OAAmB;UAAA;YAAA;cAAA;gBAAA;gBAAA,OAClCF,IAAI,CAASS,IAAI,CAACd,IAAI,CAACe,SAAS,CAACR,OAAO,CAAC,CAAC;cAAA;cAAA;gBAAA;YAAA;UAAA;QAAA;QAAA;UAAA;QAAA;QAAA;MAAA;MAErDS,OAAO,qBAAG;QACNtC,MAAM,CAACuC,KAAK,EAAE;QACd9B,MAAM,CAAC+B,QAAQ,EAAE;QACjBnC,QAAQ,CAACmC,QAAQ,EAAE;QACnBlC,WAAW,CAACkC,QAAQ,EAAE;QACtBjC,QAAQ,CAACiC,QAAQ,EAAE;QACnBhC,SAAS,CAACgC,QAAQ,EAAE;QACpB,OAAOpD,oBAAoB;MAC/B;IACJ,CAAC;IACD,OAAO+C,OAAO;EAClB,CAAC;EACD,OAAOrC,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/replication-p2p/index.js b/dist/es/plugins/replication-p2p/index.js index 40dbc02ac51..452b8204f95 100644 --- a/dist/es/plugins/replication-p2p/index.js +++ b/dist/es/plugins/replication-p2p/index.js @@ -1,182 +1,240 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { BehaviorSubject, filter, firstValueFrom, map, Subject } from 'rxjs'; import { addRxPlugin } from '../../plugin'; import { rxStorageInstanceToReplicationHandler } from '../../replication-protocol'; -import { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../util'; +import { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../plugins/utils'; import { RxDBLeaderElectionPlugin } from '../leader-election'; import { replicateRxCollection } from '../replication'; import { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper'; -export var syncP2P = function syncP2P(options) { - try { - var _temp2 = function _temp2() { - // used to easier debug stuff - var requestCounter = 0; - function getRequestId() { - var count = requestCounter++; - return _collection.database.token + '|' + requestFlag + '|' + count; - } - var requestFlag = randomCouchString(10); - return Promise.resolve(_this.database.storageToken).then(function (storageToken) { - var pool = new RxP2PReplicationPool(_this, options, options.connectionHandlerCreator(options)); - pool.subs.push(pool.connectionHandler.error$.subscribe(function (err) { - return pool.error$.next(err); - }), pool.connectionHandler.disconnect$.subscribe(function (peer) { - return pool.removePeer(peer); - })); - - /** - * Answer if someone requests our storage token - */ - pool.subs.push(pool.connectionHandler.message$.pipe(filter(function (data) { - return data.message.method === 'token'; - })).subscribe(function (data) { - pool.connectionHandler.send(data.peer, { - id: data.message.id, - result: storageToken - }); - })); - var connectSub = pool.connectionHandler.connect$.pipe(filter(function () { - return !pool.canceled; - })).subscribe(function (peer) { - try { - /** - * TODO ensure both know the correct secret - */ - return Promise.resolve(sendMessageAndAwaitAnswer(pool.connectionHandler, peer, { - id: getRequestId(), - method: 'token', - params: [] - })).then(function (tokenResponse) { - var peerToken = tokenResponse.result; - var isMaster = isMasterInP2PReplication(_this.database.hashFunction, storageToken, peerToken); - var replicationState; - if (isMaster) { - var masterHandler = pool.masterReplicationHandler; - var masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(function (ev) { - var streamResponse = { - id: 'masterChangeStream$', - result: ev - }; - pool.connectionHandler.send(peer, streamResponse); - }); - - // clean up the subscription - pool.subs.push(masterChangeStreamSub, pool.connectionHandler.disconnect$.pipe(filter(function (p) { - return p.id === peer.id; - })).subscribe(function () { - return masterChangeStreamSub.unsubscribe(); - })); - var messageSub = pool.connectionHandler.message$.pipe(filter(function (data) { - return data.peer.id === peer.id; - }), filter(function (data) { - return data.message.method !== 'token'; - })).subscribe(function (data) { - try { - var msgPeer = data.peer, - message = data.message; - /** - * If it is not a function, - * it means that the client requested the masterChangeStream$ - */ - var method = masterHandler[message.method].bind(masterHandler); - return Promise.resolve(method.apply(void 0, message.params)).then(function (result) { - var response = { - id: message.id, - result: result - }; - pool.connectionHandler.send(msgPeer, response); - }); - } catch (e) { - return Promise.reject(e); - } - }); - pool.subs.push(messageSub); - } else { - replicationState = replicateRxCollection({ - replicationIdentifier: [_this.name, options.topic, peerToken].join('||'), - collection: _this, - autoStart: true, - deletedField: '_deleted', - live: true, - retryTime: options.retryTime, - waitForLeadership: false, - pull: options.pull ? Object.assign({}, options.pull, { - handler: function handler(lastPulledCheckpoint) { - try { - return Promise.resolve(sendMessageAndAwaitAnswer(pool.connectionHandler, peer, { - method: 'masterChangesSince', - params: [lastPulledCheckpoint, ensureNotFalsy(options.pull).batchSize], - id: getRequestId() - })).then(function (answer) { - return answer.result; - }); - } catch (e) { - return Promise.reject(e); - } - }, - stream$: pool.connectionHandler.response$.pipe(filter(function (m) { - return m.response.id === 'masterChangeStream$'; - }), map(function (m) { - return m.response.result; - })) - }) : undefined, - push: options.push ? Object.assign({}, options.push, { - handler: function handler(docs) { - try { - return Promise.resolve(sendMessageAndAwaitAnswer(pool.connectionHandler, peer, { - method: 'masterWrite', - params: [docs], - id: getRequestId() - })).then(function (answer) { - return answer.result; - }); - } catch (e) { - return Promise.reject(e); - } - } - }) : undefined - }); - } - pool.addPeer(peer, replicationState); - }); - } catch (e) { - return Promise.reject(e); - } - }); - pool.subs.push(connectSub); - return pool; - }); - }; - var _this = this; - // fill defaults - if (options.pull) { - if (!options.pull.batchSize) { - options.pull.batchSize = 20; - } - } - if (options.push) { - if (!options.push.batchSize) { - options.push.batchSize = 20; - } - } - var _collection = _this; - var _temp = function () { - if (_this.database.multiInstance) { - return Promise.resolve(_this.database.waitForLeadership()).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } -}; +export function replicateP2P(_x) { + return _replicateP2P.apply(this, arguments); +} /** * Because the P2P replication runs between many instances, * we use a Pool instead of returning a single replication state. */ +function _replicateP2P() { + _replicateP2P = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(options) { + var collection, requestCounter, requestFlag, getRequestId, storageToken, pool, connectSub; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + getRequestId = function _getRequestId() { + var count = requestCounter++; + return collection.database.token + '|' + requestFlag + '|' + count; + }; + collection = options.collection; + addRxPlugin(RxDBLeaderElectionPlugin); + + // fill defaults + if (options.pull) { + if (!options.pull.batchSize) { + options.pull.batchSize = 20; + } + } + if (options.push) { + if (!options.push.batchSize) { + options.push.batchSize = 20; + } + } + if (!collection.database.multiInstance) { + _context6.next = 8; + break; + } + _context6.next = 8; + return collection.database.waitForLeadership(); + case 8: + // used to easier debug stuff + requestCounter = 0; + requestFlag = randomCouchString(10); + _context6.next = 12; + return collection.database.storageToken; + case 12: + storageToken = _context6.sent; + pool = new RxP2PReplicationPool(collection, options, options.connectionHandlerCreator(options)); + pool.subs.push(pool.connectionHandler.error$.subscribe(function (err) { + return pool.error$.next(err); + }), pool.connectionHandler.disconnect$.subscribe(function (peer) { + return pool.removePeer(peer); + })); + + /** + * Answer if someone requests our storage token + */ + pool.subs.push(pool.connectionHandler.message$.pipe(filter(function (data) { + return data.message.method === 'token'; + })).subscribe(function (data) { + pool.connectionHandler.send(data.peer, { + id: data.message.id, + result: storageToken + }); + })); + connectSub = pool.connectionHandler.connect$.pipe(filter(function () { + return !pool.canceled; + })).subscribe( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(peer) { + var tokenResponse, peerToken, isMaster, replicationState, masterHandler, masterChangeStreamSub, messageSub; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return sendMessageAndAwaitAnswer(pool.connectionHandler, peer, { + id: getRequestId(), + method: 'token', + params: [] + }); + case 2: + tokenResponse = _context5.sent; + peerToken = tokenResponse.result; + isMaster = isMasterInP2PReplication(collection.database.hashFunction, storageToken, peerToken); + if (isMaster) { + masterHandler = pool.masterReplicationHandler; + masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(function (ev) { + var streamResponse = { + id: 'masterChangeStream$', + result: ev + }; + pool.connectionHandler.send(peer, streamResponse); + }); // clean up the subscription + pool.subs.push(masterChangeStreamSub, pool.connectionHandler.disconnect$.pipe(filter(function (p) { + return p.id === peer.id; + })).subscribe(function () { + return masterChangeStreamSub.unsubscribe(); + })); + messageSub = pool.connectionHandler.message$.pipe(filter(function (data) { + return data.peer.id === peer.id; + }), filter(function (data) { + return data.message.method !== 'token'; + })).subscribe( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(data) { + var msgPeer, message, method, result, response; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + msgPeer = data.peer, message = data.message; + /** + * If it is not a function, + * it means that the client requested the masterChangeStream$ + */ + method = masterHandler[message.method].bind(masterHandler); + _context2.next = 4; + return method.apply(void 0, message.params); + case 4: + result = _context2.sent; + response = { + id: message.id, + result: result + }; + pool.connectionHandler.send(msgPeer, response); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }()); + pool.subs.push(messageSub); + } else { + replicationState = replicateRxCollection({ + replicationIdentifier: [collection.name, options.topic, peerToken].join('||'), + collection: collection, + autoStart: true, + deletedField: '_deleted', + live: true, + retryTime: options.retryTime, + waitForLeadership: false, + pull: options.pull ? Object.assign({}, options.pull, { + handler: function () { + var _handler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(lastPulledCheckpoint) { + var answer; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return sendMessageAndAwaitAnswer(pool.connectionHandler, peer, { + method: 'masterChangesSince', + params: [lastPulledCheckpoint, ensureNotFalsy(options.pull).batchSize], + id: getRequestId() + }); + case 2: + answer = _context3.sent; + return _context3.abrupt("return", answer.result); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function handler(_x4) { + return _handler.apply(this, arguments); + } + return handler; + }(), + stream$: pool.connectionHandler.response$.pipe(filter(function (m) { + return m.response.id === 'masterChangeStream$'; + }), map(function (m) { + return m.response.result; + })) + }) : undefined, + push: options.push ? Object.assign({}, options.push, { + handler: function () { + var _handler2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(docs) { + var answer; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return sendMessageAndAwaitAnswer(pool.connectionHandler, peer, { + method: 'masterWrite', + params: [docs], + id: getRequestId() + }); + case 2: + answer = _context4.sent; + return _context4.abrupt("return", answer.result); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function handler(_x5) { + return _handler2.apply(this, arguments); + } + return handler; + }() + }) : undefined + }); + } + pool.addPeer(peer, replicationState); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x2) { + return _ref.apply(this, arguments); + }; + }()); + pool.subs.push(connectSub); + return _context6.abrupt("return", pool); + case 19: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _replicateP2P.apply(this, arguments); +} export var RxP2PReplicationPool = /*#__PURE__*/function () { function RxP2PReplicationPool(collection, options, connectionHandler) { - var _this2 = this; + var _this = this; this.peerStates$ = new BehaviorSubject(new Map()); this.canceled = false; this.subs = []; @@ -185,13 +243,13 @@ export var RxP2PReplicationPool = /*#__PURE__*/function () { this.options = options; this.connectionHandler = connectionHandler; this.collection.onDestroy.push(function () { - return _this2.cancel(); + return _this.cancel(); }); - this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(collection.storageInstance, collection.conflictHandler, collection.database.hashFunction); + this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(collection.storageInstance, collection.conflictHandler, collection.database.token); } var _proto = RxP2PReplicationPool.prototype; _proto.addPeer = function addPeer(peer, replicationState) { - var _this3 = this; + var _this2 = this; var peerState = { peer: peer, replicationState: replicationState, @@ -200,7 +258,7 @@ export var RxP2PReplicationPool = /*#__PURE__*/function () { this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState)); if (replicationState) { peerState.subs.push(replicationState.error$.subscribe(function (ev) { - return _this3.error$.next(ev); + return _this2.error$.next(ev); })); } }; @@ -223,38 +281,40 @@ export var RxP2PReplicationPool = /*#__PURE__*/function () { return peerStates.size > 0; }))); }; - _proto.cancel = function cancel() { - try { - var _this4 = this; - if (_this4.canceled) { - return Promise.resolve(); - } - _this4.canceled = true; - _this4.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - Array.from(_this4.peerStates$.getValue().keys()).forEach(function (peer) { - _this4.removePeer(peer); - }); - return Promise.resolve(_this4.connectionHandler.destroy()).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto.cancel = /*#__PURE__*/function () { + var _cancel = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var _this3 = this; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!this.canceled) { + _context.next = 2; + break; + } + return _context.abrupt("return"); + case 2: + this.canceled = true; + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + Array.from(this.peerStates$.getValue().keys()).forEach(function (peer) { + _this3.removePeer(peer); + }); + _context.next = 7; + return this.connectionHandler.destroy(); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function cancel() { + return _cancel.apply(this, arguments); } - }; + return cancel; + }(); return RxP2PReplicationPool; }(); -export var RxDBReplicationP2PPlugin = { - name: 'replication-p2p', - init: function init() { - addRxPlugin(RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncP2P = syncP2P; - } - } -}; export * from './p2p-helper'; export * from './p2p-types'; // export * from './connection-handler-webtorrent'; diff --git a/dist/es/plugins/replication-p2p/index.js.map b/dist/es/plugins/replication-p2p/index.js.map index 7755ef12e80..d532d99ac6a 100644 --- a/dist/es/plugins/replication-p2p/index.js.map +++ b/dist/es/plugins/replication-p2p/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["BehaviorSubject","filter","firstValueFrom","map","Subject","addRxPlugin","rxStorageInstanceToReplicationHandler","ensureNotFalsy","getFromMapOrThrow","randomCouchString","RxDBLeaderElectionPlugin","replicateRxCollection","isMasterInP2PReplication","sendMessageAndAwaitAnswer","syncP2P","options","requestCounter","getRequestId","count","collection","database","token","requestFlag","storageToken","pool","RxP2PReplicationPool","connectionHandlerCreator","subs","push","connectionHandler","error$","subscribe","err","next","disconnect$","peer","removePeer","message$","pipe","data","message","method","send","id","result","connectSub","connect$","canceled","params","tokenResponse","peerToken","isMaster","hashFunction","replicationState","masterHandler","masterReplicationHandler","masterChangeStreamSub","masterChangeStream$","ev","streamResponse","p","unsubscribe","messageSub","msgPeer","bind","response","replicationIdentifier","name","topic","join","autoStart","deletedField","live","retryTime","waitForLeadership","pull","Object","assign","handler","lastPulledCheckpoint","batchSize","answer","stream$","response$","m","undefined","docs","addPeer","multiInstance","peerStates$","Map","onDestroy","cancel","storageInstance","conflictHandler","peerState","getValue","set","forEach","sub","awaitFirstPeer","peerStates","size","Array","from","keys","destroy","RxDBReplicationP2PPlugin","init","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-p2p/index.ts"],"sourcesContent":["import { BehaviorSubject, filter, firstValueFrom, map, Subject, Subscription } from 'rxjs';\nimport { addRxPlugin } from '../../plugin';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport type {\n RxCollection,\n RxError,\n RxPlugin,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxTypeError\n} from '../../types';\nimport { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../util';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport { replicateRxCollection } from '../replication';\nimport { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper';\nimport type {\n P2PConnectionHandler,\n P2PPeer,\n P2PPeerState,\n P2PReplicationCheckpoint,\n P2PResponse,\n RxP2PReplicationState,\n SyncOptionsP2P\n} from './p2p-types';\n\n\nexport async function syncP2P(\n this: RxCollection,\n options: SyncOptionsP2P\n): Promise> {\n\n // fill defaults\n if (options.pull) {\n if (!options.pull.batchSize) {\n options.pull.batchSize = 20;\n }\n }\n if (options.push) {\n if (!options.push.batchSize) {\n options.push.batchSize = 20;\n }\n }\n\n const collection = this;\n if (this.database.multiInstance) {\n await this.database.waitForLeadership();\n }\n\n // used to easier debug stuff\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return collection.database.token + '|' + requestFlag + '|' + count;\n }\n\n const storageToken = await this.database.storageToken;\n const pool = new RxP2PReplicationPool(\n this,\n options,\n options.connectionHandlerCreator(options)\n );\n\n\n pool.subs.push(\n pool.connectionHandler.error$.subscribe(err => pool.error$.next(err)),\n pool.connectionHandler.disconnect$.subscribe(peer => pool.removePeer(peer))\n );\n\n /**\n * Answer if someone requests our storage token\n */\n pool.subs.push(\n pool.connectionHandler.message$.pipe(\n filter(data => data.message.method === 'token')\n ).subscribe(data => {\n pool.connectionHandler.send(data.peer, {\n id: data.message.id,\n result: storageToken\n });\n })\n );\n\n const connectSub = pool.connectionHandler.connect$\n .pipe(\n filter(() => !pool.canceled)\n )\n .subscribe(async (peer) => {\n /**\n * TODO ensure both know the correct secret\n */\n const tokenResponse = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n id: getRequestId(),\n method: 'token',\n params: []\n }\n );\n const peerToken: string = tokenResponse.result;\n const isMaster = isMasterInP2PReplication(this.database.hashFunction, storageToken, peerToken);\n\n let replicationState: RxP2PReplicationState | undefined;\n if (isMaster) {\n const masterHandler = pool.masterReplicationHandler;\n const masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(ev => {\n const streamResponse: P2PResponse = {\n id: 'masterChangeStream$',\n result: ev\n };\n pool.connectionHandler.send(peer, streamResponse);\n });\n\n // clean up the subscription\n pool.subs.push(\n masterChangeStreamSub,\n pool.connectionHandler.disconnect$.pipe(\n filter(p => p.id === peer.id)\n ).subscribe(() => masterChangeStreamSub.unsubscribe())\n );\n\n const messageSub = pool.connectionHandler.message$\n .pipe(\n filter(data => data.peer.id === peer.id),\n filter(data => data.message.method !== 'token')\n )\n .subscribe(async (data) => {\n const { peer: msgPeer, message } = data;\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n const method = (masterHandler as any)[message.method].bind(masterHandler);\n const result = await (method as any)(...message.params);\n const response: P2PResponse = {\n id: message.id,\n result\n };\n pool.connectionHandler.send(msgPeer, response);\n });\n pool.subs.push(messageSub);\n } else {\n replicationState = replicateRxCollection({\n replicationIdentifier: [this.name, options.topic, peerToken].join('||'),\n collection: this,\n autoStart: true,\n deletedField: '_deleted',\n live: true,\n retryTime: options.retryTime,\n waitForLeadership: false,\n pull: options.pull ? Object.assign({}, options.pull, {\n async handler(lastPulledCheckpoint: P2PReplicationCheckpoint) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterChangesSince',\n params: [\n lastPulledCheckpoint,\n ensureNotFalsy(options.pull).batchSize\n ],\n id: getRequestId()\n }\n );\n return answer.result;\n },\n stream$: pool.connectionHandler.response$.pipe(\n filter(m => m.response.id === 'masterChangeStream$'),\n map(m => m.response.result)\n )\n\n }) : undefined,\n push: options.push ? Object.assign({}, options.push, {\n async handler(docs: RxReplicationWriteToMasterRow[]) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterWrite',\n params: [docs],\n id: getRequestId()\n }\n );\n return answer.result;\n }\n }) : undefined\n });\n }\n pool.addPeer(peer, replicationState);\n });\n pool.subs.push(connectSub);\n return pool;\n}\n\n\n/**\n * Because the P2P replication runs between many instances,\n * we use a Pool instead of returning a single replication state.\n */\nexport class RxP2PReplicationPool {\n\n peerStates$: BehaviorSubject>> = new BehaviorSubject(new Map());\n canceled: boolean = false;\n masterReplicationHandler: RxReplicationHandler;\n subs: Subscription[] = [];\n\n public error$ = new Subject();\n\n constructor(\n public readonly collection: RxCollection,\n public readonly options: SyncOptionsP2P,\n public readonly connectionHandler: P2PConnectionHandler\n ) {\n this.collection.onDestroy.push(() => this.cancel());\n this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n collection.database.hashFunction\n );\n }\n\n addPeer(\n peer: P2PPeer,\n replicationState?: RxP2PReplicationState\n ) {\n const peerState: P2PPeerState = {\n peer,\n replicationState,\n subs: []\n };\n this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState));\n if (replicationState) {\n peerState.subs.push(\n replicationState.error$.subscribe(ev => this.error$.next(ev))\n );\n }\n }\n removePeer(peer: P2PPeer) {\n const peerState = getFromMapOrThrow(this.peerStates$.getValue(), peer);\n this.peerStates$.getValue().delete(peer);\n this.peerStates$.next(this.peerStates$.getValue());\n peerState.subs.forEach(sub => sub.unsubscribe());\n if (peerState.replicationState) {\n peerState.replicationState.cancel();\n }\n }\n\n // often used in unit tests\n awaitFirstPeer() {\n return firstValueFrom(\n this.peerStates$.pipe(\n filter(peerStates => peerStates.size > 0)\n )\n );\n }\n\n public async cancel() {\n if (this.canceled) {\n return;\n }\n this.canceled = true;\n this.subs.forEach(sub => sub.unsubscribe());\n Array.from(this.peerStates$.getValue().keys()).forEach(peer => {\n this.removePeer(peer);\n });\n await this.connectionHandler.destroy();\n }\n}\n\n\nexport const RxDBReplicationP2PPlugin: RxPlugin = {\n name: 'replication-p2p',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncP2P = syncP2P;\n }\n }\n};\n\n\nexport * from './p2p-helper';\nexport * from './p2p-types';\n// export * from './connection-handler-webtorrent';\n// export * from './connection-handler-p2pcf';\nexport * from './connection-handler-simple-peer';\n"],"mappings":"AAAA,SAASA,eAAe,EAAEC,MAAM,EAAEC,cAAc,EAAEC,GAAG,EAAEC,OAAO,QAAsB,MAAM;AAC1F,SAASC,WAAW,QAAQ,cAAc;AAC1C,SAASC,qCAAqC,QAAQ,4BAA4B;AASlF,SAASC,cAAc,EAAEC,iBAAiB,EAAEC,iBAAiB,QAAQ,YAAY;AACjF,SAASC,wBAAwB,QAAQ,oBAAoB;AAC7D,SAASC,qBAAqB,QAAQ,gBAAgB;AACtD,SAASC,wBAAwB,EAAEC,yBAAyB,QAAQ,cAAc;AAYlF,WAAsBC,OAAO,YAAPA,OAAO,CAEzBC,OAAkC;EAAA,IACM;IAAA;MAmBxC;MACA,IAAIC,cAAc,GAAG,CAAC;MAEtB,SAASC,YAAY,GAAG;QACpB,IAAMC,KAAK,GAAGF,cAAc,EAAE;QAC9B,OAAOG,WAAU,CAACC,QAAQ,CAACC,KAAK,GAAG,GAAG,GAAGC,WAAW,GAAG,GAAG,GAAGJ,KAAK;MACtE;MAJA,IAAMI,WAAW,GAAGb,iBAAiB,CAAC,EAAE,CAAC;MAAC,uBAMf,MAAKW,QAAQ,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AAC;EAAA,OAEYV,MAAM;IAAA,IAAG;MAAA,aACd,IAAI;MAAR,IAAI,OAAK7C,QAAQ,EAAE;QACf;MACJ;MACA,OAAKA,QAAQ,GAAG,IAAI;MACpB,OAAKpB,IAAI,CAACuE,OAAO,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACtC,WAAW,EAAE;MAAA,EAAC;MAC3C0C,KAAK,CAACC,IAAI,CAAC,OAAKf,WAAW,CAACO,QAAQ,EAAE,CAACS,IAAI,EAAE,CAAC,CAACP,OAAO,CAAC,UAAA/D,IAAI,EAAI;QAC3D,OAAKC,UAAU,CAACD,IAAI,CAAC;MACzB,CAAC,CAAC;MAAC,uBACG,OAAKN,iBAAiB,CAAC6E,OAAO,EAAE;IAC1C,CAAC;MAAA;IAAA;EAAA;EAAA;AAAA;AAIL,OAAO,IAAMC,wBAAkC,GAAG;EAC9CxC,IAAI,EAAE,iBAAiB;EACvByC,IAAI,kBAAG;IACHvG,WAAW,CAACK,wBAAwB,CAAC;EACzC,CAAC;EACDmG,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAAClG,OAAO,GAAGA,OAAO;IAC3B;EACJ;AACJ,CAAC;AAGD,cAAc,cAAc;AAC5B,cAAc,aAAa;AAC3B;AACA;AACA,cAAc,kCAAkC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["BehaviorSubject","filter","firstValueFrom","map","Subject","addRxPlugin","rxStorageInstanceToReplicationHandler","ensureNotFalsy","getFromMapOrThrow","randomCouchString","RxDBLeaderElectionPlugin","replicateRxCollection","isMasterInP2PReplication","sendMessageAndAwaitAnswer","replicateP2P","options","getRequestId","count","requestCounter","collection","database","token","requestFlag","pull","batchSize","push","multiInstance","waitForLeadership","storageToken","pool","RxP2PReplicationPool","connectionHandlerCreator","subs","connectionHandler","error$","subscribe","err","next","disconnect$","peer","removePeer","message$","pipe","data","message","method","send","id","result","connectSub","connect$","canceled","params","tokenResponse","peerToken","isMaster","hashFunction","masterHandler","masterReplicationHandler","masterChangeStreamSub","masterChangeStream$","ev","streamResponse","p","unsubscribe","messageSub","msgPeer","bind","response","replicationState","replicationIdentifier","name","topic","join","autoStart","deletedField","live","retryTime","Object","assign","handler","lastPulledCheckpoint","answer","stream$","response$","m","undefined","docs","addPeer","peerStates$","Map","onDestroy","cancel","storageInstance","conflictHandler","peerState","getValue","set","forEach","sub","awaitFirstPeer","peerStates","size","Array","from","keys","destroy"],"sources":["../../../../src/plugins/replication-p2p/index.ts"],"sourcesContent":["import {\n BehaviorSubject,\n filter,\n firstValueFrom,\n map,\n Subject,\n Subscription\n} from 'rxjs';\nimport { addRxPlugin } from '../../plugin';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport type {\n RxCollection,\n RxError,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxTypeError\n} from '../../types';\nimport { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../plugins/utils';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport { replicateRxCollection } from '../replication';\nimport { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper';\nimport type {\n P2PConnectionHandler,\n P2PPeer,\n P2PPeerState,\n P2PReplicationCheckpoint,\n P2PResponse,\n RxP2PReplicationState,\n SyncOptionsP2P\n} from './p2p-types';\n\n\nexport async function replicateP2P(\n options: SyncOptionsP2P\n): Promise> {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n // fill defaults\n if (options.pull) {\n if (!options.pull.batchSize) {\n options.pull.batchSize = 20;\n }\n }\n if (options.push) {\n if (!options.push.batchSize) {\n options.push.batchSize = 20;\n }\n }\n\n if (collection.database.multiInstance) {\n await collection.database.waitForLeadership();\n }\n\n // used to easier debug stuff\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return collection.database.token + '|' + requestFlag + '|' + count;\n }\n\n const storageToken = await collection.database.storageToken;\n const pool = new RxP2PReplicationPool(\n collection,\n options,\n options.connectionHandlerCreator(options)\n );\n\n\n pool.subs.push(\n pool.connectionHandler.error$.subscribe(err => pool.error$.next(err)),\n pool.connectionHandler.disconnect$.subscribe(peer => pool.removePeer(peer))\n );\n\n /**\n * Answer if someone requests our storage token\n */\n pool.subs.push(\n pool.connectionHandler.message$.pipe(\n filter(data => data.message.method === 'token')\n ).subscribe(data => {\n pool.connectionHandler.send(data.peer, {\n id: data.message.id,\n result: storageToken\n });\n })\n );\n\n const connectSub = pool.connectionHandler.connect$\n .pipe(\n filter(() => !pool.canceled)\n )\n .subscribe(async (peer) => {\n /**\n * TODO ensure both know the correct secret\n */\n const tokenResponse = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n id: getRequestId(),\n method: 'token',\n params: []\n }\n );\n const peerToken: string = tokenResponse.result;\n const isMaster = isMasterInP2PReplication(collection.database.hashFunction, storageToken, peerToken);\n\n let replicationState: RxP2PReplicationState | undefined;\n if (isMaster) {\n const masterHandler = pool.masterReplicationHandler;\n const masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(ev => {\n const streamResponse: P2PResponse = {\n id: 'masterChangeStream$',\n result: ev\n };\n pool.connectionHandler.send(peer, streamResponse);\n });\n\n // clean up the subscription\n pool.subs.push(\n masterChangeStreamSub,\n pool.connectionHandler.disconnect$.pipe(\n filter(p => p.id === peer.id)\n ).subscribe(() => masterChangeStreamSub.unsubscribe())\n );\n\n const messageSub = pool.connectionHandler.message$\n .pipe(\n filter(data => data.peer.id === peer.id),\n filter(data => data.message.method !== 'token')\n )\n .subscribe(async (data) => {\n const { peer: msgPeer, message } = data;\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n const method = (masterHandler as any)[message.method].bind(masterHandler);\n const result = await (method as any)(...message.params);\n const response: P2PResponse = {\n id: message.id,\n result\n };\n pool.connectionHandler.send(msgPeer, response);\n });\n pool.subs.push(messageSub);\n } else {\n replicationState = replicateRxCollection({\n replicationIdentifier: [collection.name, options.topic, peerToken].join('||'),\n collection: collection,\n autoStart: true,\n deletedField: '_deleted',\n live: true,\n retryTime: options.retryTime,\n waitForLeadership: false,\n pull: options.pull ? Object.assign({}, options.pull, {\n async handler(lastPulledCheckpoint: P2PReplicationCheckpoint) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterChangesSince',\n params: [\n lastPulledCheckpoint,\n ensureNotFalsy(options.pull).batchSize\n ],\n id: getRequestId()\n }\n );\n return answer.result;\n },\n stream$: pool.connectionHandler.response$.pipe(\n filter(m => m.response.id === 'masterChangeStream$'),\n map(m => m.response.result)\n )\n\n }) : undefined,\n push: options.push ? Object.assign({}, options.push, {\n async handler(docs: RxReplicationWriteToMasterRow[]) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterWrite',\n params: [docs],\n id: getRequestId()\n }\n );\n return answer.result;\n }\n }) : undefined\n });\n }\n pool.addPeer(peer, replicationState);\n });\n pool.subs.push(connectSub);\n return pool;\n}\n\n\n/**\n * Because the P2P replication runs between many instances,\n * we use a Pool instead of returning a single replication state.\n */\nexport class RxP2PReplicationPool {\n\n peerStates$: BehaviorSubject>> = new BehaviorSubject(new Map());\n canceled: boolean = false;\n masterReplicationHandler: RxReplicationHandler;\n subs: Subscription[] = [];\n\n public error$ = new Subject();\n\n constructor(\n public readonly collection: RxCollection,\n public readonly options: SyncOptionsP2P,\n public readonly connectionHandler: P2PConnectionHandler\n ) {\n this.collection.onDestroy.push(() => this.cancel());\n this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n collection.database.token,\n );\n }\n\n addPeer(\n peer: P2PPeer,\n replicationState?: RxP2PReplicationState\n ) {\n const peerState: P2PPeerState = {\n peer,\n replicationState,\n subs: []\n };\n this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState));\n if (replicationState) {\n peerState.subs.push(\n replicationState.error$.subscribe(ev => this.error$.next(ev))\n );\n }\n }\n removePeer(peer: P2PPeer) {\n const peerState = getFromMapOrThrow(this.peerStates$.getValue(), peer);\n this.peerStates$.getValue().delete(peer);\n this.peerStates$.next(this.peerStates$.getValue());\n peerState.subs.forEach(sub => sub.unsubscribe());\n if (peerState.replicationState) {\n peerState.replicationState.cancel();\n }\n }\n\n // often used in unit tests\n awaitFirstPeer() {\n return firstValueFrom(\n this.peerStates$.pipe(\n filter(peerStates => peerStates.size > 0)\n )\n );\n }\n\n public async cancel() {\n if (this.canceled) {\n return;\n }\n this.canceled = true;\n this.subs.forEach(sub => sub.unsubscribe());\n Array.from(this.peerStates$.getValue().keys()).forEach(peer => {\n this.removePeer(peer);\n });\n await this.connectionHandler.destroy();\n }\n}\n\nexport * from './p2p-helper';\nexport * from './p2p-types';\n// export * from './connection-handler-webtorrent';\n// export * from './connection-handler-p2pcf';\nexport * from './connection-handler-simple-peer';\n"],"mappings":";;AAAA,SACIA,eAAe,EACfC,MAAM,EACNC,cAAc,EACdC,GAAG,EACHC,OAAO,QAEJ,MAAM;AACb,SAASC,WAAW,QAAQ,cAAc;AAC1C,SAASC,qCAAqC,QAAQ,4BAA4B;AAQlF,SAASC,cAAc,EAAEC,iBAAiB,EAAEC,iBAAiB,QAAQ,qBAAqB;AAC1F,SAASC,wBAAwB,QAAQ,oBAAoB;AAC7D,SAASC,qBAAqB,QAAQ,gBAAgB;AACtD,SAASC,wBAAwB,EAAEC,yBAAyB,QAAQ,cAAc;AAYlF,gBAAsBC,YAAY;EAAA;AAAA;;AA0KlC;AACA;AACA;AACA;AAHA;EAAA,yEA1KO,kBACHC,OAAkC;IAAA,6CAwBzBC,YAAY;IAAA;MAAA;QAAA;UAAZA,YAAY,4BAAG;YACpB,IAAMC,KAAK,GAAGC,cAAc,EAAE;YAC9B,OAAOC,UAAU,CAACC,QAAQ,CAACC,KAAK,GAAG,GAAG,GAAGC,WAAW,GAAG,GAAG,GAAGL,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C/D,IAAI,CAACkE,OAAO,CAAC,UAAAC,GAAG;MAAA,OAAIA,GAAG,CAACnC,WAAW,EAAE;IAAA,EAAC;IAChD,IAAI+B,SAAS,CAAC1B,gBAAgB,EAAE;MAC5B0B,SAAS,CAAC1B,gBAAgB,CAACuB,MAAM,EAAE;IACvC;EACJ;;EAEA;EAAA;EAAA,OACAQ,cAAc,GAAd,0BAAiB;IACb,OAAOlG,cAAc,CACjB,IAAI,CAACuF,WAAW,CAAC/C,IAAI,CACjBzC,MAAM,CAAC,UAAAoG,UAAU;MAAA,OAAIA,UAAU,CAACC,IAAI,GAAG,CAAC;IAAA,EAAC,CAC5C,CACJ;EACL,CAAC;EAAA,OAEYV,MAAM;IAAA,uEAAnB;MAAA;MAAA;QAAA;UAAA;YAAA,KACQ,IAAI,CAACzC,QAAQ;cAAA;cAAA;YAAA;YAAA;UAAA;YAGjB,IAAI,CAACA,QAAQ,GAAG,IAAI;YACpB,IAAI,CAACnB,IAAI,CAACkE,OAAO,CAAC,UAAAC,GAAG;cAAA,OAAIA,GAAG,CAACnC,WAAW,EAAE;YAAA,EAAC;YAC3CuC,KAAK,CAACC,IAAI,CAAC,IAAI,CAACf,WAAW,CAACO,QAAQ,EAAE,CAACS,IAAI,EAAE,CAAC,CAACP,OAAO,CAAC,UAAA3D,IAAI,EAAI;cAC3D,MAAI,CAACC,UAAU,CAACD,IAAI,CAAC;YACzB,CAAC,CAAC;YAAC;YAAA,OACG,IAAI,CAACN,iBAAiB,CAACyE,OAAO,EAAE;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACzC;IAAA;MAAA;IAAA;IAAA;EAAA;EAAA;AAAA;AAGL,cAAc,cAAc;AAC5B,cAAc,aAAa;AAC3B;AACA;AACA,cAAc,kCAAkC"} \ No newline at end of file diff --git a/dist/es/plugins/replication-p2p/p2p-types.js.map b/dist/es/plugins/replication-p2p/p2p-types.js.map index 19e141004e2..bf9948a6b0a 100644 --- a/dist/es/plugins/replication-p2p/p2p-types.js.map +++ b/dist/es/plugins/replication-p2p/p2p-types.js.map @@ -1 +1 @@ -{"version":3,"file":"p2p-types.js","names":[],"sources":["../../../../src/plugins/replication-p2p/p2p-types.ts"],"sourcesContent":["import { Observable, Subscription } from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxError,\n RxReplicationHandler,\n RxStorageDefaultCheckpoint,\n RxTypeError,\n StringKeys\n} from '../../types';\nimport { RxReplicationState } from '../replication';\nimport { WebsocketMessageResponseType, WebsocketMessageType } from '../replication-websocket';\n\nexport type P2PPeer = {\n id: string;\n};\nexport type P2PReplicationCheckpoint = RxStorageDefaultCheckpoint;\n\n\nexport type P2PMessage = Omit & {\n method: StringKeys> | 'token';\n};\nexport type P2PResponse = Omit;\nexport type PeerWithMessage = {\n peer: P2PPeer;\n message: P2PMessage;\n};\nexport type PeerWithResponse = {\n peer: P2PPeer;\n response: P2PResponse;\n};\n\nexport type P2PConnectionHandler = {\n connect$: Observable;\n disconnect$: Observable;\n message$: Observable;\n response$: Observable;\n error$: Observable;\n send(peer: P2PPeer, message: P2PMessage | P2PResponse): Promise;\n destroy(): Promise;\n};\n\nexport type P2PConnectionHandlerCreator = (\n opts: SyncOptionsP2P\n) => P2PConnectionHandler;\n\nexport type P2PSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {};\n\nexport type P2PSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {};\n\nexport type SyncOptionsP2P = Omit<\nReplicationOptions,\n'pull' |\n'push' |\n'replicationIdentifier' |\n'collection' |\n'deletedField' |\n'live' |\n'autostart' |\n'waitForLeadership'\n> & {\n /**\n * It will only replicate with other instances\n * that use the same topic and\n * are able to prove that they know the secret.\n */\n topic: string;\n secret: string;\n connectionHandlerCreator: P2PConnectionHandlerCreator;\n pull?: P2PSyncPullOptions;\n push?: P2PSyncPushOptions;\n};\n\nexport type RxP2PReplicationState = RxReplicationState;\n\n\nexport type P2PPeerState = {\n peer: P2PPeer;\n // only exists when the peer was picked as master and the own client was picked as fork.\n replicationState?: RxP2PReplicationState;\n // clean this up when removing the peer\n subs: Subscription[];\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"p2p-types.js","names":[],"sources":["../../../../src/plugins/replication-p2p/p2p-types.ts"],"sourcesContent":["import { Observable, Subscription } from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxError,\n RxReplicationHandler,\n RxStorageDefaultCheckpoint,\n RxTypeError,\n StringKeys\n} from '../../types';\nimport { RxReplicationState } from '../replication';\nimport { WebsocketMessageResponseType, WebsocketMessageType } from '../replication-websocket';\n\nexport type P2PPeer = {\n id: string;\n};\nexport type P2PReplicationCheckpoint = RxStorageDefaultCheckpoint;\n\n\nexport type P2PMessage = Omit & {\n method: StringKeys> | 'token';\n};\nexport type P2PResponse = Omit;\nexport type PeerWithMessage = {\n peer: P2PPeer;\n message: P2PMessage;\n};\nexport type PeerWithResponse = {\n peer: P2PPeer;\n response: P2PResponse;\n};\n\nexport type P2PConnectionHandler = {\n connect$: Observable;\n disconnect$: Observable;\n message$: Observable;\n response$: Observable;\n error$: Observable;\n send(peer: P2PPeer, message: P2PMessage | P2PResponse): Promise;\n destroy(): Promise;\n};\n\nexport type P2PConnectionHandlerCreator = (\n opts: SyncOptionsP2P\n) => P2PConnectionHandler;\n\nexport type P2PSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {};\n\nexport type P2PSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {};\n\nexport type SyncOptionsP2P = Omit<\nReplicationOptions,\n'pull' |\n'push' |\n'replicationIdentifier' |\n'deletedField' |\n'live' |\n'autostart' |\n'waitForLeadership'\n> & {\n /**\n * It will only replicate with other instances\n * that use the same topic and\n * are able to prove that they know the secret.\n */\n topic: string;\n secret: string;\n connectionHandlerCreator: P2PConnectionHandlerCreator;\n pull?: P2PSyncPullOptions;\n push?: P2PSyncPushOptions;\n};\n\nexport type RxP2PReplicationState = RxReplicationState;\n\n\nexport type P2PPeerState = {\n peer: P2PPeer;\n // only exists when the peer was picked as master and the own client was picked as fork.\n replicationState?: RxP2PReplicationState;\n // clean this up when removing the peer\n subs: Subscription[];\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/replication-websocket/websocket-client.js b/dist/es/plugins/replication-websocket/websocket-client.js index 3747a3c2900..b83e8c856f7 100644 --- a/dist/es/plugins/replication-websocket/websocket-client.js +++ b/dist/es/plugins/replication-websocket/websocket-client.js @@ -1,7 +1,9 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { replicateRxCollection } from '../replication'; import ReconnectingWebSocket from 'reconnecting-websocket'; import IsomorphicWebSocket from 'isomorphic-ws'; -import { getFromMapOrThrow, randomCouchString } from '../../util'; +import { errorToPlainJson, getFromMapOrThrow, randomCouchString, toArray } from '../../plugins/utils'; import { filter, map, Subject, firstValueFrom, BehaviorSubject } from 'rxjs'; import { newRxError } from '../../rx-error'; /** @@ -22,164 +24,82 @@ function ensureIsWebsocket(w) { * Reuse the same socket even when multiple * collection replicate with the same server at once. */ - -export var replicateWithWebsocketServer = function replicateWithWebsocketServer(options) { - try { - return Promise.resolve(getWebSocket(options.url, options.collection.database.token)).then(function (socketState) { - var wsClient = socketState.socket; - var messages$ = socketState.message$; - var requestCounter = 0; - function getRequestId() { - var count = requestCounter++; - return options.collection.database.token + '|' + requestFlag + '|' + count; - } - var requestFlag = randomCouchString(10); - var replicationState = replicateRxCollection({ - collection: options.collection, - replicationIdentifier: 'websocket-' + options.url, - pull: { - batchSize: options.batchSize, - stream$: messages$.pipe(filter(function (msg) { - return msg.id === 'stream' && msg.collection === options.collection.name; - }), map(function (msg) { - return msg.result; - })), - handler: function handler(lastPulledCheckpoint, batchSize) { - try { - var requestId = getRequestId(); - var request = { - id: requestId, - collection: options.collection.name, - method: 'masterChangesSince', - params: [lastPulledCheckpoint, batchSize] +export var WEBSOCKET_BY_CACHE_KEY = new Map(); +export function getWebSocket(_x, _x2) { + return _getWebSocket.apply(this, arguments); +} +function _getWebSocket() { + _getWebSocket = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(url, + /** + * The value of RxDatabase.token. + */ + databaseToken) { + var cacheKey, has, wsClient, connected$, openPromise, message$, error$; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * Also use the database token as cache-key + * to make it easier to test and debug + * multi-instance setups. + */ + cacheKey = url + '|||' + databaseToken; + has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey); + if (!has) { + ensureIsWebsocket(IsomorphicWebSocket); + wsClient = new ReconnectingWebSocket(url, [], { + WebSocket: IsomorphicWebSocket + }); + connected$ = new BehaviorSubject(false); + openPromise = new Promise(function (res) { + wsClient.onopen = function () { + connected$.next(true); + res(); }; - wsClient.send(JSON.stringify(request)); - return Promise.resolve(firstValueFrom(messages$.pipe(filter(function (msg) { - return msg.id === requestId; - }), map(function (msg) { - return msg.result; - })))); - } catch (e) { - return Promise.reject(e); - } - } - }, - push: { - batchSize: options.batchSize, - handler: function handler(docs) { - var requestId = getRequestId(); - var request = { - id: requestId, - collection: options.collection.name, - method: 'masterWrite', - params: [docs] + }); + wsClient.onclose = function () { + connected$.next(false); + }; + message$ = new Subject(); + wsClient.onmessage = function (messageObj) { + var message = JSON.parse(messageObj.data); + message$.next(message); + }; + error$ = new Subject(); + wsClient.onerror = function (err) { + var emitError = newRxError('RC_STREAM', { + errors: toArray(err).map(function (er) { + return errorToPlainJson(er); + }), + direction: 'pull' + }); + error$.next(emitError); }; - wsClient.send(JSON.stringify(request)); - return firstValueFrom(messages$.pipe(filter(function (msg) { - return msg.id === requestId; - }), map(function (msg) { - return msg.result; - }))); + has = { + url: url, + socket: wsClient, + openPromise: openPromise, + refCount: 1, + connected$: connected$, + message$: message$, + error$: error$ + }; + WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has); + } else { + has.refCount = has.refCount + 1; } - } - }); - socketState.error$.subscribe(function (err) { - return replicationState.subjects.error.next(err); - }); - socketState.connected$.subscribe(function (isConnected) { - if (isConnected) { - /** - * When the client goes offline and online again, - * we have to send a 'RESYNC' signal because the client - * might have missed out events while being offline. - */ - replicationState.reSync(); - - /** - * Because reconnecting creates a new websocket-instance, - * we have to start the changestream from the remote again - * each time. - */ - var streamRequest = { - id: 'stream', - collection: options.collection.name, - method: 'masterChangeStream$', - params: [] - }; - wsClient.send(JSON.stringify(streamRequest)); - } - }); - options.collection.onDestroy.push(function () { - return removeWebSocketRef(options.url, options.collection.database); - }); - return replicationState; - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var getWebSocket = function getWebSocket(url, -/** - * The value of RxDatabase.token. - */ -databaseToken) { - try { - /** - * Also use the database token as cache-key - * to make it easier to test and debug - * multi-instance setups. - */ - var cacheKey = url + '|||' + databaseToken; - var has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey); - if (!has) { - ensureIsWebsocket(IsomorphicWebSocket); - var wsClient = new ReconnectingWebSocket(url, [], { - WebSocket: IsomorphicWebSocket - }); - var connected$ = new BehaviorSubject(false); - var openPromise = new Promise(function (res) { - wsClient.onopen = function () { - connected$.next(true); - res(); - }; - }); - wsClient.onclose = function () { - connected$.next(false); - }; - var message$ = new Subject(); - wsClient.onmessage = function (messageObj) { - var message = JSON.parse(messageObj.data); - message$.next(message); - }; - var error$ = new Subject(); - wsClient.onerror = function (err) { - var emitError = newRxError('RC_STREAM', { - errors: Array.isArray(err) ? err : [err], - direction: 'pull' - }); - error$.next(emitError); - }; - has = { - url: url, - socket: wsClient, - openPromise: openPromise, - refCount: 1, - connected$: connected$, - message$: message$, - error$: error$ - }; - WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has); - } else { - has.refCount = has.refCount + 1; - } - return Promise.resolve(has.openPromise).then(function () { - return has; - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var WEBSOCKET_BY_CACHE_KEY = new Map(); + _context.next = 5; + return has.openPromise; + case 5: + return _context.abrupt("return", has); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getWebSocket.apply(this, arguments); +} export function removeWebSocketRef(url, database) { var cacheKey = url + '|||' + database.token; var obj = getFromMapOrThrow(WEBSOCKET_BY_CACHE_KEY, cacheKey); @@ -190,4 +110,128 @@ export function removeWebSocketRef(url, database) { obj.socket.close(); } } +export function replicateWithWebsocketServer(_x3) { + return _replicateWithWebsocketServer.apply(this, arguments); +} +function _replicateWithWebsocketServer() { + _replicateWithWebsocketServer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(options) { + var socketState, wsClient, messages$, requestCounter, requestFlag, getRequestId, replicationState; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + getRequestId = function _getRequestId() { + var count = requestCounter++; + return options.collection.database.token + '|' + requestFlag + '|' + count; + }; + _context3.next = 3; + return getWebSocket(options.url, options.collection.database.token); + case 3: + socketState = _context3.sent; + wsClient = socketState.socket; + messages$ = socketState.message$; + requestCounter = 0; + requestFlag = randomCouchString(10); + replicationState = replicateRxCollection({ + collection: options.collection, + replicationIdentifier: 'websocket-' + options.url, + live: options.live, + pull: { + batchSize: options.batchSize, + stream$: messages$.pipe(filter(function (msg) { + return msg.id === 'stream' && msg.collection === options.collection.name; + }), map(function (msg) { + return msg.result; + })), + handler: function () { + var _handler = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(lastPulledCheckpoint, batchSize) { + var requestId, request, result; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + requestId = getRequestId(); + request = { + id: requestId, + collection: options.collection.name, + method: 'masterChangesSince', + params: [lastPulledCheckpoint, batchSize] + }; + wsClient.send(JSON.stringify(request)); + _context2.next = 5; + return firstValueFrom(messages$.pipe(filter(function (msg) { + return msg.id === requestId; + }), map(function (msg) { + return msg.result; + }))); + case 5: + result = _context2.sent; + return _context2.abrupt("return", result); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x4, _x5) { + return _handler.apply(this, arguments); + } + return handler; + }() + }, + push: { + batchSize: options.batchSize, + handler: function handler(docs) { + var requestId = getRequestId(); + var request = { + id: requestId, + collection: options.collection.name, + method: 'masterWrite', + params: [docs] + }; + wsClient.send(JSON.stringify(request)); + return firstValueFrom(messages$.pipe(filter(function (msg) { + return msg.id === requestId; + }), map(function (msg) { + return msg.result; + }))); + } + } + }); + socketState.error$.subscribe(function (err) { + return replicationState.subjects.error.next(err); + }); + socketState.connected$.subscribe(function (isConnected) { + if (isConnected) { + /** + * When the client goes offline and online again, + * we have to send a 'RESYNC' signal because the client + * might have missed out events while being offline. + */ + replicationState.reSync(); + + /** + * Because reconnecting creates a new websocket-instance, + * we have to start the changestream from the remote again + * each time. + */ + var streamRequest = { + id: 'stream', + collection: options.collection.name, + method: 'masterChangeStream$', + params: [] + }; + wsClient.send(JSON.stringify(streamRequest)); + } + }); + options.collection.onDestroy.push(function () { + return removeWebSocketRef(options.url, options.collection.database); + }); + return _context3.abrupt("return", replicationState); + case 13: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _replicateWithWebsocketServer.apply(this, arguments); +} //# sourceMappingURL=websocket-client.js.map \ No newline at end of file diff --git a/dist/es/plugins/replication-websocket/websocket-client.js.map b/dist/es/plugins/replication-websocket/websocket-client.js.map index 45aaf61003d..d572714b33d 100644 --- a/dist/es/plugins/replication-websocket/websocket-client.js.map +++ b/dist/es/plugins/replication-websocket/websocket-client.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-client.js","names":["replicateRxCollection","ReconnectingWebSocket","IsomorphicWebSocket","getFromMapOrThrow","randomCouchString","filter","map","Subject","firstValueFrom","BehaviorSubject","newRxError","ensureIsWebsocket","w","is","CLOSING","console","dir","Error","replicateWithWebsocketServer","options","getWebSocket","url","collection","database","token","socketState","wsClient","socket","messages$","message$","requestCounter","getRequestId","count","requestFlag","replicationState","replicationIdentifier","pull","batchSize","stream$","pipe","msg","id","name","result","handler","lastPulledCheckpoint","requestId","request","method","params","send","JSON","stringify","push","docs","error$","subscribe","err","subjects","error","next","connected$","isConnected","reSync","streamRequest","onDestroy","removeWebSocketRef","databaseToken","cacheKey","has","WEBSOCKET_BY_CACHE_KEY","get","WebSocket","openPromise","Promise","res","onopen","onclose","onmessage","messageObj","message","parse","data","onerror","emitError","errors","Array","isArray","direction","refCount","set","Map","obj","complete","close"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import { replicateRxCollection, RxReplicationState } from '../replication';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n getFromMapOrThrow,\n randomCouchString\n} from '../../util';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport {\n RxDatabase,\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types';\nimport { newRxError } from '../../rx-error';\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: ReconnectingWebSocket;\n refCount: number;\n openPromise: Promise;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapter from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nfunction ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n/**\n * Reuse the same socket even when multiple\n * collection replicate with the same server at once.\n */\nexport const WEBSOCKET_BY_CACHE_KEY: Map = new Map();\nexport async function getWebSocket(\n url: string,\n /**\n * The value of RxDatabase.token.\n */\n databaseToken: string\n): Promise {\n /**\n * Also use the database token as cache-key\n * to make it easier to test and debug\n * multi-instance setups.\n */\n const cacheKey = url + '|||' + databaseToken;\n\n let has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey);\n if (!has) {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n\n const connected$ = new BehaviorSubject(false);\n const openPromise = new Promise(res => {\n wsClient.onopen = () => {\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n const message$ = new Subject();\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n const emitError = newRxError('RC_STREAM', {\n errors: Array.isArray(err) ? err as any : [err],\n direction: 'pull'\n });\n error$.next(emitError);\n };\n\n\n has = {\n url,\n socket: wsClient,\n openPromise,\n refCount: 1,\n connected$,\n message$,\n error$\n };\n WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n\n\n await has.openPromise;\n return has;\n}\n\nexport function removeWebSocketRef(\n url: string,\n database: RxDatabase\n) {\n const cacheKey = url + '|||' + database.token;\n const obj = getFromMapOrThrow(WEBSOCKET_BY_CACHE_KEY, cacheKey);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n WEBSOCKET_BY_CACHE_KEY.delete(cacheKey);\n obj.connected$.complete();\n obj.socket.close();\n }\n}\n\n\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const socketState = await getWebSocket(options.url, options.collection.database.token);\n const wsClient = socketState.socket;\n\n const messages$ = socketState.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: 'websocket-' + options.url,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n socketState.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n socketState.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => removeWebSocketRef(options.url, options.collection.database));\n return replicationState;\n}\n"],"mappings":"AAAA,SAASA,qBAAqB,QAA4B,gBAAgB;AAM1E,OAAOC,qBAAqB,MAAM,wBAAwB;AAC1D,OAAOC,mBAAmB,MAAM,eAAe;AAC/C,SACIC,iBAAiB,EACjBC,iBAAiB,QACd,YAAY;AACnB,SACIC,MAAM,EACNC,GAAG,EACHC,OAA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G,EAAHA,GAAG;QACHM,MAAM,EAAED,QAAQ;QAChB+C,WAAW,EAAXA,WAAW;QACXgB,QAAQ,EAAE,CAAC;QACX5B,UAAU,EAAVA,UAAU;QACVhC,QAAQ,EAARA,QAAQ;QACR0B,MAAM,EAANA;MACJ,CAAC;MACDe,sBAAsB,CAACoB,GAAG,CAACtB,QAAQ,EAAEC,GAAG,CAAC;IAC7C,CAAC,MAAM;MACHA,GAAG,CAACoB,QAAQ,GAAGpB,GAAG,CAACoB,QAAQ,GAAG,CAAC;IACnC;IAAC,uBAGKpB,GAAG,CAACI,WAAW;MACrB,OAAOJ,GAAG;IAAC;EACf,CAAC;IAAA;EAAA;AAAA;AAtED,OAAO,IAAMC,sBAA0D,GAAG,IAAIqB,GAAG,EAAE;AAwEnF,OAAO,SAASzB,kBAAkB,CAC9B7C,GAAW,EACXE,QAAoB,EACtB;EACE,IAAM6C,QAAQ,GAAG/C,GAAG,GAAG,KAAK,GAAGE,QAAQ,CAACC,KAAK;EAC7C,IAAMoE,GAAG,GAAGzF,iBAAiB,CAACmE,sBAAsB,EAAEF,QAAQ,CAAC;EAC/DwB,GAAG,CAACH,QAAQ,GAAGG,GAAG,CAACH,QAAQ,GAAG,CAAC;EAC/B,IAAIG,GAAG,CAACH,QAAQ,KAAK,CAAC,EAAE;IACpBnB,sBAAsB,UAAO,CAACF,QAAQ,CAAC;IACvCwB,GAAG,CAAC/B,UAAU,CAACgC,QAAQ,EAAE;IACzBD,GAAG,CAACjE,MAAM,CAACmE,KAAK,EAAE;EACtB;AACJ"} \ No newline at end of file +{"version":3,"file":"websocket-client.js","names":["replicateRxCollection","ReconnectingWebSocket","IsomorphicWebSocket","errorToPlainJson","getFromMapOrThrow","randomCouchString","toArray","filter","map","Subject","firstValueFrom","BehaviorSubject","newRxError","ensureIsWebsocket","w","is","CLOSING","console","dir","Error","WEBSOCKET_BY_CACHE_KEY","Map","getWebSocket","url","databaseToken","cacheKey","has","get","wsClient","WebSocket","connected$","openPromise","Promise","res","onopen","next","onclose","message$","onmessage","messageObj","message","JSON","parse","data","error$","onerror","err","emitError","errors","er","direction","socket","refCount","set","removeWebSocketRef","database","token","obj","complete","close","replicateWithWebsocketServer","options","getRequestId","count","requestCounter","collection","requestFlag","socketState","messages$","replicationState","replicationIdentifier","live","pull","batchSize","stream$","pipe","msg","id","name","result","handler","lastPulledCheckpoint","requestId","request","method","params","send","stringify","push","docs","subscribe","subjects","error","isConnected","reSync","streamRequest","onDestroy"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import { replicateRxCollection, RxReplicationState } from '../replication';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n errorToPlainJson,\n getFromMapOrThrow,\n randomCouchString,\n toArray\n} from '../../plugins/utils';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport {\n RxDatabase,\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types';\nimport { newRxError } from '../../rx-error';\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: ReconnectingWebSocket;\n refCount: number;\n openPromise: Promise;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapter from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nfunction ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n/**\n * Reuse the same socket even when multiple\n * collection replicate with the same server at once.\n */\nexport const WEBSOCKET_BY_CACHE_KEY: Map = new Map();\nexport async function getWebSocket(\n url: string,\n /**\n * The value of RxDatabase.token.\n */\n databaseToken: string\n): Promise {\n /**\n * Also use the database token as cache-key\n * to make it easier to test and debug\n * multi-instance setups.\n */\n const cacheKey = url + '|||' + databaseToken;\n\n let has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey);\n if (!has) {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n\n const connected$ = new BehaviorSubject(false);\n const openPromise = new Promise(res => {\n wsClient.onopen = () => {\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n const message$ = new Subject();\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n const emitError = newRxError('RC_STREAM', {\n errors: toArray(err).map((er: any) => errorToPlainJson(er)),\n direction: 'pull'\n });\n error$.next(emitError);\n };\n\n\n has = {\n url,\n socket: wsClient,\n openPromise,\n refCount: 1,\n connected$,\n message$,\n error$\n };\n WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n\n\n await has.openPromise;\n return has;\n}\n\nexport function removeWebSocketRef(\n url: string,\n database: RxDatabase\n) {\n const cacheKey = url + '|||' + database.token;\n const obj = getFromMapOrThrow(WEBSOCKET_BY_CACHE_KEY, cacheKey);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n WEBSOCKET_BY_CACHE_KEY.delete(cacheKey);\n obj.connected$.complete();\n obj.socket.close();\n }\n}\n\n\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const socketState = await getWebSocket(options.url, options.collection.database.token);\n const wsClient = socketState.socket;\n\n const messages$ = socketState.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: 'websocket-' + options.url,\n live: options.live,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n socketState.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n socketState.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => removeWebSocketRef(options.url, options.collection.database));\n return replicationState;\n}\n"],"mappings":";;AAAA,SAASA,qBAAqB,QAA4B,gBAAgB;AAM1E,OAAOC,qBAAqB,MAAM,wBAAwB;AAC1D,OAAOC,mBAAmB,MAAM,eAAe;AAC/C,SACIC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,EACjBC,OAAO,QACJ,qBAAqB;AAC5B,SACIC,MAAM,E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QAAA;UAAA;MAAA;IAAA;EAAA,CAC1B;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/replication-websocket/websocket-server.js b/dist/es/plugins/replication-websocket/websocket-server.js index 08c2c04c3a2..31c85649ef6 100644 --- a/dist/es/plugins/replication-websocket/websocket-server.js +++ b/dist/es/plugins/replication-websocket/websocket-server.js @@ -1,8 +1,10 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } import { rxStorageInstanceToReplicationHandler } from '../../replication-protocol'; -import { PROMISE_RESOLVE_VOID } from '../../util'; +import { PROMISE_RESOLVE_VOID } from '../../plugins/utils'; import { Subject } from 'rxjs'; export function startSocketServer(options) { var _require = require('isomorphic-ws' + ''), @@ -63,7 +65,7 @@ export function startWebsocketServer(options) { var handler = replicationHandlerByCollection.get(collectionName); if (!handler) { var collection = database.collections[collectionName]; - handler = rxStorageInstanceToReplicationHandler(collection.storageInstance, collection.conflictHandler, database.hashFunction); + handler = rxStorageInstanceToReplicationHandler(collection.storageInstance, collection.conflictHandler, database.token); replicationHandlerByCollection.set(collectionName, handler); } return handler; @@ -75,42 +77,56 @@ export function startWebsocketServer(options) { return fn(); }); }; - ws.on('message', function (messageString) { - try { - var message = JSON.parse(messageString); - var handler = getReplicationHandler(message.collection); - var method = handler[message.method]; - - /** - * If it is not a function, - * it means that the client requested the masterChangeStream$ - */ - if (typeof method !== 'function') { - var changeStreamSub = handler.masterChangeStream$.subscribe(function (ev) { - var streamResponse = { - id: 'stream', - collection: message.collection, - result: ev - }; - ws.send(JSON.stringify(streamResponse)); - }); - onCloseHandlers.push(function () { - return changeStreamSub.unsubscribe(); - }); - return Promise.resolve(); - } - return Promise.resolve(method.apply(void 0, message.params)).then(function (result) { - var response = { - id: message.id, - collection: message.collection, - result: result - }; - ws.send(JSON.stringify(response)); - }); - } catch (e) { - return Promise.reject(e); - } - }); + ws.on('message', /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(messageString) { + var message, handler, method, changeStreamSub, result, response; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + message = JSON.parse(messageString); + handler = getReplicationHandler(message.collection); + method = handler[message.method]; + /** + * If it is not a function, + * it means that the client requested the masterChangeStream$ + */ + if (!(typeof method !== 'function')) { + _context.next = 7; + break; + } + changeStreamSub = handler.masterChangeStream$.subscribe(function (ev) { + var streamResponse = { + id: 'stream', + collection: message.collection, + result: ev + }; + ws.send(JSON.stringify(streamResponse)); + }); + onCloseHandlers.push(function () { + return changeStreamSub.unsubscribe(); + }); + return _context.abrupt("return"); + case 7: + _context.next = 9; + return method.apply(void 0, message.params); + case 9: + result = _context.sent; + response = { + id: message.id, + collection: message.collection, + result: result + }; + ws.send(JSON.stringify(response)); + case 12: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); }); return serverState; } diff --git a/dist/es/plugins/replication-websocket/websocket-server.js.map b/dist/es/plugins/replication-websocket/websocket-server.js.map index f66479a7c6e..c30934f5f22 100644 --- a/dist/es/plugins/replication-websocket/websocket-server.js.map +++ b/dist/es/plugins/replication-websocket/websocket-server.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-server.js","names":["rxStorageInstanceToReplicationHandler","PROMISE_RESOLVE_VOID","Subject","startSocketServer","options","require","WebSocketServer","wss","port","path","closed","closeServer","onConnection$","complete","Promise","res","rej","clients","ws","close","err","on","next","server","asObservable","startWebsocketServer","serverState","database","onDestroy","push","replicationHandlerByCollection","Map","getReplicationHandler","collectionName","collections","Error","handler","get","collection","storageInstance","conflictHandler","hashFunction","set","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxReplicationHandler\n} from '../../types';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport {\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport { Subject } from 'rxjs';\n\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const { WebSocketServer } = require('isomorphic-ws' + '');\n const wss = new WebSocketServer({\n port: options.port,\n path: options.path\n });\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const serverState = startSocketServer(options);\n\n const database = options.database;\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n const replicationHandlerByCollection: Map> = new Map();\n function getReplicationHandler(collectionName: string): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n let handler = replicationHandlerByCollection.get(collectionName);\n if (!handler) {\n const collection = database.collections[collectionName];\n handler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.hashFunction\n );\n replicationHandlerByCollection.set(collectionName, handler);\n }\n return handler;\n }\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandler(message.collection);\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":";;;AAcA,SAASA,qCAAqC,QAAQ,4BAA4B;AAClF,SACIC,oBAAoB,QACjB,YAAY;AACnB,SAASC,OAAO,QAAQ,MAAM;AAG9B,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,KAAK,UAAU,EAAE;UAC9B,IAAMC,eAAe,GAAGjB,OAAO,CAACkB,mBAAmB,CAACX,SAAS,CAAC,UAAAY,EAAE,EAAI;YAChE,IAAMC,cAA4C,GAAG;cACjDC,EAAE,EAAE,QAAQ;cACZnB,UAAU,EAAEW,OAAO,CAACX,UAAU;cAC9BoB,MAAM,EAAEH;YACZ,CAAC;YACDrC,EAAE,CAACyC,IAAI,CAACT,IAAI,CAACU,SAAS,CAACJ,cAAc,CAAC,CAAC;UAC3C,CAAC,CAAC;UACFZ,eAAe,CAACf,IAAI,CAAC;YAAA,OAAMwB,eAAe,CAACQ,WAAW,EAAE;UAAA,EAAC;UACzD;QACJ;QAAC,uBACqBT,MAAM,eAAYH,OAAO,CAACa,MAAM,CAAC,iBAAjDJ,MAAM;UACZ,IAAMK,QAAsC,GAAG;YAC3CN,EAAE,EAAER,OAAO,CAACQ,EAAE;YACdnB,UAAU,EAAEW,OAAO,CAACX,UAAU;YAC9BoB,MAAM,EAANA;UACJ,CAAC;UACDxC,EAAE,CAACyC,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;QAAC;MACtC,CAAC;QAAA;MAAA;IAAA,EAAC;EACN,CAAC,CAAC;EAGF,OAAOrC,WAAW;AACtB"} \ No newline at end of file +{"version":3,"file":"websocket-server.js","names":["rxStorageInstanceToReplicationHandler","PROMISE_RESOLVE_VOID","Subject","startSocketServer","options","require","WebSocketServer","wss","port","path","closed","closeServer","onConnection$","complete","Promise","res","rej","clients","ws","close","err","on","next","server","asObservable","startWebsocketServer","serverState","database","onDestroy","push","replicationHandlerByCollection","Map","getReplicationHandler","collectionName","collections","Error","handler","get","collection","storageInstance","conflictHandler","token","set","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxReplicationHandler\n} from '../../types';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport {\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils';\nimport { Subject } from 'rxjs';\n\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const { WebSocketServer } = require('isomorphic-ws' + '');\n const wss = new WebSocketServer({\n port: options.port,\n path: options.path\n });\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const serverState = startSocketServer(options);\n\n const database = options.database;\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n const replicationHandlerByCollection: Map> = new Map();\n function getReplicationHandler(collectionName: string): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n let handler = replicationHandlerByCollection.get(collectionName);\n if (!handler) {\n const collection = database.collections[collectionName];\n handler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.token\n );\n replicationHandlerByCollection.set(collectionName, handler);\n }\n return handler;\n }\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandler(message.collection);\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":";;;;;AAcA,SAASA,qCAAqC,QAAQ,4BAA4B;AAClF,SACIC,oBAAoB,QACjB,qBAAqB;AAC5B,SAASC,OAAO,QAAQ,MAAM;AAG9B,OAAO,SAASC,iBAAiB,CAACC,OAAsB,EAAwB;EAC5E,eAA4BC,OAAO,CAAC,eAAe,GAAG,EAAE,CAAC;IAAjDC,eAAe,YAAfA,eAAe;EACvB,IAAMC,GAAG,GAAG,IAAID,eAAe,CAAC;IAC5BE,IAAI,EAAEJ,OAAO,CAACI,IAAI;IAClBC,IAAI,EAAEL,OAAO,CAACK;EAClB,CAAC,CAAC;EACF,IAAIC,MAAM,GAAG,KAAK;EAClB,SAASC,WAAW,GAAG;IACnB,IAAID,MAAM,EAAE;MACR,OAAOT,oBAAoB;IAC/B;IACAS,MAAM,GAAG,IAAI;IACbE,aAAa,CAACC,QAAQ,EAAE;IACxB,OAAO,IAAIC,OAAO,CAAO,UAACC,GAAG,EAAEC,GAAG,EAAK;MACnC;AACZ;AACA;AACA;AACA;MACY,qDAAiBT,GAAG,CAACU,OAAO,wCAAE;QAAA,IAAnBC,EAAE;QACTA,EAAE,CAACC,KAAK,EAAE;MACd;MACAZ,GAAG,CAACY,KAAK,CAAC,UAACC,GA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EAANA;cACJ,CAAC;cACDxC,EAAE,CAACyC,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;YAAC;YAAA;cAAA;UAAA;QAAA;MAAA,CACrC;MAAA;QAAA;MAAA;IAAA,IAAC;EACN,CAAC,CAAC;EAGF,OAAOrC,WAAW;AACtB"} \ No newline at end of file diff --git a/dist/es/plugins/replication-websocket/websocket-types.js.map b/dist/es/plugins/replication-websocket/websocket-types.js.map index e463e41a496..4125dc4e21f 100644 --- a/dist/es/plugins/replication-websocket/websocket-types.js.map +++ b/dist/es/plugins/replication-websocket/websocket-types.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n collection: RxCollection;\n url: string;\n batchSize?: number;\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys>;\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n collection: RxCollection;\n url: string;\n batchSize?: number;\n live?: boolean;\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys>;\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/replication/index.js b/dist/es/plugins/replication/index.js index e751609e841..dc8c1158182 100644 --- a/dist/es/plugins/replication/index.js +++ b/dist/es/plugins/replication/index.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * This plugin contains the primitives to create * a RxDB client-server replication. @@ -6,171 +8,13 @@ */ import { BehaviorSubject, combineLatest, mergeMap, Subject } from 'rxjs'; -import { ensureNotFalsy, fastUnsecureHash, flatClone, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE } from '../../util'; +import { RxDBLeaderElectionPlugin } from '../leader-election'; +import { ensureNotFalsy, errorToPlainJson, fastUnsecureHash, flatClone, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, toArray } from '../../plugins/utils'; import { awaitRxStorageReplicationFirstInSync, awaitRxStorageReplicationInSync, cancelRxStorageReplication, replicateRxStorageInstance, RX_REPLICATION_META_INSTANCE_SCHEMA } from '../../replication-protocol'; import { newRxError } from '../../rx-error'; import { awaitRetry, DEFAULT_MODIFIER, swapDefaultDeletedTodeletedField, swapdeletedFieldToDefaultDeleted } from './replication-helper'; import { addConnectedStorageToCollection } from '../../rx-database-internal-store'; -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} +import { addRxPlugin } from '../../plugin'; export var REPLICATION_STATE_BY_COLLECTION = new WeakMap(); export var RxReplicationState = /*#__PURE__*/function () { function RxReplicationState( @@ -235,179 +79,233 @@ export var RxReplicationState = /*#__PURE__*/function () { this.startPromise = startPromise; } var _proto = RxReplicationState.prototype; - _proto.start = function start() { - try { + _proto.start = /*#__PURE__*/function () { + var _start = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() { var _this2 = this; - if (_this2.isStopped()) { - return Promise.resolve(); - } - - // fill in defaults for pull & push - var pullModifier = _this2.pull && _this2.pull.modifier ? _this2.pull.modifier : DEFAULT_MODIFIER; - var pushModifier = _this2.push && _this2.push.modifier ? _this2.push.modifier : DEFAULT_MODIFIER; - var database = _this2.collection.database; - var metaInstanceCollectionName = _this2.collection.name + '-rx-replication-' + _this2.replicationIdentifierHash; - return Promise.resolve(Promise.all([_this2.collection.database.storage.createStorageInstance({ - databaseName: database.name, - collectionName: metaInstanceCollectionName, - databaseInstanceToken: database.token, - multiInstance: database.multiInstance, - // TODO is this always false? - options: {}, - schema: RX_REPLICATION_META_INSTANCE_SCHEMA - }), addConnectedStorageToCollection(_this2.collection, metaInstanceCollectionName, RX_REPLICATION_META_INSTANCE_SCHEMA)])).then(function (_ref) { - var metaInstance = _ref[0]; - function _temp2() { - _this2.callOnStart(); - } - _this2.metaInstance = metaInstance; - _this2.internalReplicationState = replicateRxStorageInstance({ - pushBatchSize: _this2.push && _this2.push.batchSize ? _this2.push.batchSize : 100, - pullBatchSize: _this2.pull && _this2.pull.batchSize ? _this2.pull.batchSize : 100, - forkInstance: _this2.collection.storageInstance, - metaInstance: _this2.metaInstance, - hashFunction: database.hashFunction, - identifier: 'rx-replication-' + _this2.replicationIdentifierHash, - conflictHandler: _this2.collection.conflictHandler, - replicationHandler: { - masterChangeStream$: _this2.remoteEvents$.asObservable().pipe(mergeMap(function (ev) { - try { - if (ev === 'RESYNC') { - return Promise.resolve(ev); - } - var useEv = flatClone(ev); - if (_this2.deletedField !== '_deleted') { - useEv.documents = useEv.documents.map(function (doc) { - return swapdeletedFieldToDefaultDeleted(_this2.deletedField, doc); - }); - } - return Promise.resolve(Promise.all(useEv.documents.map(function (d) { - return pullModifier(d); - }))).then(function (_Promise$all) { - useEv.documents = _Promise$all; - return useEv; - }); - } catch (e) { - return Promise.reject(e); - } - })), - masterChangesSince: function (checkpoint, batchSize) { - try { - var _temp5 = function _temp5() { - if (_this2.isStopped()) { - return { - checkpoint: null, - documents: [] - }; - } - var useResult = flatClone(result); - if (_this2.deletedField !== '_deleted') { - useResult.documents = useResult.documents.map(function (doc) { - return swapdeletedFieldToDefaultDeleted(_this2.deletedField, doc); - }); - } - return Promise.resolve(Promise.all(useResult.documents.map(function (d) { - return pullModifier(d); - }))).then(function (_Promise$all2) { - useResult.documents = _Promise$all2; - return useResult; - }); - }; - if (!_this2.pull) { - return Promise.resolve({ - checkpoint: null, - documents: [] - }); - } - - /** - * Retries must be done here in the replication primitives plugin, - * because the replication protocol itself has no - * error handling. - */ - var done = false; - var result = {}; - var _temp4 = _for(function () { - return !done && !_this2.isStopped(); - }, void 0, function () { - var _temp3 = _catch(function () { - return Promise.resolve(_this2.pull.handler(checkpoint, batchSize)).then(function (_this2$pull$handler) { - result = _this2$pull$handler; - done = true; - }); - }, function (err) { - var emitError = newRxError('RC_PULL', { - checkpoint: checkpoint, - errors: Array.isArray(err) ? err : [err], - direction: 'pull' - }); - _this2.subjects.error.next(emitError); - return Promise.resolve(awaitRetry(_this2.collection, ensureNotFalsy(_this2.retryTime))).then(function () {}); - }); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }, - masterWrite: function (rows) { - try { - if (!_this2.push) { - return Promise.resolve([]); - } - var done = false; - return Promise.resolve(Promise.all(rows.map(function (row) { - try { - return Promise.resolve(pushModifier(row.newDocumentState)).then(function (_pushModifier) { - function _temp9() { - if (_this2.deletedField !== '_deleted') { - row.newDocumentState = swapDefaultDeletedTodeletedField(_this2.deletedField, row.newDocumentState); - if (row.assumedMasterState) { - row.assumedMasterState = swapDefaultDeletedTodeletedField(_this2.deletedField, row.assumedMasterState); + var pullModifier, pushModifier, database, metaInstanceCollectionName, _yield$Promise$all, metaInstance; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!this.isStopped()) { + _context5.next = 2; + break; + } + return _context5.abrupt("return"); + case 2: + // fill in defaults for pull & push + pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER; + pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER; + database = this.collection.database; + metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash; + _context5.next = 8; + return Promise.all([this.collection.database.storage.createStorageInstance({ + databaseName: database.name, + collectionName: metaInstanceCollectionName, + databaseInstanceToken: database.token, + multiInstance: database.multiInstance, + // TODO is this always false? + options: {}, + schema: RX_REPLICATION_META_INSTANCE_SCHEMA + }), addConnectedStorageToCollection(this.collection, metaInstanceCollectionName, RX_REPLICATION_META_INSTANCE_SCHEMA)]); + case 8: + _yield$Promise$all = _context5.sent; + metaInstance = _yield$Promise$all[0]; + this.metaInstance = metaInstance; + this.internalReplicationState = replicateRxStorageInstance({ + pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100, + pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100, + forkInstance: this.collection.storageInstance, + metaInstance: this.metaInstance, + hashFunction: database.hashFunction, + identifier: 'rx-replication-' + this.replicationIdentifierHash, + conflictHandler: this.collection.conflictHandler, + replicationHandler: { + masterChangeStream$: this.remoteEvents$.asObservable().pipe(mergeMap( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(ev) { + var useEv; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(ev === 'RESYNC')) { + _context.next = 2; + break; + } + return _context.abrupt("return", ev); + case 2: + useEv = flatClone(ev); + if (_this2.deletedField !== '_deleted') { + useEv.documents = useEv.documents.map(function (doc) { + return swapdeletedFieldToDefaultDeleted(_this2.deletedField, doc); + }); } - } - return row; + _context.next = 6; + return Promise.all(useEv.documents.map(function (d) { + return pullModifier(d); + })); + case 6: + useEv.documents = _context.sent; + return _context.abrupt("return", useEv); + case 8: + case "end": + return _context.stop(); } - row.newDocumentState = _pushModifier; - var _temp8 = function () { - if (row.assumedMasterState) { - return Promise.resolve(pushModifier(row.assumedMasterState)).then(function (_pushModifier2) { - row.assumedMasterState = _pushModifier2; + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }())), + masterChangesSince: function () { + var _masterChangesSince = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(checkpoint, batchSize) { + var done, result, emitError, useResult; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (_this2.pull) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", { + checkpoint: null, + documents: [] }); - } - }(); - return _temp8 && _temp8.then ? _temp8.then(_temp9) : _temp9(_temp8); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function (useRows) { - var _exit = false; - function _temp7(_result2) { - if (_exit) return _result2; - if (_this2.isStopped()) { - return []; - } - var conflicts = ensureNotFalsy(result).map(function (doc) { - return swapdeletedFieldToDefaultDeleted(_this2.deletedField, doc); - }); - return conflicts; + case 2: + /** + * Retries must be done here in the replication primitives plugin, + * because the replication protocol itself has no + * error handling. + */ + done = false; + result = {}; + case 4: + if (!(!done && !_this2.isStopped())) { + _context2.next = 20; + break; + } + _context2.prev = 5; + _context2.next = 8; + return _this2.pull.handler(checkpoint, batchSize); + case 8: + result = _context2.sent; + done = true; + _context2.next = 18; + break; + case 12: + _context2.prev = 12; + _context2.t0 = _context2["catch"](5); + emitError = newRxError('RC_PULL', { + checkpoint: checkpoint, + errors: toArray(_context2.t0).map(function (er) { + return errorToPlainJson(er); + }), + direction: 'pull' + }); + _this2.subjects.error.next(emitError); + _context2.next = 18; + return awaitRetry(_this2.collection, ensureNotFalsy(_this2.retryTime)); + case 18: + _context2.next = 4; + break; + case 20: + if (!_this2.isStopped()) { + _context2.next = 22; + break; + } + return _context2.abrupt("return", { + checkpoint: null, + documents: [] + }); + case 22: + useResult = flatClone(result); + if (_this2.deletedField !== '_deleted') { + useResult.documents = useResult.documents.map(function (doc) { + return swapdeletedFieldToDefaultDeleted(_this2.deletedField, doc); + }); + } + _context2.next = 26; + return Promise.all(useResult.documents.map(function (d) { + return pullModifier(d); + })); + case 26: + useResult.documents = _context2.sent; + return _context2.abrupt("return", useResult); + case 28: + case "end": + return _context2.stop(); + } + }, _callee2, null, [[5, 12]]); + })); + function masterChangesSince(_x2, _x3) { + return _masterChangesSince.apply(this, arguments); } - var result = null; - var _temp6 = _for(function () { - return !_exit && !done && !_this2.isStopped(); - }, void 0, function () { - return _catch(function () { - return Promise.resolve(_this2.push.handler(useRows)).then(function (_this2$push$handler) { - result = _this2$push$handler; - /** - * It is a common problem that people have wrongly behaving backend - * that do not return an array with the conflicts on push requests. - * So we run this check here to make it easier to debug. - * @link https://github.com/pubkey/rxdb/issues/4103 - */ - if (!Array.isArray(result)) { + return masterChangesSince; + }(), + masterWrite: function () { + var _masterWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(rows) { + var done, useRows, result, emitError, conflicts; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (_this2.push) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", []); + case 2: + done = false; + _context4.next = 5; + return Promise.all(rows.map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(row) { + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return pushModifier(row.newDocumentState); + case 2: + row.newDocumentState = _context3.sent; + if (!row.assumedMasterState) { + _context3.next = 7; + break; + } + _context3.next = 6; + return pushModifier(row.assumedMasterState); + case 6: + row.assumedMasterState = _context3.sent; + case 7: + if (_this2.deletedField !== '_deleted') { + row.newDocumentState = swapDefaultDeletedTodeletedField(_this2.deletedField, row.newDocumentState); + if (row.assumedMasterState) { + row.assumedMasterState = swapDefaultDeletedTodeletedField(_this2.deletedField, row.assumedMasterState); + } + } + return _context3.abrupt("return", row); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x5) { + return _ref2.apply(this, arguments); + }; + }())); + case 5: + useRows = _context4.sent; + result = null; + case 7: + if (!(!done && !_this2.isStopped())) { + _context4.next = 25; + break; + } + _context4.prev = 8; + _context4.next = 11; + return _this2.push.handler(useRows); + case 11: + result = _context4.sent; + if (Array.isArray(result)) { + _context4.next = 14; + break; + } throw newRxError('RC_PUSH_NO_AR', { pushRows: rows, direction: 'push', @@ -415,85 +313,128 @@ export var RxReplicationState = /*#__PURE__*/function () { result: result } }); - } - done = true; - }); - }, function (err) { - var emitError = err.rxdb ? err : newRxError('RC_PUSH', { - pushRows: rows, - errors: Array.isArray(err) ? err : [err], - direction: 'push' - }); - _this2.subjects.error.next(emitError); - return Promise.resolve(awaitRetry(_this2.collection, ensureNotFalsy(_this2.retryTime))).then(function () {}); - }); - }); - return _temp6 && _temp6.then ? _temp6.then(_temp7) : _temp7(_temp6); - }); - } catch (e) { - return Promise.reject(e); + case 14: + done = true; + _context4.next = 23; + break; + case 17: + _context4.prev = 17; + _context4.t0 = _context4["catch"](8); + emitError = _context4.t0.rxdb ? _context4.t0 : newRxError('RC_PUSH', { + pushRows: rows, + errors: toArray(_context4.t0).map(function (er) { + return errorToPlainJson(er); + }), + direction: 'push' + }); + _this2.subjects.error.next(emitError); + _context4.next = 23; + return awaitRetry(_this2.collection, ensureNotFalsy(_this2.retryTime)); + case 23: + _context4.next = 7; + break; + case 25: + if (!_this2.isStopped()) { + _context4.next = 27; + break; + } + return _context4.abrupt("return", []); + case 27: + conflicts = ensureNotFalsy(result).map(function (doc) { + return swapdeletedFieldToDefaultDeleted(_this2.deletedField, doc); + }); + return _context4.abrupt("return", conflicts); + case 29: + case "end": + return _context4.stop(); + } + }, _callee4, null, [[8, 17]]); + })); + function masterWrite(_x4) { + return _masterWrite.apply(this, arguments); + } + return masterWrite; + }() } - } - } - }); - _this2.subs.push(_this2.internalReplicationState.events.error.subscribe(function (err) { - _this2.subjects.error.next(err); - }), _this2.internalReplicationState.events.processed.down.subscribe(function (row) { - return _this2.subjects.received.next(row.document); - }), _this2.internalReplicationState.events.processed.up.subscribe(function (writeToMasterRow) { - _this2.subjects.send.next(writeToMasterRow.newDocumentState); - }), combineLatest([_this2.internalReplicationState.events.active.down, _this2.internalReplicationState.events.active.up]).subscribe(function (_ref2) { - var down = _ref2[0], - up = _ref2[1]; - var isActive = down || up; - _this2.subjects.active.next(isActive); - })); - if (_this2.pull && _this2.pull.stream$ && _this2.live) { - _this2.subs.push(_this2.pull.stream$.subscribe({ - next: function next(ev) { - _this2.remoteEvents$.next(ev); - }, - error: function error(err) { + }); + this.subs.push(this.internalReplicationState.events.error.subscribe(function (err) { _this2.subjects.error.next(err); + }), this.internalReplicationState.events.processed.down.subscribe(function (row) { + return _this2.subjects.received.next(row.document); + }), this.internalReplicationState.events.processed.up.subscribe(function (writeToMasterRow) { + _this2.subjects.send.next(writeToMasterRow.newDocumentState); + }), combineLatest([this.internalReplicationState.events.active.down, this.internalReplicationState.events.active.up]).subscribe(function (_ref3) { + var down = _ref3[0], + up = _ref3[1]; + var isActive = down || up; + _this2.subjects.active.next(isActive); + })); + if (this.pull && this.pull.stream$ && this.live) { + this.subs.push(this.pull.stream$.subscribe({ + next: function next(ev) { + _this2.remoteEvents$.next(ev); + }, + error: function error(err) { + _this2.subjects.error.next(err); + } + })); } - })); - } - /** - * Non-live replications run once - * and then automatically get canceled. - */ - var _temp = function () { - if (!_this2.live) { - return Promise.resolve(awaitRxStorageReplicationFirstInSync(_this2.internalReplicationState)).then(function () { - return Promise.resolve(awaitRxStorageReplicationInSync(_this2.internalReplicationState)).then(function () { - return Promise.resolve(_this2.cancel()).then(function () {}); - }); - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); + /** + * Non-live replications run once + * and then automatically get canceled. + */ + if (this.live) { + _context5.next = 21; + break; + } + _context5.next = 17; + return awaitRxStorageReplicationFirstInSync(this.internalReplicationState); + case 17: + _context5.next = 19; + return awaitRxStorageReplicationInSync(this.internalReplicationState); + case 19: + _context5.next = 21; + return this.cancel(); + case 21: + this.callOnStart(); + case 22: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function start() { + return _start.apply(this, arguments); } - }; + return start; + }(); _proto.isStopped = function isStopped() { if (this.subjects.canceled.getValue()) { return true; } return false; }; - _proto.awaitInitialReplication = function awaitInitialReplication() { - try { - var _this3 = this; - return Promise.resolve(_this3.startPromise).then(function () { - return awaitRxStorageReplicationFirstInSync(ensureNotFalsy(_this3.internalReplicationState)); - }); - } catch (e) { - return Promise.reject(e); + _proto.awaitInitialReplication = /*#__PURE__*/function () { + var _awaitInitialReplication = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() { + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return this.startPromise; + case 2: + return _context6.abrupt("return", awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState))); + case 3: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function awaitInitialReplication() { + return _awaitInitialReplication.apply(this, arguments); } - } + return awaitInitialReplication; + }() /** * Returns a promise that resolves when: * - All local data is replicated with the remote @@ -505,28 +446,37 @@ export var RxReplicationState = /*#__PURE__*/function () { * For multi-tab support you should set and observe a flag in a local document. */ ; - _proto.awaitInSync = function awaitInSync() { - try { - var _this4 = this; - return Promise.resolve(_this4.startPromise).then(function () { - return Promise.resolve(awaitRxStorageReplicationFirstInSync(ensureNotFalsy(_this4.internalReplicationState))).then(function () { - /** - * Often awaitInSync() is called directly after a document write, - * like in the unit tests. - * So we first have to await the idleness to ensure that all RxChangeEvents - * are processed already. - */ - return Promise.resolve(_this4.collection.database.requestIdlePromise()).then(function () { - return Promise.resolve(awaitRxStorageReplicationInSync(ensureNotFalsy(_this4.internalReplicationState))).then(function () { - return true; - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); + _proto.awaitInSync = + /*#__PURE__*/ + function () { + var _awaitInSync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.startPromise; + case 2: + _context7.next = 4; + return awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState)); + case 4: + _context7.next = 6; + return this.collection.database.requestIdlePromise(); + case 6: + _context7.next = 8; + return awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState)); + case 8: + return _context7.abrupt("return", true); + case 9: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function awaitInSync() { + return _awaitInSync.apply(this, arguments); } - }; + return awaitInSync; + }(); _proto.reSync = function reSync() { this.remoteEvents$.next('RESYNC'); }; @@ -534,7 +484,7 @@ export var RxReplicationState = /*#__PURE__*/function () { this.remoteEvents$.next(ev); }; _proto.cancel = function cancel() { - var _this5 = this; + var _this3 = this; if (this.isStopped()) { return PROMISE_RESOLVE_FALSE; } @@ -544,7 +494,7 @@ export var RxReplicationState = /*#__PURE__*/function () { } if (this.metaInstance) { promises.push(ensureNotFalsy(this.internalReplicationState).checkpointQueue.then(function () { - return ensureNotFalsy(_this5.metaInstance).close(); + return ensureNotFalsy(_this3.metaInstance).close(); })); } this.subs.forEach(function (sub) { @@ -560,21 +510,22 @@ export var RxReplicationState = /*#__PURE__*/function () { }; return RxReplicationState; }(); -export function replicateRxCollection(_ref3) { - var replicationIdentifier = _ref3.replicationIdentifier, - collection = _ref3.collection, - _ref3$deletedField = _ref3.deletedField, - deletedField = _ref3$deletedField === void 0 ? '_deleted' : _ref3$deletedField, - pull = _ref3.pull, - push = _ref3.push, - _ref3$live = _ref3.live, - live = _ref3$live === void 0 ? true : _ref3$live, - _ref3$retryTime = _ref3.retryTime, - retryTime = _ref3$retryTime === void 0 ? 1000 * 5 : _ref3$retryTime, - _ref3$waitForLeadersh = _ref3.waitForLeadership, - waitForLeadership = _ref3$waitForLeadersh === void 0 ? true : _ref3$waitForLeadersh, - _ref3$autoStart = _ref3.autoStart, - autoStart = _ref3$autoStart === void 0 ? true : _ref3$autoStart; +export function replicateRxCollection(_ref4) { + var replicationIdentifier = _ref4.replicationIdentifier, + collection = _ref4.collection, + _ref4$deletedField = _ref4.deletedField, + deletedField = _ref4$deletedField === void 0 ? '_deleted' : _ref4$deletedField, + pull = _ref4.pull, + push = _ref4.push, + _ref4$live = _ref4.live, + live = _ref4$live === void 0 ? true : _ref4$live, + _ref4$retryTime = _ref4.retryTime, + retryTime = _ref4$retryTime === void 0 ? 1000 * 5 : _ref4$retryTime, + _ref4$waitForLeadersh = _ref4.waitForLeadership, + waitForLeadership = _ref4$waitForLeadersh === void 0 ? true : _ref4$waitForLeadersh, + _ref4$autoStart = _ref4.autoStart, + autoStart = _ref4$autoStart === void 0 ? true : _ref4$autoStart; + addRxPlugin(RxDBLeaderElectionPlugin); var replicationIdentifierHash = fastUnsecureHash([collection.database.name, collection.name, replicationIdentifier].join('|')); var replicationState = new RxReplicationState(replicationIdentifierHash, collection, deletedField, pull, push, live, retryTime, autoStart); startReplicationOnLeaderShip(waitForLeadership, replicationState); diff --git a/dist/es/plugins/replication/index.js.map b/dist/es/plugins/replication/index.js.map index e6f30156150..89c7072397c 100644 --- a/dist/es/plugins/replication/index.js.map +++ b/dist/es/plugins/replication/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","mergeMap","Subject","ensureNotFalsy","fastUnsecureHash","flatClone","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","cancelRxStorageReplication","replicateRxStorageInstance","RX_REPLICATION_META_INSTANCE_SCHEMA","newRxError","awaitRetry","DEFAULT_MODIFIER","swapDefaultDeletedTodeletedField","swapdeletedFieldToDefaultDeleted","addConnectedStorageToCollection","body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","send","error","canceled","active","initialReplicationComplete","received$","asObservable","send$","error$","canceled$","active$","callOnStart","undefined","remoteEvents$","replicationStates","get","set","onDestroy","cancel","Object","keys","forEach","key","defineProperty","startPromise","Promise","res","start","isStopped","pullModifier","modifier","pushModifier","database","metaInstanceCollectionName","name","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","schema","metaInstance","internalReplicationState","pushBatchSize","batchSize","pullBatchSize","forkInstance","storageInstance","hashFunction","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","ev","useEv","documents","map","doc","d","masterChangesSince","checkpoint","useResult","done","handler","err","emitError","errors","Array","isArray","direction","next","masterWrite","rows","row","newDocumentState","assumedMasterState","useRows","conflicts","pushRows","args","rxdb","events","subscribe","processed","down","document","up","writeToMasterRow","isActive","stream$","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","promises","checkpointQueue","close","sub","unsubscribe","complete","replicateRxCollection","replicationIdentifier","waitForLeadership","join","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types';\nimport {\n ensureNotFalsy,\n fastUnsecureHash,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE\n} from '../../util';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n replicateRxStorageInstance,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n} from '../../replication-protocol';\nimport { newRxError } from '../../rx-error';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n swapdeletedFieldToDefaultDeleted\n} from './replication-helper';\nimport { addConnectedStorageToCollection } from '../../rx-database-internal-store';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n send: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false), // true when something is running, false when not\n initialReplicationComplete: new BehaviorSubject(false) // true the initial replication-cycle is over\n };\n\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly send$: Observable> = this.subjects.send.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n private startPromise: Promise;\n constructor(\n /**\n * hash of the identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n let replicationStates = REPLICATION_STATE_BY_COLLECTION.get(collection);\n if (!replicationStates) {\n replicationStates = [];\n REPLICATION_STATE_BY_COLLECTION.set(collection, replicationStates);\n }\n replicationStates.push(this);\n\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n\n const metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash;\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: RX_REPLICATION_META_INSTANCE_SCHEMA\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n )\n ]);\n this.metaInstance = metaInstance;\n\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rx-replication-' + this.replicationIdentifierHash,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n if (this.deletedField !== '_deleted') {\n useEv.documents = useEv.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: Array.isArray(err) ? err : [err],\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n if (this.deletedField !== '_deleted') {\n useResult.documents = useResult.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n const useRows = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n\n return row;\n })\n );\n\n let result: WithDeleted[] = null as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: Array.isArray(err) ? err : [err],\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return [];\n }\n\n const conflicts = ensureNotFalsy(result).map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.send.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = [];\n\n if (this.internalReplicationState) {\n cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.send.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n const replicationIdentifierHash = fastUnsecureHash(\n [\n collection.database.name,\n collection.name,\n replicationIdentifier\n ].join('|')\n );\n const replicationState = new RxReplicationState(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,eAAe,EACfC,aAAa,EACbC,QAAQ,EAERC,OAAO,QAEJ,MAAM;AAiBb,SACIC,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,qBAAqB,EACrBC,oBAAoB,QACjB,YAAY;AACnB,SACIC,oCAAoC,EACpCC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,mCAAmC,QAChC,4BAA4B;AACnC,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SACIC,UAAU,EACVC,gBAAgB,EAChBC,gCAAgC,EAChCC,gCAAgC,QAC7B,sBAAsB;AAC7B,SAASC,+BAA+B,QAAQ,kCAAkC;AA8f3E,gBAAgBC,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AArhBO,iBAAiBG,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,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,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SAAS,CACZ;EAGDoH,4BAA4B,CAACH,iBAAiB,EAAEE,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGA,OAAO,SAASC,4BAA4B,CACxCH,iBAA0B,EAC1BE,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGJ,iBAAiB,IAAIE,gBAAgB,CAACzH,UAAU,CAAC0C,QAAQ,CAACU,aAAa;EACrG,IAAMwE,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAACzH,UAAU,CAAC0C,QAAQ,CAAC6E,iBAAiB,EAAE,GAAGnK,oBAAoB;EACzI,OAAOwK,WAAW,CAACxJ,IAAI,CAAC,YAAM;IAC1B,IAAIqJ,gBAAgB,CAACnF,SAAS,EAAE,EAAE;MAC9B;IACJ;IACA,IAAImF,gBAAgB,CAACnH,SAAS,EAAE;MAC5BmH,gBAAgB,CAACpF,KAAK,EAAE;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file +{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","mergeMap","Subject","RxDBLeaderElectionPlugin","ensureNotFalsy","errorToPlainJson","fastUnsecureHash","flatClone","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","toArray","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","cancelRxStorageReplication","replicateRxStorageInstance","RX_REPLICATION_META_INSTANCE_SCHEMA","newRxError","awaitRetry","DEFAULT_MODIFIER","swapDefaultDeletedTodeletedField","swapdeletedFieldToDefaultDeleted","addConnectedStorageToCollection","addRxPlugin","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","send","error","canceled","active","initialReplicationComplete","received$","asObservable","send$","error$","canceled$","active$","callOnStart","undefined","remoteEvents$","replicationStates","get","set","onDestroy","cancel","Object","keys","forEach","key","defineProperty","startPromise","Promise","res","start","isStopped","pullModifier","modifier","pushModifier","database","metaInstanceCollectionName","name","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","schema","metaInstance","internalReplicationState","pushBatchSize","batchSize","pullBatchSize","forkInstance","storageInstance","hashFunction","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","ev","useEv","documents","map","doc","d","masterChangesSince","checkpoint","done","result","handler","emitError","errors","er","direction","next","useResult","masterWrite","rows","row","newDocumentState","assumedMasterState","useRows","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","err","processed","down","document","up","writeToMasterRow","isActive","stream$","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","promises","checkpointQueue","then","close","sub","unsubscribe","complete","replicateRxCollection","replicationIdentifier","waitForLeadership","join","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n fastUnsecureHash,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray\n} from '../../plugins/utils';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n replicateRxStorageInstance,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n} from '../../replication-protocol';\nimport { newRxError } from '../../rx-error';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n swapdeletedFieldToDefaultDeleted\n} from './replication-helper';\nimport {\n addConnectedStorageToCollection\n} from '../../rx-database-internal-store';\nimport { addRxPlugin } from '../../plugin';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n send: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false), // true when something is running, false when not\n initialReplicationComplete: new BehaviorSubject(false) // true the initial replication-cycle is over\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly send$: Observable> = this.subjects.send.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n private startPromise: Promise;\n constructor(\n /**\n * hash of the identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n let replicationStates = REPLICATION_STATE_BY_COLLECTION.get(collection);\n if (!replicationStates) {\n replicationStates = [];\n REPLICATION_STATE_BY_COLLECTION.set(collection, replicationStates);\n }\n replicationStates.push(this);\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n const metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash;\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: RX_REPLICATION_META_INSTANCE_SCHEMA\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n )\n ]);\n this.metaInstance = metaInstance;\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rx-replication-' + this.replicationIdentifierHash,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n if (this.deletedField !== '_deleted') {\n useEv.documents = useEv.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n if (this.deletedField !== '_deleted') {\n useResult.documents = useResult.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n const useRows = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n\n let result: WithDeleted[] = null as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n const conflicts = ensureNotFalsy(result).map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.send.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = [];\n\n if (this.internalReplicationState) {\n cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.send.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n const replicationIdentifierHash = fastUnsecureHash(\n [\n collection.database.name,\n collection.name,\n replicationIdentifier\n ].join('|')\n );\n const replicationState = new RxReplicationState(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,eAAe,EACfC,aAAa,EACbC,QAAQ,EAERC,OAAO,QAEJ,MAAM;AAiBb,SAASC,wBAAwB,QAAQ,oBAAoB;AAC7D,SACIC,cAAc,EACdC,gBAAgB,EAChBC,gBAAgB,EAChBC,SAAS,EACTC,qBAAqB,EACrBC,oBAAoB,EACpBC,OAAO,QACJ,qBAAqB;AAC5B,SACIC,oCAAoC,EACpCC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,mCAAmC,QAChC,4BAA4B;AACnC,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SACIC,UAAU,EACVC,gBAAgB,EAChBC,gCAAgC,EAChCC,gCAAgC,QAC7B,sBAAsB;AAC7B,SACIC,+BAA+B,QAC5B,kCAAkC;AACzC,SAASC,WAAW,QAAQ,cAAc;AAG1C,OAAO,IAAMC,+BAAsF,GAAG,IAAIC,OAAO,EAAE;AAEnH,WAAaC,kBAAkB;EAkB3B;EACI;AACR;AACA;AACA;EACwBC,yBAAiC,EACjCC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EAC5B;IAAA;IAAA,KA9BcC,IAAI,GAAmB,EAAE;IAAA,KACzBC,QAAQ,GAAG;MACvBC,QAAQ,EAAE,IAAIlC,OAAO,EAA6B;MAAE;MACpDmC,IAAI,EAAE,IAAInC,OAAO,EAA0B;MAAE;M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CAAC0C,QAAQ,CAACgF,iBAAiB,EAAE,GAAG5I,oBAAoB;EACzI,OAAOiJ,WAAW,CAACZ,IAAI,CAAC,YAAM;IAC1B,IAAIS,gBAAgB,CAACtF,SAAS,EAAE,EAAE;MAC9B;IACJ;IACA,IAAIsF,gBAAgB,CAACtH,SAAS,EAAE;MAC5BsH,gBAAgB,CAACvF,KAAK,EAAE;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file diff --git a/dist/es/plugins/replication/replication-helper.js b/dist/es/plugins/replication/replication-helper.js index 5a39d53d688..ed92f72e944 100644 --- a/dist/es/plugins/replication/replication-helper.js +++ b/dist/es/plugins/replication/replication-helper.js @@ -1,4 +1,4 @@ -import { flatClone } from '../../util'; +import { flatClone } from '../../plugins/utils'; // does nothing export var DEFAULT_MODIFIER = function DEFAULT_MODIFIER(d) { diff --git a/dist/es/plugins/replication/replication-helper.js.map b/dist/es/plugins/replication/replication-helper.js.map index 790870c5f45..8bc330009e7 100644 --- a/dist/es/plugins/replication/replication-helper.js.map +++ b/dist/es/plugins/replication/replication-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"replication-helper.js","names":["flatClone","DEFAULT_MODIFIER","d","Promise","resolve","swapDefaultDeletedTodeletedField","deletedField","doc","isDeleted","_deleted","swapdeletedFieldToDefaultDeleted","awaitRetry","collection","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types';\nimport { flatClone } from '../../util';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n\nexport function swapdeletedFieldToDefaultDeleted(\n deletedField: string,\n doc: RxDocType\n): WithDeleted {\n if (deletedField === '_deleted') {\n return doc as any;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!(doc as any)[deletedField];\n (doc as any)._deleted = isDeleted;\n delete (doc as any)[deletedField];\n return doc as any;\n }\n}\n\n\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n"],"mappings":"AAIA,SAASA,SAAS,QAAQ,YAAY;;AAEtC;AACA,OAAO,IAAMC,gBAAgB,GAAG,SAAnBA,gBAAgB,CAAIC,CAAM;EAAA,OAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAAA;AAG9D,OAAO,SAASG,gCAAgC,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAGP,SAAS,CAACO,GAAG,CAAC;IACpB,IAAMC,SAAS,GAAG,CAAC,CAACD,GAAG,CAACE,QAAQ;IAC/BF,GAAG,CAASD,YAAY,CAAC,GAAGE,SAAS;IACtC,OAAQD,GAAG,CAASE,QAAQ;IAC5B,OAAOF,GAAG;EACd;AACJ;AAGA,OAAO,SAASG,gCAAgC,CAC5CJ,YAAoB,EACpBC,GAAc,EACQ;EACtB,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAGP,SAAS,CAACO,GAAG,CAAC;IACpB,IAAMC,SAAS,GAAG,CAAC,CAAED,GAAG,CAASD,YAAY,CAAC;IAC7CC,GAAG,CAASE,QAAQ,GAAGD,SAAS;IACjC,OAAQD,GAAG,CAASD,YAAY,CAAC;IACjC,OAAOC,GAAG;EACd;AACJ;AAGA,OAAO,SAASI,UAAU,CACtBC,UAAwB,EACxBC,SAAiB,EACnB;EACE,IACI,OAAOC,MAAM,KAAK,WAAW,IAC7B,OAAOA,MAAM,KAAK,QAAQ,IAC1B,OAAOA,MAAM,CAACC,gBAAgB,KAAK,WAAW,IAC9CC,SAAS,CAACC,MAAM,EAClB;IACE,OAAOL,UAAU,CAACM,WAAW,CAACL,SAAS,CAAC;EAC5C;EAEA,IAAIM,SAAa;EACjB,IAAMC,WAAW,GAAG,IAAIjB,OAAO,CAAO,UAAAkB,GAAG,EAAI;IACzCF,SAAQ,GAAG,oBAAM;MACbL,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,SAAQ,CAAC;MAC9CE,GAAG,EAAE;IACT,CAAC;IACDP,MAAM,CAACC,gBAAgB,CAAC,QAAQ,EAAEI,SAAQ,CAAC;EAC/C,CAAC,CAAC;EAEF,OAAOhB,OAAO,CAACoB,IAAI,CAAC,CAChBH,WAAW,EACXR,UAAU,CAACM,WAAW,CAACL,SAAS,CAAC,CACpC,CAAC,CAACW,IAAI,CAAC,YAAM;IACVV,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,SAAQ,CAAC;EAClD,CAAC,CAAC;AACN"} \ No newline at end of file +{"version":3,"file":"replication-helper.js","names":["flatClone","DEFAULT_MODIFIER","d","Promise","resolve","swapDefaultDeletedTodeletedField","deletedField","doc","isDeleted","_deleted","swapdeletedFieldToDefaultDeleted","awaitRetry","collection","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types';\nimport { flatClone } from '../../plugins/utils';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n\nexport function swapdeletedFieldToDefaultDeleted(\n deletedField: string,\n doc: RxDocType\n): WithDeleted {\n if (deletedField === '_deleted') {\n return doc as any;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!(doc as any)[deletedField];\n (doc as any)._deleted = isDeleted;\n delete (doc as any)[deletedField];\n return doc as any;\n }\n}\n\n\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n"],"mappings":"AAIA,SAASA,SAAS,QAAQ,qBAAqB;;AAE/C;AACA,OAAO,IAAMC,gBAAgB,GAAG,SAAnBA,gBAAgB,CAAIC,CAAM;EAAA,OAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAAA;AAG9D,OAAO,SAASG,gCAAgC,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAGP,SAAS,CAACO,GAAG,CAAC;IACpB,IAAMC,SAAS,GAAG,CAAC,CAACD,GAAG,CAACE,QAAQ;IAC/BF,GAAG,CAASD,YAAY,CAAC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b/dist/es/plugins/server-couchdb/index.js deleted file mode 100644 index b9eccef6d5e..00000000000 --- a/dist/es/plugins/server-couchdb/index.js +++ /dev/null @@ -1,413 +0,0 @@ -import * as os from 'os'; -import * as nodePath from 'path'; -import express from 'express'; -import corsFn from 'cors'; -import { addPouchPlugin, PouchDB } from '../../plugins/pouchdb'; -import { newRxError } from '../../rx-error'; -import { RxDBReplicationCouchDBPlugin } from '../replication-couchdb'; -import PouchAdapterHttp from 'pouchdb-adapter-http'; -import { adapterObject, addRxPlugin } from '../../index'; -import { flatClone, PROMISE_RESOLVE_VOID } from '../../util'; -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} - -/** - * when a server is created, no more collections can be spawned - */ -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -export var spawnServer = function spawnServer(_ref) { - try { - var _temp6 = function _temp6() { - return Promise.resolve(startupPromise).then(function () { - var response = { - app: app, - pouchApp: pouchApp, - server: server - }; - return response; - }); - }; - var _this = this; - var _ref$path = _ref.path, - path = _ref$path === void 0 ? '/db' : _ref$path, - _ref$port = _ref.port, - port = _ref$port === void 0 ? 3000 : _ref$port, - _ref$cors = _ref.cors, - cors = _ref$cors === void 0 ? false : _ref$cors, - _ref$startServer = _ref.startServer, - startServer = _ref$startServer === void 0 ? true : _ref$startServer, - _ref$pouchdbExpressOp = _ref.pouchdbExpressOptions, - pouchdbExpressOptions = _ref$pouchdbExpressOp === void 0 ? {} : _ref$pouchdbExpressOp; - var db = _this; - var collectionsPath = startServer ? path : '/'; - if (!SERVERS_OF_DB.has(db)) { - SERVERS_OF_DB.set(db, []); - } - var storage = db.storage; - if (!storage.adapter) { - throw new Error('The RxDB server plugin only works with pouchdb storage.'); - } - var adapterObj = adapterObject(storage.adapter); - var pouchDBOptions = Object.assign({ - prefix: getPrefix(db), - log: false - }, adapterObj); - var pseudo = PouchDB.defaults(pouchDBOptions); - var app = express(); - APP_OF_DB.set(db, app); - Object.keys(db.collections).forEach(function (colName) { - // tunnel requests so collection-names can be used as paths - tunnelCollectionPath(db, collectionsPath, app, colName); - }); - - // remember to throw error if collection is created after the server is already there - DBS_WITH_SERVER.add(db); - if (cors) { - app.use(corsFn({ - 'origin': function origin(_origin, callback) { - var originToSend = _origin || '*'; - callback(null, originToSend); - }, - 'credentials': true, - 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT' - })); - } - - /** - * Overwrite the defaults of PouchDBExpressServerOptions. - * In RxDB the defaults should not pollute anything with folders so we store the config in memory - * and the logs in the tmp folder of the os. - */ - var usePouchExpressOptions = flatClone(pouchdbExpressOptions); - if (typeof usePouchExpressOptions.inMemoryConfig === 'undefined') { - usePouchExpressOptions.inMemoryConfig = true; - } - if (typeof usePouchExpressOptions.logPath === 'undefined') { - usePouchExpressOptions.logPath = nodePath.join(os.tmpdir(), 'rxdb-server-log.txt'); - } - var pouchApp = ExpressPouchDB(pseudo, usePouchExpressOptions); - app.use(collectionsPath, pouchApp); - var server = null; - var startupPromise = PROMISE_RESOLVE_VOID; - var _temp5 = function () { - if (startServer) { - /** - * Listen for errors on server startup. - * and properly handle the error instead of returning a startupPromise - */ - startupPromise = new Promise(function (res, rej) { - var answered = false; - server = app.listen(port, function () { - if (!answered) { - answered = true; - res(); - } - }); - server.on('error', function (err) { - if (!answered) { - answered = true; - rej(err); - } - }); - }); - SERVERS_OF_DB.get(db).push(server); - - /** - * When the database has no documents, there is no db file - * and so the replication would not work. - * This is a hack which ensures that the couchdb instance exists - * and we can replicate even if there is no document in the beginning. - */ - return Promise.resolve(Promise.all(Object.values(db.collections).map(function (collection) { - try { - var url = 'http://0.0.0.0:' + port + collectionsPath + '/' + collection.name; - var _temp7 = _catch(function () { - var pingDb = new PouchDB(url); - pingDb.aaa = 'pingDB for ' + url; - return Promise.resolve(pingDb.info()).then(function () { - return Promise.resolve(pingDb.close()).then(function () {}); - }); - }, function () {}); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } - }(); - return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5)); - } catch (e) { - return Promise.reject(e); - } -}; -var ExpressPouchDB; -try { - ExpressPouchDB = require('express-pouchdb'); -} catch (error) { - console.error('Since version 8.4.0 the module \'express-pouchdb\' is not longer delivered with RxDB.\n' + 'You can install it with \'npm install express-pouchdb\''); -} - -// we have to clean up after tests so there is no stupid logging -// @link https://github.com/pouchdb/pouchdb-server/issues/226 -var PouchdbAllDbs = require('pouchdb-all-dbs'); -PouchdbAllDbs(PouchDB); -var APP_OF_DB = new WeakMap(); -var SERVERS_OF_DB = new WeakMap(); -var DBS_WITH_SERVER = new WeakSet(); -var normalizeDbName = function normalizeDbName(db) { - var split = db.name.split('/').filter(function (str) { - return str !== ''; - }); - return split.pop(); -}; -var getPrefix = function getPrefix(db) { - var split = db.name.split('/').filter(function (str) { - return str !== ''; - }); - split.pop(); // last was the name - if (split.length === 0) { - return ''; - } - var ret = split.join('/') + '/'; - if (db.name.startsWith('/')) { - ret = '/' + ret; - } - return ret; -}; - -/** - * tunnel requests so collection-names can be used as paths - */ -function tunnelCollectionPath(db, path, app, colName) { - var pathWithSlash = path.endsWith('/') ? path : path + '/'; - var collectionPath = pathWithSlash + colName; - app.use(collectionPath, function (req, res, next) { - try { - var _temp4 = function _temp4() { - next(); - }; - var _temp3 = function () { - if (req.baseUrl.endsWith(collectionPath)) { - var _temp2 = function _temp2() { - var to = normalizeDbName(db) + '-rxdb-' + db[colName].schema.version + '-' + colName; - var toFull = req.originalUrl.replace(collectionPath, pathWithSlash + to); - req.originalUrl = toFull; - }; - var _temp = _for(function () { - return !db[colName]; - }, void 0, function () { - // if the collection is migrated, - // it can happen that it does not exist at this moment - return Promise.resolve(new Promise(function (res1) { - return setTimeout(res1, 50); - })).then(function () {}); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); - } - }); -} -function ensureNoMoreCollections(args) { - if (DBS_WITH_SERVER.has(args.database)) { - var err = newRxError('S1', { - collection: args.name, - database: args.database.name - }); - throw err; - } -} - -/** - * runs when the database gets destroyed - */ -export function onDestroy(db) { - if (SERVERS_OF_DB.has(db)) { - SERVERS_OF_DB.get(db).forEach(function (server) { - return server.close(); - }); - } -} -export var RxDBServerCouchDBPlugin = { - name: 'server-couchdb', - rxdb: true, - init: function init() { - addPouchPlugin(PouchAdapterHttp); - addRxPlugin(RxDBReplicationCouchDBPlugin); - }, - prototypes: { - RxDatabase: function RxDatabase(proto) { - proto.serverCouchDB = spawnServer; - } - }, - overwritable: {}, - hooks: { - preDestroyRxDatabase: { - after: onDestroy - }, - preCreateRxCollection: { - after: ensureNoMoreCollections - } - } -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/server-couchdb/index.js.map b/dist/es/plugins/server-couchdb/index.js.map deleted file mode 100644 index 23881bfbd8d..00000000000 --- a/dist/es/plugins/server-couchdb/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["os","nodePath","express","corsFn","addPouchPlugin","PouchDB","newRxError","RxDBReplicationCouchDBPlugin","PouchAdapterHttp","adapterObject","addRxPlugin","flatClone","PROMISE_RESOLVE_VOID","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","recover","spawnServer","startupPromise","response","app","pouchApp","server","path","port","cors","startServer","pouchdbExpressOptions","db","collectionsPath","SERVERS_OF_DB","has","set","storage","adapter","Error","adapterObj","pouchDBOptions","Object","assign","prefix","getPrefix","log","pseudo","defaults","APP_OF_DB","keys","collections","forEach","colName","tunnelCollectionPath","DBS_WITH_SERVER","add","use","origin","originToSend","usePouchExpressOptions","inMemoryConfig","logPath","join","tmpdir","ExpressPouchDB","Promise","res","rej","answered","listen","on","err","get","push","all","values","map","collection","url","name","pingDb","aaa","info","close","require","error","console","PouchdbAllDbs","WeakMap","WeakSet","normalizeDbName","split","filter","str","pop","length","ret","startsWith","pathWithSlash","endsWith","collectionPath","req","next","baseUrl","to","schema","version","toFull","originalUrl","replace","res1","setTimeout","ensureNoMoreCollections","args","database","onDestroy","RxDBServerCouchDBPlugin","rxdb","init","prototypes","RxDatabase","proto","serverCouchDB","overwritable","hooks","preDestroyRxDatabase","after","preCreateRxCollection"],"sources":["../../../../src/plugins/server-couchdb/index.ts"],"sourcesContent":["import * as os from 'os';\nimport * as nodePath from 'path';\n\nimport express from 'express';\nimport type { Express } from 'express';\nimport corsFn from 'cors';\n\nimport {\n addPouchPlugin,\n PouchDB,\n RxStoragePouch\n} from '../../plugins/pouchdb';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n PouchDBExpressServerOptions,\n RxDatabase,\n RxPlugin,\n CouchDBServerResponse\n} from '../../types';\n\nimport { RxDBReplicationCouchDBPlugin } from '../replication-couchdb';\n\nimport PouchAdapterHttp from 'pouchdb-adapter-http';\nimport { adapterObject, addRxPlugin } from '../../index';\nimport {\n flatClone, PROMISE_RESOLVE_VOID\n} from '../../util';\n\nlet ExpressPouchDB: any;\ntry {\n ExpressPouchDB = require('express-pouchdb');\n} catch (error) {\n console.error(\n 'Since version 8.4.0 the module \\'express-pouchdb\\' is not longer delivered with RxDB.\\n' +\n 'You can install it with \\'npm install express-pouchdb\\''\n );\n}\n\n// we have to clean up after tests so there is no stupid logging\n// @link https://github.com/pouchdb/pouchdb-server/issues/226\nconst PouchdbAllDbs = require('pouchdb-all-dbs');\nPouchdbAllDbs(PouchDB);\n\nconst APP_OF_DB: WeakMap = new WeakMap();\nconst SERVERS_OF_DB = new WeakMap();\nconst DBS_WITH_SERVER = new WeakSet();\n\n\nconst normalizeDbName = function (db: RxDatabase) {\n const split = db.name.split('/').filter((str: string) => str !== '');\n return split.pop();\n};\n\nconst getPrefix = function (db: RxDatabase) {\n const split = db.name.split('/').filter((str: string) => str !== '');\n split.pop(); // last was the name\n if (split.length === 0) {\n return '';\n }\n let ret = split.join('/') + '/';\n if (db.name.startsWith('/')) {\n ret = '/' + ret;\n }\n return ret;\n};\n\n/**\n * tunnel requests so collection-names can be used as paths\n */\nfunction tunnelCollectionPath(\n db: RxDatabase,\n path: string,\n app: Express,\n colName: string\n) {\n const pathWithSlash = path.endsWith('/') ? path : path + '/';\n const collectionPath = pathWithSlash + colName;\n app.use(collectionPath, async function (req: any, res: any, next: any) {\n if (req.baseUrl.endsWith(collectionPath)) {\n\n while (!db[colName]) {\n // if the collection is migrated,\n // it can happen that it does not exist at this moment\n await new Promise(res1 => setTimeout(res1, 50));\n }\n const to = normalizeDbName(db) + '-rxdb-' + db[colName].schema.version + '-' + colName;\n const toFull = req.originalUrl.replace(collectionPath, pathWithSlash + to);\n req.originalUrl = toFull;\n }\n next();\n });\n}\n\nexport async function spawnServer(\n this: RxDatabase,\n {\n path = '/db',\n port = 3000,\n cors = false,\n startServer = true,\n pouchdbExpressOptions = {}\n }\n): Promise {\n const db: RxDatabase = this;\n const collectionsPath = startServer ? path : '/';\n if (!SERVERS_OF_DB.has(db)) {\n SERVERS_OF_DB.set(db, []);\n }\n\n const storage: RxStoragePouch = db.storage as any;\n if (!storage.adapter) {\n throw new Error('The RxDB server plugin only works with pouchdb storage.');\n }\n\n const adapterObj = adapterObject(storage.adapter);\n const pouchDBOptions = Object.assign(\n { prefix: getPrefix(db), log: false },\n adapterObj,\n );\n\n const pseudo = PouchDB.defaults(pouchDBOptions);\n const app = express();\n APP_OF_DB.set(db, app);\n\n Object.keys(db.collections).forEach(colName => {\n // tunnel requests so collection-names can be used as paths\n tunnelCollectionPath(db, collectionsPath, app, colName);\n });\n\n // remember to throw error if collection is created after the server is already there\n DBS_WITH_SERVER.add(db);\n\n if (cors) {\n app.use(corsFn({\n 'origin': function (origin, callback) {\n const originToSend: any = origin || '*';\n callback(null, originToSend);\n },\n 'credentials': true,\n 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT',\n }));\n }\n\n /**\n * Overwrite the defaults of PouchDBExpressServerOptions.\n * In RxDB the defaults should not pollute anything with folders so we store the config in memory\n * and the logs in the tmp folder of the os.\n */\n const usePouchExpressOptions: PouchDBExpressServerOptions = flatClone(pouchdbExpressOptions);\n if (typeof usePouchExpressOptions.inMemoryConfig === 'undefined') {\n usePouchExpressOptions.inMemoryConfig = true;\n }\n if (typeof usePouchExpressOptions.logPath === 'undefined') {\n usePouchExpressOptions.logPath = nodePath.join(\n os.tmpdir(),\n 'rxdb-server-log.txt'\n );\n }\n\n const pouchApp = ExpressPouchDB(pseudo, usePouchExpressOptions);\n app.use(collectionsPath, pouchApp);\n\n let server = null;\n let startupPromise: Promise = PROMISE_RESOLVE_VOID;\n if (startServer) {\n /**\n * Listen for errors on server startup.\n * and properly handle the error instead of returning a startupPromise\n */\n startupPromise = new Promise((res, rej) => {\n let answered = false;\n server = app.listen(port, () => {\n if (!answered) {\n answered = true;\n res();\n }\n });\n server.on('error', (err) => {\n if (!answered) {\n answered = true;\n rej(err);\n }\n });\n });\n SERVERS_OF_DB.get(db).push(server);\n\n /**\n * When the database has no documents, there is no db file\n * and so the replication would not work.\n * This is a hack which ensures that the couchdb instance exists\n * and we can replicate even if there is no document in the beginning.\n */\n await Promise.all(\n Object.values(db.collections).map(async (collection) => {\n const url = 'http://0.0.0.0:' + port + collectionsPath + '/' + collection.name;\n try {\n const pingDb = new PouchDB(url);\n pingDb.aaa = 'pingDB for ' + url;\n await pingDb.info();\n await pingDb.close();\n } catch (_err) { }\n })\n );\n }\n await startupPromise;\n\n const response: CouchDBServerResponse = {\n app,\n pouchApp,\n server\n };\n return response;\n}\n\n/**\n * when a server is created, no more collections can be spawned\n */\nfunction ensureNoMoreCollections(args: any) {\n if (DBS_WITH_SERVER.has(args.database)) {\n const err = newRxError(\n 'S1', {\n collection: args.name,\n database: args.database.name\n }\n );\n throw err;\n }\n}\n\n/**\n * runs when the database gets destroyed\n */\nexport function onDestroy(db: RxDatabase) {\n if (SERVERS_OF_DB.has(db)) {\n SERVERS_OF_DB.get(db).forEach((server: any) => server.close());\n }\n}\n\nexport const RxDBServerCouchDBPlugin: RxPlugin = {\n name: 'server-couchdb',\n rxdb: true,\n init() {\n addPouchPlugin(PouchAdapterHttp);\n addRxPlugin(RxDBReplicationCouchDBPlugin);\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.serverCouchDB = spawnServer;\n }\n },\n overwritable: {},\n hooks: {\n preDestroyRxDatabase: {\n after: onDestroy\n },\n preCreateRxCollection: {\n after: ensureNoMoreCollections\n }\n }\n};\n"],"mappings":"AAAA,OAAO,KAAKA,EAAE,MAAM,IAAI;AACxB,OAAO,KAAKC,QAAQ,MAAM,MAAM;AAEhC,OAAOC,OAAO,MAAM,SAAS;AAE7B,OAAOC,MAAM,MAAM,MAAM;AAEzB,SACIC,cAAc,EACdC,OAAO,QAEJ,uBAAuB;AAC9B,SACIC,UAAU,QACP,gBAAgB;AAQvB,SAASC,4BAA4B,QAAQ,wBAAwB;AAErE,OAAOC,gBAA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EAAE;EACxC,IAAI3D,eAAe,CAACpB,GAAG,CAAC+E,IAAI,CAACC,QAAQ,CAAC,EAAE;IACpC,IAAM3C,GAAG,GAAGtF,UAAU,CAClB,IAAI,EAAE;MACF4F,UAAU,EAAEoC,IAAI,CAAClC,IAAI;MACrBmC,QAAQ,EAAED,IAAI,CAACC,QAAQ,CAACnC;IAC5B,CAAC,CACJ;IACD,MAAMR,GAAG;EACb;AACJ;;AAEA;AACA;AACA;AACA,OAAO,SAAS4C,SAAS,CAACpF,EAAc,EAAE;EACtC,IAAIE,aAAa,CAACC,GAAG,CAACH,EAAE,CAAC,EAAE;IACvBE,aAAa,CAACuC,GAAG,CAACzC,EAAE,CAAC,CAACoB,OAAO,CAAC,UAAC1B,MAAW;MAAA,OAAKA,MAAM,CAAC0D,KAAK,EAAE;IAAA,EAAC;EAClE;AACJ;AAEA,OAAO,IAAMiC,uBAAiC,GAAG;EAC7CrC,IAAI,EAAE,gBAAgB;EACtBsC,IAAI,EAAE,IAAI;EACVC,IAAI,kBAAG;IACHvI,cAAc,CAACI,gBAAgB,CAAC;IAChCE,WAAW,CAACH,4BAA4B,CAAC;EAC7C,CAAC;EACDqI,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACC,aAAa,GAAGtG,WAAW;IACrC;EACJ,CAAC;EACDuG,YAAY,EAAE,CAAC,CAAC;EAChBC,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEX;IACX,CAAC;IACDY,qBAAqB,EAAE;MACnBD,KAAK,EAAEd;IACX;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/dexie-helper.js b/dist/es/plugins/storage-dexie/dexie-helper.js similarity index 61% rename from dist/es/plugins/dexie/dexie-helper.js rename to dist/es/plugins/storage-dexie/dexie-helper.js index 799fb6dc214..6ccf8a559ea 100644 --- a/dist/es/plugins/dexie/dexie-helper.js +++ b/dist/es/plugins/storage-dexie/dexie-helper.js @@ -1,39 +1,10 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { Dexie } from 'dexie'; -import { flatClone } from '../../util'; +import { flatClone, toArray } from '../utils'; import { newRxError } from '../../rx-error'; import { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper'; import { getMingoQuery } from '../../rx-query-mingo'; -/** - * Returns all documents in the database. - * Non-deleted plus deleted ones. - */ -export var getDocsInDb = function getDocsInDb(internals, docIds) { - return Promise.resolve(internals).then(function (state) { - return Promise.resolve(Promise.all([state.dexieTable.bulkGet(docIds), state.dexieDeletedTable.bulkGet(docIds)])).then(function (_ref3) { - var nonDeletedDocsInDb = _ref3[0], - deletedDocsInDb = _ref3[1]; - var docsInDb = deletedDocsInDb.slice(0); - nonDeletedDocsInDb.forEach(function (doc, idx) { - if (doc) { - docsInDb[idx] = doc; - } - }); - return docsInDb; - }); - }); -}; -export var closeDexieDb = function closeDexieDb(statePromise) { - return Promise.resolve(statePromise).then(function (state) { - var prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise); - var newCount = prevCount - 1; - if (newCount === 0) { - state.dexieDb.close(); - REF_COUNT_PER_DEXIE_DB["delete"](statePromise); - } else { - REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount); - } - }); -}; export var DEXIE_DOCS_TABLE_NAME = 'docs'; export var DEXIE_DELETED_DOCS_TABLE_NAME = 'deleted-docs'; export var DEXIE_CHANGES_TABLE_NAME = 'changes'; @@ -45,35 +16,70 @@ export function getDexieDbWithTables(databaseName, collectionName, settings, sch var dexieDbName = 'rxdb-dexie-' + databaseName + '--' + schema.version + '--' + collectionName; var state = DEXIE_STATE_DB_BY_NAME.get(dexieDbName); if (!state) { - state = function () { - try { - var _dexieStoresSettings; - /** - * IndexedDB was not designed for dynamically adding tables on the fly, - * so we create one dexie database per RxDB storage instance. - * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696 - */ - var useSettings = flatClone(settings); - useSettings.autoOpen = false; - var dexieDb = new Dexie(dexieDbName, useSettings); - var dexieStoresSettings = (_dexieStoresSettings = {}, _dexieStoresSettings[DEXIE_DOCS_TABLE_NAME] = getDexieStoreSchema(schema), _dexieStoresSettings[DEXIE_CHANGES_TABLE_NAME] = '++sequence, id', _dexieStoresSettings[DEXIE_DELETED_DOCS_TABLE_NAME] = primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']', _dexieStoresSettings); - dexieDb.version(1).stores(dexieStoresSettings); - return Promise.resolve(dexieDb.open()).then(function () { - return { - dexieDb: dexieDb, - dexieTable: dexieDb[DEXIE_DOCS_TABLE_NAME], - dexieDeletedTable: dexieDb[DEXIE_DELETED_DOCS_TABLE_NAME] - }; - }); - } catch (e) { - return Promise.reject(e); - } - }(); + state = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var _dexieStoresSettings; + var useSettings, dexieDb, dexieStoresSettings; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * IndexedDB was not designed for dynamically adding tables on the fly, + * so we create one dexie database per RxDB storage instance. + * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696 + */ + useSettings = flatClone(settings); + useSettings.autoOpen = false; + dexieDb = new Dexie(dexieDbName, useSettings); + dexieStoresSettings = (_dexieStoresSettings = {}, _dexieStoresSettings[DEXIE_DOCS_TABLE_NAME] = getDexieStoreSchema(schema), _dexieStoresSettings[DEXIE_CHANGES_TABLE_NAME] = '++sequence, id', _dexieStoresSettings[DEXIE_DELETED_DOCS_TABLE_NAME] = primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']', _dexieStoresSettings); + dexieDb.version(1).stores(dexieStoresSettings); + _context.next = 7; + return dexieDb.open(); + case 7: + return _context.abrupt("return", { + dexieDb: dexieDb, + dexieTable: dexieDb[DEXIE_DOCS_TABLE_NAME], + dexieDeletedTable: dexieDb[DEXIE_DELETED_DOCS_TABLE_NAME] + }); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + }))(); DEXIE_STATE_DB_BY_NAME.set(dexieDbName, state); REF_COUNT_PER_DEXIE_DB.set(state, 0); } return state; } +export function closeDexieDb(_x) { + return _closeDexieDb.apply(this, arguments); +} +function _closeDexieDb() { + _closeDexieDb = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(statePromise) { + var state, prevCount, newCount; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return statePromise; + case 2: + state = _context2.sent; + prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise); + newCount = prevCount - 1; + if (newCount === 0) { + state.dexieDb.close(); + REF_COUNT_PER_DEXIE_DB["delete"](statePromise); + } else { + REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount); + } + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _closeDexieDb.apply(this, arguments); +} function sortDirectionToMingo(direction) { if (direction === 'asc') { return 1; @@ -115,7 +121,7 @@ export function ensureNoBooleanIndex(schema) { } var checkedFields = new Set(); schema.indexes.forEach(function (index) { - var fields = Array.isArray(index) ? index : []; + var fields = toArray(index); fields.forEach(function (field) { if (checkedFields.has(field)) { return; @@ -180,9 +186,9 @@ export function fromStorageToDexie(documentData) { }); } else if (typeof documentData === 'object') { var ret = {}; - Object.entries(documentData).forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; + Object.entries(documentData).forEach(function (_ref2) { + var key = _ref2[0], + value = _ref2[1]; if (typeof value === 'object') { value = fromStorageToDexie(value); } @@ -200,9 +206,9 @@ export function fromDexieToStorage(documentData) { }); } else if (typeof documentData === 'object') { var ret = {}; - Object.entries(documentData).forEach(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; + Object.entries(documentData).forEach(function (_ref3) { + var key = _ref3[0], + value = _ref3[1]; if (typeof value === 'object' || Array.isArray(documentData)) { value = fromDexieToStorage(value); } @@ -229,7 +235,7 @@ export function getDexieStoreSchema(rxJsonSchema) { // add other indexes if (rxJsonSchema.indexes) { rxJsonSchema.indexes.forEach(function (index) { - var arIndex = Array.isArray(index) ? index : [index]; + var arIndex = toArray(index); parts.push(arIndex); }); } @@ -255,4 +261,43 @@ export function getDexieStoreSchema(rxJsonSchema) { } }).join(', '); } + +/** + * Returns all documents in the database. + * Non-deleted plus deleted ones. + */ +export function getDocsInDb(_x2, _x3) { + return _getDocsInDb.apply(this, arguments); +} +function _getDocsInDb() { + _getDocsInDb = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(internals, docIds) { + var state, _yield$Promise$all, nonDeletedDocsInDb, deletedDocsInDb, docsInDb; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return internals; + case 2: + state = _context3.sent; + _context3.next = 5; + return Promise.all([state.dexieTable.bulkGet(docIds), state.dexieDeletedTable.bulkGet(docIds)]); + case 5: + _yield$Promise$all = _context3.sent; + nonDeletedDocsInDb = _yield$Promise$all[0]; + deletedDocsInDb = _yield$Promise$all[1]; + docsInDb = deletedDocsInDb.slice(0); + nonDeletedDocsInDb.forEach(function (doc, idx) { + if (doc) { + docsInDb[idx] = doc; + } + }); + return _context3.abrupt("return", docsInDb); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _getDocsInDb.apply(this, arguments); +} //# sourceMappingURL=dexie-helper.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-dexie/dexie-helper.js.map b/dist/es/plugins/storage-dexie/dexie-helper.js.map new file mode 100644 index 00000000000..66cde98906c --- /dev/null +++ b/dist/es/plugins/storage-dexie/dexie-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-helper.js","names":["Dexie","flatClone","toArray","newRxError","getPrimaryFieldOfPrimaryKey","getSchemaByObjectPath","getMingoQuery","DEXIE_DOCS_TABLE_NAME","DEXIE_DELETED_DOCS_TABLE_NAME","DEXIE_CHANGES_TABLE_NAME","RX_STORAGE_NAME_DEXIE","DEXIE_STATE_DB_BY_NAME","Map","REF_COUNT_PER_DEXIE_DB","getDexieDbWithTables","databaseName","collectionName","settings","schema","primaryPath","primaryKey","dexieDbName","version","state","get","useSettings","autoOpen","dexieDb","dexieStoresSettings","getDexieStoreSchema","stores","open","dexieTable","dexieDeletedTable","set","closeDexieDb","statePromise","prevCount","newCount","close","sortDirectionToMingo","direction","getDexieSortComparator","_schema","query","mingoSortObject","sort","forEach","sortBlock","key","Object","keys","values","fun","a","b","sorted","find","first","next","ensureNoBooleanIndex","indexes","checkedFields","Set","index","fields","field","has","add","schemaObj","type","DEXIE_PIPE_SUBSTITUTE","dexieReplaceIfStartsWithPipe","str","split","length","map","part","join","startsWith","withoutFirst","substring","dexieReplaceIfStartsWithPipeRevert","fromStorageToDexie","documentData","Array","isArray","row","ret","entries","value","fromDexieToStorage","rxJsonSchema","parts","push","arIndex","getDocsInDb","internals","docIds","Promise","all","bulkGet","nonDeletedDocsInDb","deletedDocsInDb","docsInDb","slice","doc","idx"],"sources":["../../../../src/plugins/storage-dexie/dexie-helper.ts"],"sourcesContent":["import type {\n DeterministicSortComparator\n} from 'event-reduce-js';\nimport type {\n DexieStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { Dexie } from 'dexie';\nimport { DexieSettings } from '../../types';\nimport { flatClone, toArray } from '../utils';\nimport { newRxError } from '../../rx-error';\nimport {\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath\n} from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const DEXIE_DOCS_TABLE_NAME = 'docs';\nexport const DEXIE_DELETED_DOCS_TABLE_NAME = 'deleted-docs';\nexport const DEXIE_CHANGES_TABLE_NAME = 'changes';\n\nexport const RX_STORAGE_NAME_DEXIE = 'dexie';\n\nconst DEXIE_STATE_DB_BY_NAME: Map = new Map();\nconst REF_COUNT_PER_DEXIE_DB: Map = new Map();\nexport function getDexieDbWithTables(\n databaseName: string,\n collectionName: string,\n settings: DexieSettings,\n schema: RxJsonSchema\n): DexieStorageInternals {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const dexieDbName = 'rxdb-dexie-' + databaseName + '--' + schema.version + '--' + collectionName;\n let state = DEXIE_STATE_DB_BY_NAME.get(dexieDbName);\n if (!state) {\n state = (async () => {\n /**\n * IndexedDB was not designed for dynamically adding tables on the fly,\n * so we create one dexie database per RxDB storage instance.\n * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696\n */\n const useSettings = flatClone(settings);\n useSettings.autoOpen = false;\n const dexieDb = new Dexie(dexieDbName, useSettings);\n const dexieStoresSettings = {\n [DEXIE_DOCS_TABLE_NAME]: getDexieStoreSchema(schema),\n [DEXIE_CHANGES_TABLE_NAME]: '++sequence, id',\n /**\n * Instead of adding {deleted: false} to every query we run over the document store,\n * we move deleted documents into a separate store where they can only be queried\n * by primary key.\n * This increases performance because it is way easier for the query planner to select\n * a good index and we also do not have to add the _deleted field to every index.\n *\n * We also need the [_meta.lwt+' + primaryPath + '] index for getChangedDocumentsSince()\n */\n [DEXIE_DELETED_DOCS_TABLE_NAME]: primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']'\n };\n\n dexieDb.version(1).stores(dexieStoresSettings);\n await dexieDb.open();\n return {\n dexieDb,\n dexieTable: (dexieDb as any)[DEXIE_DOCS_TABLE_NAME],\n dexieDeletedTable: (dexieDb as any)[DEXIE_DELETED_DOCS_TABLE_NAME]\n };\n })();\n\n DEXIE_STATE_DB_BY_NAME.set(dexieDbName, state);\n REF_COUNT_PER_DEXIE_DB.set(state, 0);\n }\n\n return state;\n}\n\nexport async function closeDexieDb(statePromise: DexieStorageInternals) {\n const state = await statePromise;\n const prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise);\n const newCount = (prevCount as any) - 1;\n if (newCount === 0) {\n state.dexieDb.close();\n REF_COUNT_PER_DEXIE_DB.delete(statePromise);\n } else {\n REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount);\n }\n}\n\n\nfunction sortDirectionToMingo(direction: 'asc' | 'desc'): 1 | -1 {\n if (direction === 'asc') {\n return 1;\n } else {\n return -1;\n }\n}\n\n/**\n * This function is at dexie-helper\n * because we need it in multiple places.\n */\nexport function getDexieSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n const mingoSortObject: {\n [fieldName: string]: 1 | -1;\n } = {};\n\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n\n query.sort.forEach(sortBlock => {\n const key = Object.keys(sortBlock)[0];\n const direction = Object.values(sortBlock)[0];\n mingoSortObject[key] = sortDirectionToMingo(direction);\n });\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n const sorted = getMingoQuery({}).find([a, b], {}).sort(mingoSortObject);\n const first = sorted.next();\n if (first === a) {\n return -1;\n } else {\n return 1;\n }\n };\n\n return fun;\n}\n\n\nexport function ensureNoBooleanIndex(schema: RxJsonSchema) {\n if (!schema.indexes) {\n return;\n }\n const checkedFields = new Set();\n schema.indexes.forEach(index => {\n const fields = toArray(index);\n fields.forEach(field => {\n if (checkedFields.has(field)) {\n return;\n }\n checkedFields.add(field);\n const schemaObj = getSchemaByObjectPath(schema, field);\n if (schemaObj.type === 'boolean') {\n throw newRxError('DXE1', {\n schema,\n index,\n field\n });\n }\n });\n });\n}\n\n\n\n/**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\nexport const DEXIE_PIPE_SUBSTITUTE = '__';\nexport function dexieReplaceIfStartsWithPipe(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipe(part)).join('.');\n }\n\n if (str.startsWith('|')) {\n const withoutFirst = str.substring(1);\n return DEXIE_PIPE_SUBSTITUTE + withoutFirst;\n } else {\n return str;\n }\n}\n\nexport function dexieReplaceIfStartsWithPipeRevert(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipeRevert(part)).join('.');\n }\n\n if (str.startsWith(DEXIE_PIPE_SUBSTITUTE)) {\n const withoutFirst = str.substring(DEXIE_PIPE_SUBSTITUTE.length);\n return '|' + withoutFirst;\n } else {\n return str;\n }\n}\n\n/**\n * @recursive\n */\nexport function fromStorageToDexie(documentData: RxDocumentData): any {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromStorageToDexie(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object') {\n value = fromStorageToDexie(value);\n }\n ret[dexieReplaceIfStartsWithPipe(key)] = value;\n });\n return ret;\n }\n}\n\nexport function fromDexieToStorage(documentData: any): RxDocumentData {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromDexieToStorage(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object' || Array.isArray(documentData)) {\n value = fromDexieToStorage(value);\n }\n ret[dexieReplaceIfStartsWithPipeRevert(key)] = value;\n });\n return ret;\n }\n}\n\n\n/**\n * Creates a string that can be used to create the dexie store.\n * @link https://dexie.org/docs/API-Reference#quick-reference\n */\nexport function getDexieStoreSchema(\n rxJsonSchema: RxJsonSchema\n): string {\n let parts: string[][] = [];\n\n /**\n * First part must be the primary key\n * @link https://github.com/dexie/Dexie.js/issues/1307#issuecomment-846590912\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n parts.push([primaryKey]);\n\n // add other indexes\n if (rxJsonSchema.indexes) {\n rxJsonSchema.indexes.forEach(index => {\n const arIndex = toArray(index);\n parts.push(arIndex);\n });\n }\n\n // we also need the _meta.lwt+primaryKey index for the getChangedDocumentsSince() method.\n parts.push(['_meta.lwt', primaryKey]);\n\n /**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\n parts = parts.map(part => {\n return part.map(str => dexieReplaceIfStartsWithPipe(str));\n });\n\n return parts.map(part => {\n if (part.length === 1) {\n return part[0];\n } else {\n return '[' + part.join('+') + ']';\n }\n }).join(', ');\n}\n\n/**\n * Returns all documents in the database.\n * Non-deleted plus deleted ones.\n */\nexport async function getDocsInDb(\n internals: DexieStorageInternals,\n docIds: string[]\n): Promise[]> {\n const state = await internals;\n const [\n nonDeletedDocsInDb,\n deletedDocsInDb\n ] = await Promise.all([\n state.dexieTable.bulkGet(docIds),\n state.dexieDeletedTable.bulkGet(docIds)\n ]);\n const docsInDb = deletedDocsInDb.slice(0);\n nonDeletedDocsInDb.forEach((doc, idx) => {\n if (doc) {\n docsInDb[idx] = doc;\n }\n });\n return docsInDb;\n}\n"],"mappings":";;AASA,SAASA,KAAK,QAAQ,OAAO;AAE7B,SAASC,SAAS,EAAEC,OAAO,QAAQ,UAAU;AAC7C,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SACIC,2BAA2B,EAC3BC,qBAAqB,QAClB,wBAAwB;AAC/B,SAASC,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,IAAMC,qBAAqB,GAAG,MAAM;AAC3C,OAAO,IAAMC,6BAA6B,GAAG,cAAc;AAC3D,OAAO,IAAMC,wBAAwB,GAAG,SAAS;AAEjD,OAAO,IAAMC,qBAAqB,GAAG,OAAO;AAE5C,IAAMC,sBAA0D,GAAG,IAAIC,GAAG,EAAE;AAC5E,IAAMC,sBAA0D,GAAG,IAAID,GAAG,EAAE;AAC5E,OAAO,SAASE,oBAAoB,CAChCC,YAAoB,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hC;EAAA,wEAnBM,kBACHC,SAAgC,EAChCC,MAAgB;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEID,SAAS;QAAA;UAAvB1E,KAAK;UAAA;UAAA,OAID4E,OAAO,CAACC,GAAG,CAAC,CAClB7E,KAAK,CAACS,UAAU,CAACqE,OAAO,CAACH,MAAM,CAAC,EAChC3E,KAAK,CAACU,iBAAiB,CAACoE,OAAO,CAACH,MAAM,CAAC,CAC1C,CAAC;QAAA;UAAA;UALEI,kBAAkB;UAClBC,eAAe;UAKbC,QAAQ,GAAGD,eAAe,CAACE,KAAK,CAAC,CAAC,CAAC;UACzCH,kBAAkB,CAACvD,OAAO,CAAC,UAAC2D,GAAG,EAAEC,GAAG,EAAK;YACrC,IAAID,GAAG,EAAE;cACLF,QAAQ,CAACG,GAAG,CAAC,GAAGD,GAAG;YACvB;UACJ,CAAC,CAAC;UAAC,kCACIF,QAAQ;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAClB;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/storage-dexie/dexie-query.js b/dist/es/plugins/storage-dexie/dexie-query.js new file mode 100644 index 00000000000..56f0f18b5f9 --- /dev/null +++ b/dist/es/plugins/storage-dexie/dexie-query.js @@ -0,0 +1,224 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { dexieReplaceIfStartsWithPipe, DEXIE_DOCS_TABLE_NAME, fromDexieToStorage } from './dexie-helper'; +import { RxStorageDexieStatics } from './dexie-statics'; +export function getKeyRangeByQueryPlan(queryPlan, IDBKeyRange) { + if (!IDBKeyRange) { + if (typeof window === 'undefined') { + throw new Error('IDBKeyRange missing'); + } else { + IDBKeyRange = window.IDBKeyRange; + } + } + var ret; + /** + * If index has only one field, + * we have to pass the keys directly, not the key arrays. + */ + if (queryPlan.index.length === 1) { + ret = IDBKeyRange.bound(queryPlan.startKeys[0], queryPlan.endKeys[0], queryPlan.inclusiveStart, queryPlan.inclusiveEnd); + } else { + ret = IDBKeyRange.bound(queryPlan.startKeys, queryPlan.endKeys, queryPlan.inclusiveStart, queryPlan.inclusiveEnd); + } + return ret; +} + +/** + * Runs mango queries over the Dexie.js database. + */ +export function dexieQuery(_x, _x2) { + return _dexieQuery.apply(this, arguments); +} +function _dexieQuery() { + _dexieQuery = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(instance, preparedQuery) { + var state, query, skip, limit, skipPlusLimit, queryPlan, queryMatcher, keyRange, queryPlanFields, rows, sortComparator; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return instance.internals; + case 2: + state = _context2.sent; + query = preparedQuery.query; + skip = query.skip ? query.skip : 0; + limit = query.limit ? query.limit : Infinity; + skipPlusLimit = skip + limit; + queryPlan = preparedQuery.queryPlan; + queryMatcher = false; + if (!queryPlan.selectorSatisfiedByIndex) { + queryMatcher = RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); + } + keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); + queryPlanFields = queryPlan.index; + rows = []; + _context2.next = 15; + return state.dexieDb.transaction('r', state.dexieTable, /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(dexieTx) { + var tx, store, index, indexName, cursorReq; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * TODO here we use the native IndexedDB transaction + * to get the cursor. + * Instead we should not leave Dexie.js API and find + * a way to create the cursor with Dexie.js. + */ + tx = dexieTx.idbtrans; // const nativeIndexedDB = state.dexieDb.backendDB(); + // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly'); + store = tx.objectStore(DEXIE_DOCS_TABLE_NAME); + if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { + index = store; + } else { + if (queryPlanFields.length === 1) { + indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]); + } else { + indexName = '[' + queryPlanFields.map(function (field) { + return dexieReplaceIfStartsWithPipe(field); + }).join('+') + ']'; + } + index = store.index(indexName); + } + cursorReq = index.openCursor(keyRange); + _context.next = 6; + return new Promise(function (res) { + cursorReq.onsuccess = function (e) { + var cursor = e.target.result; + if (cursor) { + // We have a record in cursor.value + var docData = fromDexieToStorage(cursor.value); + if (!docData._deleted && (!queryMatcher || queryMatcher(docData))) { + rows.push(docData); + } + + /** + * If we do not have to manually sort + * and have enough documents, + * we can abort iterating over the cursor + * because we already have every relevant document. + */ + if (queryPlan.sortFieldsSameAsIndexFields && rows.length === skipPlusLimit) { + res(); + } else { + cursor["continue"](); + } + } else { + // Iteration complete + res(); + } + }; + }); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x5) { + return _ref.apply(this, arguments); + }; + }()); + case 15: + if (!queryPlan.sortFieldsSameAsIndexFields) { + sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); + rows = rows.sort(sortComparator); + } + + // apply skip and limit boundaries. + rows = rows.slice(skip, skipPlusLimit); + + /** + * Comment this in for debugging to check all fields in the database. + */ + // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray(); + // let documents = docsInDb + // .map(docData => stripDexieKey(docData)) + // .sort(sortComparator); + // if (preparedQuery.skip) { + // documents = documents.slice(preparedQuery.skip); + // } + // if (preparedQuery.limit && documents.length > preparedQuery.limit) { + // documents = documents.slice(0, preparedQuery.limit); + // } + return _context2.abrupt("return", { + documents: rows + }); + case 18: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _dexieQuery.apply(this, arguments); +} +export function dexieCount(_x3, _x4) { + return _dexieCount.apply(this, arguments); +} +function _dexieCount() { + _dexieCount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(instance, preparedQuery) { + var state, queryPlan, queryPlanFields, keyRange, count; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return instance.internals; + case 2: + state = _context4.sent; + queryPlan = preparedQuery.queryPlan; + queryPlanFields = queryPlan.index; + keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); + count = -1; + _context4.next = 9; + return state.dexieDb.transaction('r', state.dexieTable, /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(dexieTx) { + var tx, store, index, indexName, request; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + tx = dexieTx.idbtrans; + store = tx.objectStore(DEXIE_DOCS_TABLE_NAME); + if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { + index = store; + } else { + if (queryPlanFields.length === 1) { + indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]); + } else { + indexName = '[' + queryPlanFields.map(function (field) { + return dexieReplaceIfStartsWithPipe(field); + }).join('+') + ']'; + } + index = store.index(indexName); + } + request = index.count(keyRange); + _context3.next = 6; + return new Promise(function (res, rej) { + request.onsuccess = function () { + res(request.result); + }; + request.onerror = function (err) { + return rej(err); + }; + }); + case 6: + count = _context3.sent; + case 7: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x6) { + return _ref2.apply(this, arguments); + }; + }()); + case 9: + return _context4.abrupt("return", count); + case 10: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _dexieCount.apply(this, arguments); +} +//# sourceMappingURL=dexie-query.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-dexie/dexie-query.js.map b/dist/es/plugins/storage-dexie/dexie-query.js.map new file mode 100644 index 00000000000..07c1ba79770 --- /dev/null +++ b/dist/es/plugins/storage-dexie/dexie-query.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-query.js","names":["dexieReplaceIfStartsWithPipe","DEXIE_DOCS_TABLE_NAME","fromDexieToStorage","RxStorageDexieStatics","getKeyRangeByQueryPlan","queryPlan","IDBKeyRange","window","Error","ret","index","length","bound","startKeys","endKeys","inclusiveStart","inclusiveEnd","dexieQuery","instance","preparedQuery","internals","state","query","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","schema","keyRange","dexieDb","_options","queryPlanFields","rows","transaction","dexieTable","dexieTx","tx","idbtrans","store","objectStore","primaryPath","indexName","map","field","join","cursorReq","openCursor","Promise","res","onsuccess","e","cursor","target","result","docData","value","_deleted","push","sortFieldsSameAsIndexFields","sortComparator","getSortComparator","sort","slice","documents","dexieCount","count","request","rej","onerror","err"],"sources":["../../../../src/plugins/storage-dexie/dexie-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport type {\n DexiePreparedQuery,\n RxDocumentData,\n RxQueryPlan,\n RxStorageQueryResult\n} from '../../types';\nimport {\n dexieReplaceIfStartsWithPipe,\n DEXIE_DOCS_TABLE_NAME,\n fromDexieToStorage\n} from './dexie-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\nimport type { RxStorageInstanceDexie } from './rx-storage-instance-dexie';\n\n\nexport function getKeyRangeByQueryPlan(\n queryPlan: RxQueryPlan,\n IDBKeyRange?: any\n) {\n if (!IDBKeyRange) {\n if (typeof window === 'undefined') {\n throw new Error('IDBKeyRange missing');\n } else {\n IDBKeyRange = window.IDBKeyRange;\n }\n }\n\n let ret: any;\n /**\n * If index has only one field,\n * we have to pass the keys directly, not the key arrays.\n */\n if (queryPlan.index.length === 1) {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys[0],\n queryPlan.endKeys[0],\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n } else {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys,\n queryPlan.endKeys,\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n }\n return ret;\n}\n\n\n/**\n * Runs mango queries over the Dexie.js database.\n */\nexport async function dexieQuery(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise> {\n const state = await instance.internals;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlan = preparedQuery.queryPlan;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n\n const queryPlanFields: string[] = queryPlan.index;\n\n let rows: any[] = [];\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n /**\n * TODO here we use the native IndexedDB transaction\n * to get the cursor.\n * Instead we should not leave Dexie.js API and find\n * a way to create the cursor with Dexie.js.\n */\n const tx = (dexieTx as any).idbtrans;\n\n // const nativeIndexedDB = state.dexieDb.backendDB();\n // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly');\n\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n const cursorReq = index.openCursor(keyRange);\n await new Promise(res => {\n cursorReq.onsuccess = function (e: any) {\n const cursor = e.target.result;\n if (cursor) {\n // We have a record in cursor.value\n const docData = fromDexieToStorage(cursor.value);\n if (\n !docData._deleted &&\n (!queryMatcher || queryMatcher(docData))\n ) {\n rows.push(docData);\n }\n\n /**\n * If we do not have to manually sort\n * and have enough documents,\n * we can abort iterating over the cursor\n * because we already have every relevant document.\n */\n if (\n queryPlan.sortFieldsSameAsIndexFields &&\n rows.length === skipPlusLimit\n ) {\n res();\n } else {\n cursor.continue();\n }\n } else {\n // Iteration complete\n res();\n }\n };\n });\n\n\n }\n );\n\n\n if (!queryPlan.sortFieldsSameAsIndexFields) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n\n /**\n * Comment this in for debugging to check all fields in the database.\n */\n // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray();\n // let documents = docsInDb\n // .map(docData => stripDexieKey(docData))\n // .sort(sortComparator);\n // if (preparedQuery.skip) {\n // documents = documents.slice(preparedQuery.skip);\n // }\n // if (preparedQuery.limit && documents.length > preparedQuery.limit) {\n // documents = documents.slice(0, preparedQuery.limit);\n // }\n\n\n\n return {\n documents: rows\n };\n}\n\n\nexport async function dexieCount(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise {\n const state = await instance.internals;\n const queryPlan = preparedQuery.queryPlan;\n const queryPlanFields: string[] = queryPlan.index;\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n let count: number = -1;\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n const tx = (dexieTx as any).idbtrans;\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n\n const request = index.count(keyRange);\n count = await new Promise((res, rej) => {\n request.onsuccess = function () {\n res(request.result);\n };\n request.onerror = (err: any) => rej(err);\n });\n }\n );\n return count;\n}\n"],"mappings":";;AAOA,SACIA,4BAA4B,EAC5BC,qBAAqB,EACrBC,kBAAkB,QACf,gBAAgB;AACvB,SAASC,qBAAqB,QAAQ,iBAAiB;AAIvD,OAAO,SAASC,sBAAsB,CAClCC,SAAsB,EACtBC,WAAiB,EACnB;EACE,IAAI,CAACA,WAAW,EAAE;IACd,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;MAC/B,MAAM,IAAIC,KAAK,CAAC,qBAAqB,CAAC;IAC1C,CAAC,MAAM;MACHF,WAAW,GAAGC,MAAM,CAACD,WAAW;IACpC;EACJ;EAEA,IAAIG,GAAQ;EACZ;AACJ;AACA;AACA;EACI,IAAIJ,SAAS,CAACK,KAAK,CAACC,MAAM,KAAK,CAAC,EAAE;IAC9BF,GAAG,GAAGH,WAAW,CAACM,KAAK,CACnBP,SAAS,CAACQ,SAAS,CAAC,CAAC,CAAC,EACtBR,SAAS,CAACS,OAAO,CAAC,CAAC,CAAC,EACpBT,SAAS,CAACU,cAAc,EACxBV,SAAS,CAACW,YAAY,CACzB;EACL,CAAC,MAAM;IACHP,GAAG,GAAGH,WAAW,CAACM,KAAK,CACnBP,SAAS,CAACQ,SAAS,EACnBR,SAAS,CAACS,OAAO,EACjBT,SAAS,CAACU,cAAc,EACxBV,SAAS,CAACW,YAAY,CACzB;EACL;EACA,OAAOP,GAAG;AACd;;AAGA;AACA;AACA;AACA,gBAAsBQ,UAAU;EAAA;AAAA;AAkI/B;EAAA,uEAlIM,kBACHC,QAA2C,EAC3CC,aAA4C;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAExBD,QAAQ,CAACE,SAAS;QAAA;UAAhCC,KAAK;UACLC,KAAK,GAAGH,aAAa,CAACG,KAAK;UAE3BC,IAAI,GAAGD,KAAK,CAACC,IAAI,GAAGD,KAAK,CAACC,IAAI,GAAG,CAAC;UAClCC,KAAK,GAAGF,K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AAI,CAAC,GAAG,CAAC,GACZ,GAAG;sBACb;sBACArC,KAAK,GAAG+B,KAAK,CAAC/B,KAAK,CAACkC,SAAS,CAAC;oBAClC;oBAEMyB,OAAO,GAAG3D,KAAK,CAAC0D,KAAK,CAACrC,QAAQ,CAAC;oBAAA;oBAAA,OACvB,IAAImB,OAAO,CAAS,UAACC,GAAG,EAAEmB,GAAG,EAAK;sBAC5CD,OAAO,CAACjB,SAAS,GAAG,YAAY;wBAC5BD,GAAG,CAACkB,OAAO,CAACb,MAAM,CAAC;sBACvB,CAAC;sBACDa,OAAO,CAACE,OAAO,GAAG,UAACC,GAAQ;wBAAA,OAAKF,GAAG,CAACE,GAAG,CAAC;sBAAA;oBAC5C,CAAC,CAAC;kBAAA;oBALFJ,KAAK;kBAAA;kBAAA;oBAAA;gBAAA;cAAA;YAAA,CAMR;YAAA;cAAA;YAAA;UAAA,IACJ;QAAA;UAAA,kCACMA,KAAK;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACf;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/dexie-statics.js b/dist/es/plugins/storage-dexie/dexie-statics.js similarity index 100% rename from dist/es/plugins/dexie/dexie-statics.js rename to dist/es/plugins/storage-dexie/dexie-statics.js diff --git a/dist/es/plugins/storage-dexie/dexie-statics.js.map b/dist/es/plugins/storage-dexie/dexie-statics.js.map new file mode 100644 index 00000000000..2c64f5bfa6f --- /dev/null +++ b/dist/es/plugins/storage-dexie/dexie-statics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-statics.js","names":["getDexieSortComparator","newRxError","getQueryPlan","DEFAULT_CHECKPOINT_SCHEMA","getMingoQuery","RxStorageDexieStatics","prepareQuery","schema","mutateableQuery","sort","query","queryPlan","getSortComparator","preparedQuery","getQueryMatcher","_schema","mingoQuery","selector","fun","doc","_deleted","cursor","find","next","checkpointSchema"],"sources":["../../../../src/plugins/storage-dexie/dexie-statics.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n RxDocumentData,\n RxJsonSchema,\n RxStorageStatics,\n DexiePreparedQuery,\n FilledMangoQuery\n} from '../../types';\nimport {\n getDexieSortComparator\n} from './dexie-helper';\nimport { newRxError } from '../../rx-error';\nimport { getQueryPlan } from '../../query-planner';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const RxStorageDexieStatics: RxStorageStatics = {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): DexiePreparedQuery {\n\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n },\n\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: DexiePreparedQuery\n ): DeterministicSortComparator {\n return getDexieSortComparator(schema, preparedQuery.query);\n },\n\n getQueryMatcher(\n _schema: RxJsonSchema,\n preparedQuery: DexiePreparedQuery\n ): QueryMatcher> {\n const query = preparedQuery.query;\n const mingoQuery = getMingoQuery(query.selector);\n const fun: QueryMatcher> = (doc: RxDocumentData) => {\n if (doc._deleted) {\n return false;\n }\n const cursor = mingoQuery.find([doc]);\n const next = cursor.next();\n if (next) {\n return true;\n } else {\n return false;\n }\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n\n};\n"],"mappings":"AAWA,SACIA,sBAAsB,QACnB,gBAAgB;AACvB,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,yBAAyB,QAAQ,wBAAwB;AAClE,SAASC,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,IAAMC,qBAAuC,GAAG;EACnDC,YAAY,wBACRC,MAA+C,EAC/CC,eAA4C,EACf;IAE7B,IAAI,CAACA,eAAe,CAACC,IAAI,EAAE;MACvB,MAAMR,UAAU,CAAC,KAAK,EAAE;QACpBS,KAAK,EAAEF;MACX,CAAC,CAAC;IACN;;IAEA;AACR;AACA;AACA;IACQ,IAAMG,SAAS,GAAGT,YAAY,CAC1BK,MAAM,EACNC,eAAe,CAClB;IAED,OAAO;MACHE,KAAK,EAAEF,eAAe;MACtBG,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAEDC,iBAAiB,6BACbL,MAA+C,EAC/CM,aAA4C,EACN;IACtC,OAAOb,sBAAsB,CAACO,MAAM,EAAEM,aAAa,CAACH,KAAK,CAAC;EAC9D,CAAC;EAEDI,eAAe,2BACXC,OAAgC,EAChCF,aAA4C,EACL;IACvC,IAAMH,KAAK,GAAGG,aAAa,CAACH,KAAK;IACjC,IAAMM,UAAU,GAAGZ,aAAa,CAACM,KAAK,CAACO,QAAQ,CAAC;IAChD,IAAMC,GAA4C,GAAG,SAA/CA,GAA4C,CAAIC,GAA8B,EAAK;MACrF,IAAIA,GAAG,CAACC,QAAQ,EAAE;QACd,OAAO,KAAK;MAChB;MACA,IAAMC,MAAM,GAAGL,UAAU,CAACM,IAAI,CAAC,CAACH,GAAG,CAAC,CAAC;MACrC,IAAMI,IAAI,GAAGF,MAAM,CAACE,IAAI,EAAE;MAC1B,IAAIA,IAAI,EAAE;QACN,OAAO,IAAI;MACf,CAAC,MAAM;QACH,OAAO,KAAK;MAChB;IACJ,CAAC;IACD,OAAOL,GAAG;EACd,CAAC;EAEDM,gBAAgB,EAAErB;AAEtB,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/index.js b/dist/es/plugins/storage-dexie/index.js similarity index 100% rename from dist/es/plugins/dexie/index.js rename to dist/es/plugins/storage-dexie/index.js diff --git a/dist/es/plugins/storage-dexie/index.js.map b/dist/es/plugins/storage-dexie/index.js.map new file mode 100644 index 00000000000..7b02ba8cf18 --- /dev/null +++ b/dist/es/plugins/storage-dexie/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/storage-dexie/index.ts"],"sourcesContent":["export * from './rx-storage-dexie';\nexport * from './rx-storage-instance-dexie';\nexport * from './dexie-helper';\nexport * from './dexie-query';\nexport * from './dexie-statics';\n"],"mappings":"AAAA,cAAc,oBAAoB;AAClC,cAAc,6BAA6B;AAC3C,cAAc,gBAAgB;AAC9B,cAAc,eAAe;AAC7B,cAAc,iBAAiB"} \ No newline at end of file diff --git a/dist/es/plugins/dexie/rx-storage-dexie.js b/dist/es/plugins/storage-dexie/rx-storage-dexie.js similarity index 100% rename from dist/es/plugins/dexie/rx-storage-dexie.js rename to dist/es/plugins/storage-dexie/rx-storage-dexie.js diff --git a/dist/es/plugins/storage-dexie/rx-storage-dexie.js.map b/dist/es/plugins/storage-dexie/rx-storage-dexie.js.map new file mode 100644 index 00000000000..bc04fada859 --- /dev/null +++ b/dist/es/plugins/storage-dexie/rx-storage-dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-dexie.js","names":["ensureNoBooleanIndex","RX_STORAGE_NAME_DEXIE","createDexieStorageInstance","ensureRxStorageInstanceParamsAreCorrect","RxStorageDexieStatics","RxStorageDexie","settings","name","statics","createStorageInstance","params","schema","getRxStorageDexie","storage"],"sources":["../../../../src/plugins/storage-dexie/rx-storage-dexie.ts"],"sourcesContent":["import type {\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNoBooleanIndex,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport type {\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport {\n createDexieStorageInstance,\n RxStorageInstanceDexie\n} from './rx-storage-instance-dexie';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\n\n\n\nexport class RxStorageDexie implements RxStorage {\n public name = RX_STORAGE_NAME_DEXIE;\n public statics = RxStorageDexieStatics;\n\n constructor(\n public settings: DexieSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n ensureNoBooleanIndex(params.schema);\n return createDexieStorageInstance(this, params, this.settings);\n }\n}\n\n\nexport function getRxStorageDexie(\n settings: DexieSettings = {}\n): RxStorageDexie {\n const storage = new RxStorageDexie(settings);\n return storage;\n}\n"],"mappings":"AAIA,SACIA,oBAAoB,EACpBC,qBAAqB,QAClB,gBAAgB;AAKvB,SACIC,0BAA0B,QAEvB,6BAA6B;AACpC,SAASC,uCAAuC,QAAQ,yBAAyB;AACjF,SAASC,qBAAqB,QAAQ,iBAAiB;AAIvD,WAAaC,cAAc;EAIvB,wBACWC,QAAuB,EAChC;IAAA,KALKC,IAAI,GAAGN,qBAAqB;IAAA,KAC5BO,OAAO,GAAGJ,qBAAqB;IAAA,KAG3BE,QAAuB,GAAvBA,QAAuB;EAC9B;EAAC;EAAA,OAEEG,qBAAqB,GAA5B,+BACIC,MAAiE,EACvB;IAC1CP,uCAAuC,CAACO,MAAM,CAAC;IAC/CV,oBAAoB,CAACU,MAAM,CAACC,MAAM,CAAC;IACnC,OAAOT,0BAA0B,CAAC,IAAI,EAAEQ,MAAM,EAAE,IAAI,CAACJ,QAAQ,CAAC;EAClE,CAAC;EAAA;AAAA;AAIL,OAAO,SAASM,iBAAiB,GAEf;EAAA,IADdN,QAAuB,uEAAG,CAAC,CAAC;EAE5B,IAAMO,OAAO,GAAG,IAAIR,cAAc,CAACC,QAAQ,CAAC;EAC5C,OAAOO,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/storage-dexie/rx-storage-instance-dexie.js b/dist/es/plugins/storage-dexie/rx-storage-instance-dexie.js new file mode 100644 index 00000000000..2a13437a98d --- /dev/null +++ b/dist/es/plugins/storage-dexie/rx-storage-instance-dexie.js @@ -0,0 +1,415 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { Subject } from 'rxjs'; +import { now, PROMISE_RESOLVE_VOID, RX_META_LWT_MINIMUM, sortDocumentsByLastWriteTime, lastOfArray, ensureNotFalsy } from '../utils'; +import { closeDexieDb, fromDexieToStorage, fromStorageToDexie, getDexieDbWithTables, getDocsInDb, RX_STORAGE_NAME_DEXIE } from './dexie-helper'; +import { dexieCount, dexieQuery } from './dexie-query'; +import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; +import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; +import { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance'; +import { newRxError } from '../../rx-error'; +var instanceId = now(); +export var RxStorageInstanceDexie = /*#__PURE__*/function () { + function RxStorageInstanceDexie(storage, databaseName, collectionName, schema, internals, options, settings) { + this.changes$ = new Subject(); + this.instanceId = instanceId++; + this.closed = false; + this.storage = storage; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + this.settings = settings; + this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); + } + var _proto = RxStorageInstanceDexie.prototype; + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(documentWrites, context) { + var _this = this; + var state, ret, documentKeys, categorized, lastState, endTime; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + ensureNotClosed(this); + _context2.next = 3; + return this.internals; + case 3: + state = _context2.sent; + ret = { + success: {}, + error: {} + }; + documentKeys = documentWrites.map(function (writeRow) { + return writeRow.document[_this.primaryPath]; + }); + categorized = null; + _context2.next = 9; + return state.dexieDb.transaction('rw', state.dexieTable, state.dexieDeletedTable, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var docsInDbMap, docsInDbWithInternals, bulkPutDocs, bulkRemoveDocs, bulkPutDeletedDocs, bulkRemoveDeletedDocs; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + docsInDbMap = new Map(); + _context.next = 3; + return getDocsInDb(_this.internals, documentKeys); + case 3: + docsInDbWithInternals = _context.sent; + docsInDbWithInternals.forEach(function (docWithDexieInternals) { + var doc = docWithDexieInternals ? fromDexieToStorage(docWithDexieInternals) : docWithDexieInternals; + if (doc) { + docsInDbMap.set(doc[_this.primaryPath], doc); + } + return doc; + }); + categorized = categorizeBulkWriteRows(_this, _this.primaryPath, docsInDbMap, documentWrites, context); + ret.error = categorized.errors; + + /** + * Batch up the database operations + * so we can later run them in bulk. + */ + bulkPutDocs = []; + bulkRemoveDocs = []; + bulkPutDeletedDocs = []; + bulkRemoveDeletedDocs = []; + categorized.bulkInsertDocs.forEach(function (row) { + var docId = row.document[_this.primaryPath]; + ret.success[docId] = row.document; + bulkPutDocs.push(row.document); + }); + categorized.bulkUpdateDocs.forEach(function (row) { + var docId = row.document[_this.primaryPath]; + ret.success[docId] = row.document; + if (row.document._deleted && row.previous && !row.previous._deleted) { + // newly deleted + bulkRemoveDocs.push(docId); + bulkPutDeletedDocs.push(row.document); + } else if (row.document._deleted && row.previous && row.previous._deleted) { + // deleted was modified but is still deleted + bulkPutDeletedDocs.push(row.document); + } else if (!row.document._deleted) { + // non-deleted was changed + bulkPutDocs.push(row.document); + } else { + throw newRxError('SNH', { + args: { + row: row + } + }); + } + }); + _context.next = 15; + return Promise.all([bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(function (d) { + return fromStorageToDexie(d); + })) : PROMISE_RESOLVE_VOID, bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : PROMISE_RESOLVE_VOID, bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(function (d) { + return fromStorageToDexie(d); + })) : PROMISE_RESOLVE_VOID, bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : PROMISE_RESOLVE_VOID]); + case 15: + case "end": + return _context.stop(); + } + }, _callee); + }))); + case 9: + if (ensureNotFalsy(categorized).eventBulk.events.length > 0) { + lastState = getNewestOfDocumentStates(this.primaryPath, Object.values(ret.success)); + ensureNotFalsy(categorized).eventBulk.checkpoint = { + id: lastState[this.primaryPath], + lwt: lastState._meta.lwt + }; + endTime = now(); + ensureNotFalsy(categorized).eventBulk.events.forEach(function (event) { + return event.endTime = endTime; + }); + this.changes$.next(ensureNotFalsy(categorized).eventBulk); + } + return _context2.abrupt("return", ret); + case 11: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function bulkWrite(_x, _x2) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(); + _proto.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ids, deleted) { + var _this2 = this; + var state, ret; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + ensureNotClosed(this); + _context4.next = 3; + return this.internals; + case 3: + state = _context4.sent; + ret = {}; + _context4.next = 7; + return state.dexieDb.transaction('r', state.dexieTable, state.dexieDeletedTable, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var docsInDb; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!deleted) { + _context3.next = 6; + break; + } + _context3.next = 3; + return getDocsInDb(_this2.internals, ids); + case 3: + docsInDb = _context3.sent; + _context3.next = 9; + break; + case 6: + _context3.next = 8; + return state.dexieTable.bulkGet(ids); + case 8: + docsInDb = _context3.sent; + case 9: + ids.forEach(function (id, idx) { + var documentInDb = docsInDb[idx]; + if (documentInDb && (!documentInDb._deleted || deleted)) { + ret[id] = fromDexieToStorage(documentInDb); + } + }); + case 10: + case "end": + return _context3.stop(); + } + }, _callee3); + }))); + case 7: + return _context4.abrupt("return", ret); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function findDocumentsById(_x3, _x4) { + return _findDocumentsById.apply(this, arguments); + } + return findDocumentsById; + }(); + _proto.query = function query(preparedQuery) { + ensureNotClosed(this); + return dexieQuery(this, preparedQuery); + }; + _proto.count = /*#__PURE__*/function () { + var _count = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(preparedQuery) { + var result; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return dexieCount(this, preparedQuery); + case 2: + result = _context5.sent; + return _context5.abrupt("return", { + count: result, + mode: 'fast' + }); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function count(_x5) { + return _count.apply(this, arguments); + } + return count; + }(); + _proto.getChangedDocumentsSince = /*#__PURE__*/function () { + var _getChangedDocumentsSince = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(limit, checkpoint) { + var _this3 = this; + var sinceLwt, sinceId, state, _yield$Promise$all, changedDocsNormal, changedDocsDeleted, changedDocs, lastDoc; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + ensureNotClosed(this); + sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM; + sinceId = checkpoint ? checkpoint.id : ''; + _context7.next = 5; + return this.internals; + case 5: + state = _context7.sent; + _context7.next = 8; + return Promise.all([state.dexieTable, state.dexieDeletedTable].map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(table) { + var query, changedDocuments; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + query = table.where('[_meta.lwt+' + _this3.primaryPath + ']').above([sinceLwt, sinceId]).limit(limit); + _context6.next = 3; + return query.toArray(); + case 3: + changedDocuments = _context6.sent; + return _context6.abrupt("return", changedDocuments.map(function (d) { + return fromDexieToStorage(d); + })); + case 5: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return function (_x8) { + return _ref3.apply(this, arguments); + }; + }())); + case 8: + _yield$Promise$all = _context7.sent; + changedDocsNormal = _yield$Promise$all[0]; + changedDocsDeleted = _yield$Promise$all[1]; + changedDocs = changedDocsNormal.concat(changedDocsDeleted); + changedDocs = sortDocumentsByLastWriteTime(this.primaryPath, changedDocs); + changedDocs = changedDocs.slice(0, limit); + lastDoc = lastOfArray(changedDocs); + return _context7.abrupt("return", { + documents: changedDocs, + checkpoint: lastDoc ? { + id: lastDoc[this.primaryPath], + lwt: lastDoc._meta.lwt + } : checkpoint ? checkpoint : { + id: '', + lwt: 0 + } + }); + case 16: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function getChangedDocumentsSince(_x6, _x7) { + return _getChangedDocumentsSince.apply(this, arguments); + } + return getChangedDocumentsSince; + }(); + _proto.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { + var state; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + ensureNotClosed(this); + _context8.next = 3; + return this.internals; + case 3: + state = _context8.sent; + _context8.next = 6; + return Promise.all([state.dexieDeletedTable.clear(), state.dexieTable.clear()]); + case 6: + return _context8.abrupt("return", this.close()); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function remove() { + return _remove.apply(this, arguments); + } + return remove; + }(); + _proto.changeStream = function changeStream() { + ensureNotClosed(this); + return this.changes$.asObservable(); + }; + _proto.cleanup = /*#__PURE__*/function () { + var _cleanup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(minimumDeletedTime) { + var _this4 = this; + var state; + return _regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + ensureNotClosed(this); + _context10.next = 3; + return this.internals; + case 3: + state = _context10.sent; + _context10.next = 6; + return state.dexieDb.transaction('rw', state.dexieDeletedTable, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() { + var maxDeletionTime, toRemove, removeIds; + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + maxDeletionTime = now() - minimumDeletedTime; + _context9.next = 3; + return state.dexieDeletedTable.where('_meta.lwt').below(maxDeletionTime).toArray(); + case 3: + toRemove = _context9.sent; + removeIds = toRemove.map(function (doc) { + return doc[_this4.primaryPath]; + }); + _context9.next = 7; + return state.dexieDeletedTable.bulkDelete(removeIds); + case 7: + case "end": + return _context9.stop(); + } + }, _callee9); + }))); + case 6: + return _context10.abrupt("return", true); + case 7: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function cleanup(_x9) { + return _cleanup.apply(this, arguments); + } + return cleanup; + }(); + _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { + ensureNotClosed(this); + throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.'); + }; + _proto.close = function close() { + ensureNotClosed(this); + this.closed = true; + this.changes$.complete(); + closeDexieDb(this.internals); + return PROMISE_RESOLVE_VOID; + }; + _proto.conflictResultionTasks = function conflictResultionTasks() { + return new Subject(); + }; + _proto.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(_taskSolution) { + return _regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + function resolveConflictResultionTask(_x10) { + return _resolveConflictResultionTask.apply(this, arguments); + } + return resolveConflictResultionTask; + }(); + return RxStorageInstanceDexie; +}(); +export function createDexieStorageInstance(storage, params, settings) { + var internals = getDexieDbWithTables(params.databaseName, params.collectionName, settings, params.schema); + var instance = new RxStorageInstanceDexie(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); + addRxStorageMultiInstanceSupport(RX_STORAGE_NAME_DEXIE, params, instance); + return Promise.resolve(instance); +} +function ensureNotClosed(instance) { + if (instance.closed) { + throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName); + } +} +//# sourceMappingURL=rx-storage-instance-dexie.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-dexie/rx-storage-instance-dexie.js.map b/dist/es/plugins/storage-dexie/rx-storage-instance-dexie.js.map new file mode 100644 index 00000000000..71873542c76 --- /dev/null +++ b/dist/es/plugins/storage-dexie/rx-storage-instance-dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-dexie.js","names":["Subject","now","PROMISE_RESOLVE_VOID","RX_META_LWT_MINIMUM","sortDocumentsByLastWriteTime","lastOfArray","ensureNotFalsy","closeDexieDb","fromDexieToStorage","fromStorageToDexie","getDexieDbWithTables","getDocsInDb","RX_STORAGE_NAME_DEXIE","dexieCount","dexieQuery","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","addRxStorageMultiInstanceSupport","newRxError","instanceId","RxStorageInstanceDexie","storage","databaseName","collectionName","schema","internals","options","settings","changes$","closed","primaryPath","primaryKey","bulkWrite","documentWrites","context","ensureNotClosed","state","ret","success","error","documentKeys","map","writeRow","document","categorized","dexieDb","transaction","dexieTable","dexieDeletedTable","docsInDbMap","Map","docsInDbWithInternals","forEach","docWithDexieInternals","doc","set","errors","bulkPutDocs","bulkRemoveDocs","bulkPutDeletedDocs","bulkRemoveDeletedDocs","bulkInsertDocs","row","docId","push","bulkUpdateDocs","_deleted","previous","args","Promise","all","length","bulkPut","d","bulkDelete","eventBulk","events","lastState","Object","values","checkpoint","id","lwt","_meta","endTime","event","next","findDocumentsById","ids","deleted","docsInDb","bulkGet","idx","documentInDb","query","preparedQuery","count","result","mode","getChangedDocumentsSince","limit","sinceLwt","sinceId","table","where","above","toArray","changedDocuments","changedDocsNormal","changedDocsDeleted","changedDocs","concat","slice","lastDoc","documents","remove","clear","close","changeStream","asObservable","cleanup","minimumDeletedTime","maxDeletionTime","below","toRemove","removeIds","getAttachmentData","_documentId","_attachmentId","Error","complete","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","createDexieStorageInstance","params","instance","resolve"],"sources":["../../../../src/plugins/storage-dexie/rx-storage-instance-dexie.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n now,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM,\n sortDocumentsByLastWriteTime,\n lastOfArray,\n ensureNotFalsy\n} from '../utils';\nimport type {\n RxStorageInstance,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n RxStorageInstanceCreationParams,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n RxStorageCountResult\n} from '../../types';\nimport {\n DexiePreparedQuery,\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport { RxStorageDexie } from './rx-storage-dexie';\nimport {\n closeDexieDb,\n fromDexieToStorage,\n fromStorageToDexie,\n getDexieDbWithTables,\n getDocsInDb,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport { dexieCount, dexieQuery } from './dexie-query';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance';\nimport { newRxError } from '../../rx-error';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceDexie implements RxStorageInstance<\nRxDocType,\nDexieStorageInternals,\nDexieSettings,\nRxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageDexie,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: DexieStorageInternals,\n public readonly options: Readonly,\n public readonly settings: DexieSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const documentKeys: string[] = documentWrites.map(writeRow => writeRow.document[this.primaryPath] as any);\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n const docsInDbMap = new Map>();\n const docsInDbWithInternals = await getDocsInDb(this.internals, documentKeys);\n docsInDbWithInternals.forEach(docWithDexieInternals => {\n const doc = docWithDexieInternals ? fromDexieToStorage(docWithDexieInternals) : docWithDexieInternals;\n if (doc) {\n docsInDbMap.set(doc[this.primaryPath], doc);\n }\n return doc;\n });\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDbMap,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Batch up the database operations\n * so we can later run them in bulk.\n */\n const bulkPutDocs: any[] = [];\n const bulkRemoveDocs: string[] = [];\n const bulkPutDeletedDocs: any[] = [];\n const bulkRemoveDeletedDocs: string[] = [];\n\n categorized.bulkInsertDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n bulkPutDocs.push(row.document);\n });\n categorized.bulkUpdateDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n if (\n row.document._deleted &&\n (row.previous && !row.previous._deleted)\n ) {\n // newly deleted\n bulkRemoveDocs.push(docId);\n bulkPutDeletedDocs.push(row.document);\n } else if (\n row.document._deleted &&\n row.previous && row.previous._deleted\n ) {\n // deleted was modified but is still deleted\n bulkPutDeletedDocs.push(row.document);\n } else if (!row.document._deleted) {\n // non-deleted was changed\n bulkPutDocs.push(row.document);\n } else {\n throw newRxError('SNH', { args: { row } });\n }\n });\n\n await Promise.all([\n bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : PROMISE_RESOLVE_VOID,\n bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : PROMISE_RESOLVE_VOID\n ]);\n });\n\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n const endTime = now();\n ensureNotFalsy(categorized).eventBulk.events.forEach(event => (event as any).endTime = endTime);\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n\n return ret;\n }\n\n async findDocumentsById(\n ids: string[],\n deleted: boolean\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxDocumentDataById = {};\n\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n let docsInDb: RxDocumentData[];\n if (deleted) {\n docsInDb = await getDocsInDb(this.internals, ids);\n } else {\n docsInDb = await state.dexieTable.bulkGet(ids);\n }\n ids.forEach((id, idx) => {\n const documentInDb = docsInDb[idx];\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = fromDexieToStorage(documentInDb);\n }\n });\n });\n return ret;\n }\n\n query(preparedQuery: DexiePreparedQuery): Promise> {\n ensureNotClosed(this);\n return dexieQuery(\n this,\n preparedQuery\n );\n }\n async count(\n preparedQuery: DexiePreparedQuery\n ): Promise {\n const result = await dexieCount(this, preparedQuery);\n return {\n count: result,\n mode: 'fast'\n };\n }\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n ensureNotClosed(this);\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n const state = await this.internals;\n\n\n const [changedDocsNormal, changedDocsDeleted] = await Promise.all(\n [\n state.dexieTable,\n state.dexieDeletedTable\n ].map(async (table) => {\n const query = table\n .where('[_meta.lwt+' + this.primaryPath + ']')\n .above([sinceLwt, sinceId])\n .limit(limit);\n const changedDocuments: RxDocumentData[] = await query.toArray();\n return changedDocuments.map(d => fromDexieToStorage(d));\n })\n );\n let changedDocs = changedDocsNormal.concat(changedDocsDeleted);\n\n changedDocs = sortDocumentsByLastWriteTime(this.primaryPath as any, changedDocs);\n changedDocs = changedDocs.slice(0, limit);\n\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n async remove(): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await Promise.all([\n state.dexieDeletedTable.clear(),\n state.dexieTable.clear()\n ]);\n return this.close();\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotClosed(this);\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieDeletedTable,\n async () => {\n const maxDeletionTime = now() - minimumDeletedTime;\n const toRemove = await state.dexieDeletedTable\n .where('_meta.lwt')\n .below(maxDeletionTime)\n .toArray();\n const removeIds: string[] = toRemove.map(doc => doc[this.primaryPath]);\n await state.dexieDeletedTable.bulkDelete(removeIds);\n }\n );\n\n /**\n * TODO instead of deleting all deleted docs at once,\n * only clean up some of them and return false if there are more documents to clean up.\n * This ensures that when many documents have to be purged,\n * we do not block the more important tasks too long.\n */\n return true;\n }\n\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n ensureNotClosed(this);\n throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.');\n }\n\n close(): Promise {\n ensureNotClosed(this);\n this.closed = true;\n this.changes$.complete();\n closeDexieDb(this.internals);\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\n\nexport function createDexieStorageInstance(\n storage: RxStorageDexie,\n params: RxStorageInstanceCreationParams,\n settings: DexieSettings\n): Promise> {\n const internals = getDexieDbWithTables(\n params.databaseName,\n params.collectionName,\n settings,\n params.schema\n );\n\n const instance = new RxStorageInstanceDexie(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_DEXIE,\n params,\n instance\n );\n\n return Promise.resolve(instance);\n}\n\n\n\nfunction ensureNotClosed(\n instance: RxStorageInstanceDexie\n) {\n if (instance.closed) {\n throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName);\n }\n}\n"],"mappings":";;AAAA,SACIA,OAAO,QAEJ,MAAM;AACb,SACIC,GAAG,EACHC,oBAAoB,EACpBC,mBAAmB,EACnBC,4BAA4B,EAC5BC,WA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IAAI,CAAC;IACrB,IAAI,CAACN,MAAM,GAAG,IAAI;IAClB,IAAI,CAACD,QAAQ,CAACsG,QAAQ,EAAE;IACxB5H,YAAY,CAAC,IAAI,CAACmB,SAAS,CAAC;IAC5B,OAAOxB,oBAAoB;EAC/B,CAAC;EAAA,OAEDkI,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAIpI,OAAO,EAAE;EACxB,CAAC;EAAA,OACKqI,4BAA4B;IAAA,6FAAlC,mBAAmCC,aAAyD;MAAA;QAAA;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CAAoB;IAAA;MAAA;IAAA;IAAA;EAAA;EAAA;AAAA;AAKpH,OAAO,SAASC,0BAA0B,CACtCjH,OAAuB,EACvBkH,MAAiE,EACjE5G,QAAuB,EACmB;EAC1C,IAAMF,SAAS,GAAGhB,oBAAoB,CAClC8H,MAAM,CAACjH,YAAY,EACnBiH,MAAM,CAAChH,cAAc,EACrBI,QAAQ,EACR4G,MAAM,CAAC/G,MAAM,CAChB;EAED,IAAMgH,QAAQ,GAAG,IAAIpH,sBAAsB,CACvCC,OAAO,EACPkH,MAAM,CAACjH,YAAY,EACnBiH,MAAM,CAAChH,cAAc,EACrBgH,MAAM,CAAC/G,MAAM,EACbC,SAAS,EACT8G,MAAM,CAAC7G,OAAO,EACdC,QAAQ,CACX;EAEDV,gCAAgC,CAC5BN,qBAAqB,EACrB4H,MAAM,EACNC,QAAQ,CACX;EAED,OAAOnE,OAAO,CAACoE,OAAO,CAACD,QAAQ,CAAC;AACpC;AAIA,SAASrG,eAAe,CACpBqG,QAAqC,EACvC;EACE,IAAIA,QAAQ,CAAC3G,MAAM,EAAE;IACjB,MAAM,IAAIoG,KAAK,CAAC,mCAAmC,GAAGO,QAAQ,CAAClH,YAAY,GAAG,GAAG,GAAGkH,QAAQ,CAACjH,cAAc,CAAC;EAChH;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/foundationdb-helpers.js b/dist/es/plugins/storage-foundationdb/foundationdb-helpers.js similarity index 100% rename from dist/es/plugins/foundationdb/foundationdb-helpers.js rename to dist/es/plugins/storage-foundationdb/foundationdb-helpers.js diff --git a/dist/es/plugins/storage-foundationdb/foundationdb-helpers.js.map b/dist/es/plugins/storage-foundationdb/foundationdb-helpers.js.map new file mode 100644 index 00000000000..799180c6502 --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/foundationdb-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"foundationdb-helpers.js","names":["getFoundationDBIndexName","index","join","CLEANUP_INDEX"],"sources":["../../../../src/plugins/storage-foundationdb/foundationdb-helpers.ts"],"sourcesContent":["export function getFoundationDBIndexName(index: string[]): string {\n return index.join('|');\n}\nexport const CLEANUP_INDEX: string[] = ['_deleted', '_meta.lwt'];\n"],"mappings":"AAAA,OAAO,SAASA,wBAAwB,CAACC,KAAe,EAAU;EAC9D,OAAOA,KAAK,CAACC,IAAI,CAAC,GAAG,CAAC;AAC1B;AACA,OAAO,IAAMC,aAAuB,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/storage-foundationdb/foundationdb-query.js b/dist/es/plugins/storage-foundationdb/foundationdb-query.js new file mode 100644 index 00000000000..018c1ec5b63 --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/foundationdb-query.js @@ -0,0 +1,127 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { getStartIndexStringFromLowerBound, getStartIndexStringFromUpperBound } from '../../custom-index'; +import { ensureNotFalsy } from '../../plugins/utils'; +import { RxStorageDexieStatics } from '../storage-dexie'; +import { getFoundationDBIndexName } from './foundationdb-helpers'; +export function queryFoundationDB(_x, _x2) { + return _queryFoundationDB.apply(this, arguments); +} +function _queryFoundationDB() { + _queryFoundationDB = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(instance, preparedQuery) { + var queryPlan, query, skip, limit, skipPlusLimit, queryPlanFields, mustManuallyResort, queryMatcher, dbs, indexForName, indexName, indexDB, lowerBound, lowerBoundString, upperBound, upperBoundString, result, sortComparator; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + queryPlan = preparedQuery.queryPlan; + query = preparedQuery.query; + skip = query.skip ? query.skip : 0; + limit = query.limit ? query.limit : Infinity; + skipPlusLimit = skip + limit; + queryPlanFields = queryPlan.index; + mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields; + queryMatcher = false; + if (!queryPlan.selectorSatisfiedByIndex) { + queryMatcher = RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); + } + _context2.next = 11; + return instance.internals.dbsPromise; + case 11: + dbs = _context2.sent; + indexForName = queryPlanFields.slice(0); + indexForName.unshift('_deleted'); + indexName = getFoundationDBIndexName(indexForName); + indexDB = ensureNotFalsy(dbs.indexes[indexName]).db; + lowerBound = queryPlan.startKeys; + lowerBound = [false].concat(lowerBound); + lowerBoundString = getStartIndexStringFromLowerBound(instance.schema, indexForName, lowerBound, queryPlan.inclusiveStart); + upperBound = queryPlan.endKeys; + upperBound = [false].concat(upperBound); + upperBoundString = getStartIndexStringFromUpperBound(instance.schema, indexForName, upperBound, queryPlan.inclusiveEnd); + _context2.next = 24; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(tx) { + var innerResult, indexTx, mainTx, range, done, next, docIds, docsData; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + innerResult = []; + indexTx = tx.at(indexDB.subspace); + mainTx = tx.at(dbs.main.subspace); + range = indexTx.getRangeBatch(lowerBoundString, upperBoundString, { + // TODO these options seem to be broken in the foundationdb node bindings + // limit: instance.settings.batchSize, + // streamingMode: StreamingMode.Exact + }); + done = false; + case 5: + if (done) { + _context.next = 19; + break; + } + _context.next = 8; + return range.next(); + case 8: + next = _context.sent; + if (!next.done) { + _context.next = 12; + break; + } + done = true; + return _context.abrupt("break", 19); + case 12: + docIds = next.value.map(function (row) { + return row[1]; + }); + _context.next = 15; + return Promise.all(docIds.map(function (docId) { + return mainTx.get(docId); + })); + case 15: + docsData = _context.sent; + docsData.forEach(function (docData) { + if (!done) { + if (!queryMatcher || queryMatcher(docData)) { + innerResult.push(docData); + } + } + if (!mustManuallyResort && innerResult.length === skipPlusLimit) { + done = true; + range["return"](); + } + }); + _context.next = 5; + break; + case 19: + return _context.abrupt("return", innerResult); + case 20: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + case 24: + result = _context2.sent; + if (mustManuallyResort) { + sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); + result = result.sort(sortComparator); + } + + // apply skip and limit boundaries. + result = result.slice(skip, skipPlusLimit); + return _context2.abrupt("return", { + documents: result + }); + case 28: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _queryFoundationDB.apply(this, arguments); +} +//# sourceMappingURL=foundationdb-query.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-foundationdb/foundationdb-query.js.map b/dist/es/plugins/storage-foundationdb/foundationdb-query.js.map new file mode 100644 index 00000000000..745e996218e --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/foundationdb-query.js.map @@ -0,0 +1 @@ +{"version":3,"file":"foundationdb-query.js","names":["getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","ensureNotFalsy","RxStorageDexieStatics","getFoundationDBIndexName","queryFoundationDB","instance","preparedQuery","queryPlan","query","skip","limit","Infinity","skipPlusLimit","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","schema","internals","dbsPromise","dbs","indexForName","slice","unshift","indexName","indexDB","indexes","db","lowerBound","startKeys","concat","lowerBoundString","inclusiveStart","upperBound","endKeys","upperBoundString","inclusiveEnd","root","doTransaction","tx","innerResult","indexTx","at","subspace","mainTx","main","range","getRangeBatch","done","next","docIds","value","map","row","Promise","all","docId","get","docsData","forEach","docData","push","length","result","sortComparator","getSortComparator","sort","documents"],"sources":["../../../../src/plugins/storage-foundationdb/foundationdb-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport type {\n RxDocumentData,\n RxStorageQueryResult\n} from '../../types';\nimport { ensureNotFalsy } from '../../plugins/utils';\nimport { RxStorageDexieStatics } from '../storage-dexie';\nimport { getFoundationDBIndexName } from './foundationdb-helpers';\nimport type {\n FoundationDBPreparedQuery\n} from './foundationdb-types';\nimport { RxStorageInstanceFoundationDB } from './rx-storage-instance-foundationdb';\n\nexport async function queryFoundationDB(\n instance: RxStorageInstanceFoundationDB,\n preparedQuery: FoundationDBPreparedQuery\n): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const dbs = await instance.internals.dbsPromise;\n\n\n const indexForName = queryPlanFields.slice(0);\n indexForName.unshift('_deleted');\n const indexName = getFoundationDBIndexName(indexForName);\n const indexDB = ensureNotFalsy(dbs.indexes[indexName]).db;\n\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n instance.schema,\n indexForName,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n instance.schema,\n indexForName,\n upperBound,\n queryPlan.inclusiveEnd\n );\n let result = await dbs.root.doTransaction(async (tx: any) => {\n const innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexDB.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n\n const range = indexTx.getRangeBatch(\n lowerBoundString,\n upperBoundString,\n {\n // TODO these options seem to be broken in the foundationdb node bindings\n // limit: instance.settings.batchSize,\n // streamingMode: StreamingMode.Exact\n }\n );\n let done = false;\n while (!done) {\n const next = await range.next();\n if (next.done) {\n done = true;\n break;\n }\n const docIds = next.value.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n docsData.forEach((docData) => {\n if (!done) {\n if (!queryMatcher || queryMatcher(docData)) {\n innerResult.push(docData);\n }\n }\n if (\n !mustManuallyResort &&\n innerResult.length === skipPlusLimit\n ) {\n done = true;\n range.return();\n }\n });\n }\n return innerResult;\n });\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n result = result.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n result = result.slice(skip, skipPlusLimit);\n\n return {\n documents: result\n };\n}\n"],"mappings":";;AACA,SACIA,iCAAiC,EACjCC,iCAAiC,QAC9B,oBAAoB;AAK3B,SAASC,cAAc,QAAQ,qBAAqB;AACpD,SAASC,qBAAqB,QAAQ,kBAAkB;AACxD,SAASC,wBAAwB,QAAQ,wBAAwB;AAMjE,gBAAsBC,iBAAiB;EAAA;AAAA;AAiGtC;EAAA,8EAjGM,kBACHC,QAAkD,EAClDC,aAAmD;IAAA;IAAA;MAAA;QAAA;UAE7CC,SAAS,GAAGD,aAAa,CAACC,SAAS;UACnCC,KAAK,GAAGF,aAAa,CAACE,KAAK;UAC3BC,IAAI,GAAGD,KAAK,CAACC,IAAI,GAAGD,KAAK,CAACC,IAAI,GAAG,CAAC;UAClCC,KAAK,GAAG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AEAN,WAAW;kBAAA;kBAAA;oBAAA;gBAAA;cAAA;YAAA,CACrB;YAAA;cAAA;YAAA;UAAA,IAAC;QAAA;UAvCEuB,MAAM;UAwCV,IAAInD,kBAAkB,EAAE;YACdoD,cAAc,GAAGjE,qBAAqB,CAACkE,iBAAiB,CAAC/D,QAAQ,CAACe,MAAM,EAAEd,aAAa,CAAC;YAC9F4D,MAAM,GAAGA,MAAM,CAACG,IAAI,CAACF,cAAc,CAAC;UACxC;;UAEA;UACAD,MAAM,GAAGA,MAAM,CAACzC,KAAK,CAAChB,IAAI,EAAEG,aAAa,CAAC;UAAC,kCAEpC;YACH0D,SAAS,EAAEJ;UACf,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACJ;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/foundationdb-types.js b/dist/es/plugins/storage-foundationdb/foundationdb-types.js similarity index 100% rename from dist/es/plugins/foundationdb/foundationdb-types.js rename to dist/es/plugins/storage-foundationdb/foundationdb-types.js diff --git a/dist/es/plugins/storage-foundationdb/foundationdb-types.js.map b/dist/es/plugins/storage-foundationdb/foundationdb-types.js.map new file mode 100644 index 00000000000..8f74dc14034 --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/foundationdb-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"foundationdb-types.js","names":[],"sources":["../../../../src/plugins/storage-foundationdb/foundationdb-types.ts"],"sourcesContent":["/* eslint-disable no-unused-vars */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type {\n DexiePreparedQuery,\n EventBulk,\n RxAttachmentWriteData,\n RxDocumentData,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types';\nexport type RxStorageFoundationDBSettings = {\n /**\n * Version of the API of the foundationDB server.\n */\n apiVersion: number;\n /**\n * Path to the foundationDB cluster file\n * like '/path/to/fdb.cluster'\n * (optional)\n */\n clusterFile?: string;\n batchSize?: number;\n};\nexport type RxStorageFoundationDBInstanceCreationOptions = {\n // can be overwritte per instance\n batchSize?: number;\n};\n\n/**\n * TODO atm we cannot import types from 'foundationdb'\n * because 'foundationdb' is an optional peer dependency\n * this is NOT also in the devDependencies.\n * This is because it requires to install the foundationdb client cli\n * which would mean everyone that wants to develop RxDB must have this installed manually.\n */\n// import {\n// open as foundationDBOpen,\n// Database,\n// Transaction\n// } from 'foundationdb';\n\nexport type FoundationDBIndexMeta = {\n indexName: string;\n index: string[];\n getIndexableString: (doc: RxDocumentData) => string;\n db: FoundationDBDatabase;\n};\n\nexport type FoundationDBConnection = any; // ReturnType;\nexport type FoundationDBDatabase = any; // Database;\nexport type FoundationDBTransaction = any; // Transaction, any>;\nexport type FoundationDBStorageInternals = {\n connection: FoundationDBConnection;\n dbsPromise: Promise<{\n root: FoundationDBDatabase;\n main: FoundationDBDatabase;\n attachments: FoundationDBDatabase;\n events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>>;\n indexes: {\n [indexName: string]: FoundationDBIndexMeta;\n };\n }>;\n};\nexport type RxStorageFoundationDB = RxStorage, RxStorageFoundationDBInstanceCreationOptions> & {\n};\n\n\nexport type FoundationDBPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/foundationdb/index.js b/dist/es/plugins/storage-foundationdb/index.js similarity index 94% rename from dist/es/plugins/foundationdb/index.js rename to dist/es/plugins/storage-foundationdb/index.js index 27e01f2e3f8..6954365bacd 100644 --- a/dist/es/plugins/foundationdb/index.js +++ b/dist/es/plugins/storage-foundationdb/index.js @@ -1,5 +1,5 @@ import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper'; -import { RxStorageDexieStatics } from '../dexie/dexie-statics'; +import { RxStorageDexieStatics } from '../storage-dexie/dexie-statics'; import { createFoundationDBStorageInstance } from './rx-storage-instance-foundationdb'; var versionSet; export function getRxStorageFoundationDB(settings) { diff --git a/dist/es/plugins/storage-foundationdb/index.js.map b/dist/es/plugins/storage-foundationdb/index.js.map new file mode 100644 index 00000000000..f25f98562e5 --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["ensureRxStorageInstanceParamsAreCorrect","RxStorageDexieStatics","createFoundationDBStorageInstance","versionSet","getRxStorageFoundationDB","settings","apiVersion","Error","require","setAPIVersion","storage","name","statics","createStorageInstance","params","useSettings","Object","assign","options","batchSize"],"sources":["../../../../src/plugins/storage-foundationdb/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type {\n RxStorageInstanceCreationParams\n} from '../../types';\nimport { RxStorageDexieStatics } from '../storage-dexie/dexie-statics';\nimport type {\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n\nimport {\n createFoundationDBStorageInstance,\n RxStorageInstanceFoundationDB\n} from './rx-storage-instance-foundationdb';\n\n\nlet versionSet: undefined | number;\n\nexport function getRxStorageFoundationDB(\n settings: RxStorageFoundationDBSettings\n): RxStorageFoundationDB {\n if (versionSet && versionSet !== settings.apiVersion) {\n throw new Error('foundationdb already initialized with api version ' + versionSet);\n } else if (!versionSet) {\n versionSet = settings.apiVersion;\n const { setAPIVersion } = require('foundationdb');\n setAPIVersion(settings.apiVersion);\n }\n\n\n const storage: RxStorageFoundationDB = {\n name: 'foundationdb',\n statics: RxStorageDexieStatics,\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n if (!useSettings.batchSize) {\n useSettings.batchSize = 50;\n }\n return createFoundationDBStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './foundationdb-types';\nexport * from './foundationdb-helpers';\n"],"mappings":"AAAA,SAASA,uCAAuC,QAAQ,yBAAyB;AAIjF,SAASC,qBAAqB,QAAQ,gCAAgC;AAOtE,SACIC,iCAAiC,QAE9B,oCAAoC;AAG3C,IAAIC,UAA8B;AAElC,OAAO,SAASC,wBAAwB,CACpCC,QAAuC,EAClB;EACrB,IAAIF,UAAU,IAAIA,UAAU,KAAKE,QAAQ,CAACC,UAAU,EAAE;IAClD,MAAM,IAAIC,KAAK,CAAC,oDAAoD,GAAGJ,UAAU,CAAC;EACtF,CAAC,MAAM,IAAI,CAACA,UAAU,EAAE;IACpBA,UAAU,GAAGE,QAAQ,CAACC,UAAU;IAChC,eAA0BE,OAAO,CAAC,cAAc,CAAC;MAAzCC,aAAa,YAAbA,aAAa;IACrBA,aAAa,CAACJ,QAAQ,CAACC,UAAU,CAAC;EACtC;EAGA,IAAMI,OAA8B,GAAG;IACnCC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAEX,qBAAqB;IAC9BY,qBAAqB,iCACjBC,MAAgG,EAC/C;MACjDd,uCAAuC,CAACc,MAAM,CAAC;MAC/C,IAAMC,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFZ,QAAQ,EACRS,MAAM,CAACI,OAAO,CACjB;MACD,IAAI,CAACH,WAAW,CAACI,SAAS,EAAE;QACxBJ,WAAW,CAACI,SAAS,GAAG,EAAE;MAC9B;MACA,OAAOjB,iCAAiC,CAAC,IAAI,EAAEY,MAAM,EAAEC,WAAW,CAAC;IACvE;EACJ,CAAC;EAED,OAAOL,OAAO;AAClB;AAGA,cAAc,sBAAsB;AACpC,cAAc,wBAAwB"} \ No newline at end of file diff --git a/dist/es/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js b/dist/es/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js new file mode 100644 index 00000000000..b70feffd0ee --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js @@ -0,0 +1,598 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { Subject } from 'rxjs'; +import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; +// import { +// open as foundationDBOpen, +// directory as foundationDBDirectory, +// encoders as foundationDBEncoders, +// keySelector as foundationDBKeySelector, +// StreamingMode as foundationDBStreamingMode +// } from 'foundationdb'; +import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; +import { CLEANUP_INDEX, getFoundationDBIndexName } from './foundationdb-helpers'; +import { getIndexableStringMonad, getStartIndexStringFromLowerBound, getStartIndexStringFromUpperBound } from '../../custom-index'; +import { ensureNotFalsy, lastOfArray, now, PROMISE_RESOLVE_VOID, toArray } from '../../plugins/utils'; +import { queryFoundationDB } from './foundationdb-query'; +import { INDEX_MAX } from '../../query-planner'; +import { attachmentMapKey } from '../storage-memory'; +export var RxStorageInstanceFoundationDB = /*#__PURE__*/function () { + function RxStorageInstanceFoundationDB(storage, databaseName, collectionName, schema, internals, options, settings) { + this.closed = false; + this.changes$ = new Subject(); + this.storage = storage; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + this.settings = settings; + this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); + } + var _proto = RxStorageInstanceFoundationDB.prototype; + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(documentWrites, context) { + var _this = this; + var dbs, categorized, result, lastState; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context3.sent; + categorized = null; + _context3.next = 6; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(tx) { + var ret, ids, mainTx, attachmentTx, docsInDB; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + ret = { + success: {}, + error: {} + }; + ids = documentWrites.map(function (row) { + return row.document[_this.primaryPath]; + }); + mainTx = tx.at(dbs.main.subspace); + attachmentTx = tx.at(dbs.attachments.subspace); + docsInDB = new Map(); + /** + * TODO this might be faster if fdb + * any time adds a bulk-fetch-by-key method. + */ + _context2.next = 7; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(id) { + var doc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return mainTx.get(id); + case 2: + doc = _context.sent; + docsInDB.set(id, doc); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }())); + case 7: + categorized = categorizeBulkWriteRows(_this, _this.primaryPath, docsInDB, documentWrites, context); + ret.error = categorized.errors; + + // INSERTS + categorized.bulkInsertDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this.primaryPath]; + ret.success[docId] = writeRow.document; + + // insert document data + mainTx.set(docId, writeRow.document); + + // insert secondary indexes + Object.values(dbs.indexes).forEach(function (indexMeta) { + var indexString = indexMeta.getIndexableString(writeRow.document); + var indexTx = tx.at(indexMeta.db.subspace); + indexTx.set(indexString, docId); + }); + }); + // UPDATES + categorized.bulkUpdateDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this.primaryPath]; + + // overwrite document data + mainTx.set(docId, writeRow.document); + + // update secondary indexes + Object.values(dbs.indexes).forEach(function (indexMeta) { + var oldIndexString = indexMeta.getIndexableString(ensureNotFalsy(writeRow.previous)); + var newIndexString = indexMeta.getIndexableString(writeRow.document); + if (oldIndexString !== newIndexString) { + var indexTx = tx.at(indexMeta.db.subspace); + indexTx["delete"](oldIndexString); + indexTx.set(newIndexString, docId); + } + }); + ret.success[docId] = writeRow.document; + }); + + // attachments + categorized.attachmentsAdd.forEach(function (attachment) { + attachmentTx.set(attachmentMapKey(attachment.documentId, attachment.attachmentId), attachment.attachmentData); + }); + categorized.attachmentsUpdate.forEach(function (attachment) { + attachmentTx.set(attachmentMapKey(attachment.documentId, attachment.attachmentId), attachment.attachmentData); + }); + categorized.attachmentsRemove.forEach(function (attachment) { + attachmentTx["delete"](attachmentMapKey(attachment.documentId, attachment.attachmentId)); + }); + return _context2.abrupt("return", ret); + case 15: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + case 6: + result = _context3.sent; + /** + * The events must be emitted AFTER the transaction + * has finished. + * Otherwise an observable changestream might cause a read + * to a document that does not already exist outside of the transaction. + */ + if (ensureNotFalsy(categorized).eventBulk.events.length > 0) { + lastState = getNewestOfDocumentStates(this.primaryPath, Object.values(result.success)); + ensureNotFalsy(categorized).eventBulk.checkpoint = { + id: lastState[this.primaryPath], + lwt: lastState._meta.lwt + }; + this.changes$.next(ensureNotFalsy(categorized).eventBulk); + } + return _context3.abrupt("return", result); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function bulkWrite(_x, _x2) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(); + _proto.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(ids, withDeleted) { + var dbs; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context6.sent; + return _context6.abrupt("return", dbs.main.doTransaction( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(tx) { + var ret; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + ret = {}; + _context5.next = 3; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(docId) { + var docInDb; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return tx.get(docId); + case 2: + docInDb = _context4.sent; + if (docInDb && (!docInDb._deleted || withDeleted)) { + ret[docId] = docInDb; + } + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return function (_x8) { + return _ref4.apply(this, arguments); + }; + }())); + case 3: + return _context5.abrupt("return", ret); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x7) { + return _ref3.apply(this, arguments); + }; + }())); + case 4: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function findDocumentsById(_x5, _x6) { + return _findDocumentsById.apply(this, arguments); + } + return findDocumentsById; + }(); + _proto.query = function query(preparedQuery) { + return queryFoundationDB(this, preparedQuery); + }; + _proto.count = /*#__PURE__*/function () { + var _count = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(preparedQuery) { + var result; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.query(preparedQuery); + case 2: + result = _context7.sent; + return _context7.abrupt("return", { + count: result.documents.length, + mode: 'fast' + }); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function count(_x9) { + return _count.apply(this, arguments); + } + return count; + }(); + _proto.getAttachmentData = /*#__PURE__*/function () { + var _getAttachmentData = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(documentId, attachmentId) { + var dbs, attachment; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context8.sent; + _context8.next = 5; + return dbs.attachments.get(attachmentMapKey(documentId, attachmentId)); + case 5: + attachment = _context8.sent; + return _context8.abrupt("return", attachment.data); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function getAttachmentData(_x10, _x11) { + return _getAttachmentData.apply(this, arguments); + } + return getAttachmentData; + }(); + _proto.getChangedDocumentsSince = /*#__PURE__*/function () { + var _getChangedDocumentsSince = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(limit, checkpoint) { + var _require, keySelector, StreamingMode, dbs, index, indexName, indexMeta, lowerBoundString, _checkpointPartialDoc, checkpointPartialDoc, result, lastDoc; + return _regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + _require = require('foundationdb'), keySelector = _require.keySelector, StreamingMode = _require.StreamingMode; + _context10.next = 3; + return this.internals.dbsPromise; + case 3: + dbs = _context10.sent; + index = ['_meta.lwt', this.primaryPath]; + indexName = getFoundationDBIndexName(index); + indexMeta = dbs.indexes[indexName]; + lowerBoundString = ''; + if (checkpoint) { + checkpointPartialDoc = (_checkpointPartialDoc = {}, _checkpointPartialDoc[this.primaryPath] = checkpoint.id, _checkpointPartialDoc._meta = { + lwt: checkpoint.lwt + }, _checkpointPartialDoc); + lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc); + } + _context10.next = 11; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(tx) { + var innerResult, indexTx, mainTx, range, docIds, docsData; + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + innerResult = []; + indexTx = tx.at(indexMeta.db.subspace); + mainTx = tx.at(dbs.main.subspace); + _context9.next = 5; + return indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), INDEX_MAX, { + limit: limit, + streamingMode: StreamingMode.Exact + }); + case 5: + range = _context9.sent; + docIds = range.map(function (row) { + return row[1]; + }); + _context9.next = 9; + return Promise.all(docIds.map(function (docId) { + return mainTx.get(docId); + })); + case 9: + docsData = _context9.sent; + innerResult = innerResult.concat(docsData); + return _context9.abrupt("return", innerResult); + case 12: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + return function (_x14) { + return _ref5.apply(this, arguments); + }; + }()); + case 11: + result = _context10.sent; + lastDoc = lastOfArray(result); + return _context10.abrupt("return", { + documents: result, + checkpoint: lastDoc ? { + id: lastDoc[this.primaryPath], + lwt: lastDoc._meta.lwt + } : checkpoint ? checkpoint : { + id: '', + lwt: 0 + } + }); + case 14: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function getChangedDocumentsSince(_x12, _x13) { + return _getChangedDocumentsSince.apply(this, arguments); + } + return getChangedDocumentsSince; + }(); + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + _proto.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11() { + var dbs; + return _regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context11.sent; + _context11.next = 5; + return dbs.root.doTransaction(function (tx) { + tx.clearRange('', INDEX_MAX); + return PROMISE_RESOLVE_VOID; + }); + case 5: + return _context11.abrupt("return", this.close()); + case 6: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function remove() { + return _remove.apply(this, arguments); + } + return remove; + }(); + _proto.cleanup = /*#__PURE__*/function () { + var _cleanup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(minimumDeletedTime) { + var _this2 = this; + var _require2, keySelector, StreamingMode, maxDeletionTime, dbs, index, indexName, indexMeta, lowerBoundString, upperBoundString, noMoreUndeleted; + return _regeneratorRuntime.wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + _require2 = require('foundationdb'), keySelector = _require2.keySelector, StreamingMode = _require2.StreamingMode; + maxDeletionTime = now() - minimumDeletedTime; + _context13.next = 4; + return this.internals.dbsPromise; + case 4: + dbs = _context13.sent; + index = CLEANUP_INDEX; + indexName = getFoundationDBIndexName(index); + indexMeta = dbs.indexes[indexName]; + lowerBoundString = getStartIndexStringFromLowerBound(this.schema, index, [true, + /** + * Do not use 0 here, + * because 1 is the minimum value for _meta.lwt + */ + 1], false); + upperBoundString = getStartIndexStringFromUpperBound(this.schema, index, [true, maxDeletionTime], true); + noMoreUndeleted = true; + _context13.next = 13; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(tx) { + var batchSize, indexTx, mainTx, range, docIds, docsData; + return _regeneratorRuntime.wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + batchSize = ensureNotFalsy(_this2.settings.batchSize); + indexTx = tx.at(indexMeta.db.subspace); + mainTx = tx.at(dbs.main.subspace); + _context12.next = 5; + return indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), upperBoundString, { + limit: batchSize + 1, + // get one more extra to detect what to return from cleanup() + streamingMode: StreamingMode.Exact + }); + case 5: + range = _context12.sent; + if (range.length > batchSize) { + noMoreUndeleted = false; + range.pop(); + } + docIds = range.map(function (row) { + return row[1]; + }); + _context12.next = 10; + return Promise.all(docIds.map(function (docId) { + return mainTx.get(docId); + })); + case 10: + docsData = _context12.sent; + Object.values(dbs.indexes).forEach(function (indexMetaInner) { + var subIndexDB = tx.at(indexMetaInner.db.subspace); + docsData.forEach(function (docData) { + var indexString = indexMetaInner.getIndexableString(docData); + subIndexDB["delete"](indexString); + }); + }); + docIds.forEach(function (id) { + return mainTx["delete"](id); + }); + case 13: + case "end": + return _context12.stop(); + } + }, _callee12); + })); + return function (_x16) { + return _ref6.apply(this, arguments); + }; + }()); + case 13: + return _context13.abrupt("return", noMoreUndeleted); + case 14: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function cleanup(_x15) { + return _cleanup.apply(this, arguments); + } + return cleanup; + }(); + _proto.conflictResultionTasks = function conflictResultionTasks() { + return new Subject().asObservable(); + }; + _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { + return PROMISE_RESOLVE_VOID; + }; + _proto.close = /*#__PURE__*/function () { + var _close = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14() { + var dbs; + return _regeneratorRuntime.wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + if (!this.closed) { + _context14.next = 2; + break; + } + return _context14.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.changes$.complete(); + _context14.next = 6; + return this.internals.dbsPromise; + case 6: + dbs = _context14.sent; + dbs.root.close(); + + // TODO shouldn't we close the index databases? + // Object.values(dbs.indexes).forEach(db => db.close()); + case 8: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function close() { + return _close.apply(this, arguments); + } + return close; + }(); + return RxStorageInstanceFoundationDB; +}(); +export function createFoundationDBStorageInstance(storage, params, settings) { + var primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey); + var _require3 = require('foundationdb'), + open = _require3.open, + directory = _require3.directory, + encoders = _require3.encoders; + var connection = open(settings.clusterFile); + var dbsPromise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15() { + var dir, root, main, events, attachments, indexDBs, useIndexes, useIndexesFinal; + return _regeneratorRuntime.wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + _context15.next = 2; + return directory.createOrOpen(connection, 'rxdb'); + case 2: + dir = _context15.sent; + root = connection.at(dir).at(params.databaseName + '.').at(params.collectionName + '.').at(params.schema.version + '.'); + main = root.at('main.').withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples + .withValueEncoding(encoders.json); // and values using JSON + events = root.at('events.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); + attachments = root.at('attachments.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); + indexDBs = {}; + useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : []; + useIndexes.push([primaryPath]); + useIndexesFinal = useIndexes.map(function (index) { + var indexAr = toArray(index); + indexAr.unshift('_deleted'); + return indexAr; + }); // used for `getChangedDocumentsSince()` + useIndexesFinal.push(['_meta.lwt', primaryPath]); + useIndexesFinal.push(CLEANUP_INDEX); + useIndexesFinal.forEach(function (indexAr) { + var indexName = getFoundationDBIndexName(indexAr); + var indexDB = root.at(indexName + '.').withKeyEncoding(encoders.string).withValueEncoding(encoders.string); + indexDBs[indexName] = { + indexName: indexName, + db: indexDB, + getIndexableString: getIndexableStringMonad(params.schema, indexAr), + index: indexAr + }; + }); + return _context15.abrupt("return", { + root: root, + main: main, + events: events, + attachments: attachments, + indexes: indexDBs + }); + case 15: + case "end": + return _context15.stop(); + } + }, _callee15); + }))(); + var internals = { + connection: connection, + dbsPromise: dbsPromise + }; + var instance = new RxStorageInstanceFoundationDB(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); + return Promise.resolve(instance); +} +//# sourceMappingURL=rx-storage-instance-foundationdb.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js.map b/dist/es/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js.map new file mode 100644 index 00000000000..e06ff42cdda --- /dev/null +++ b/dist/es/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-foundationdb.js","names":["Subject","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","CLEANUP_INDEX","getFoundationDBIndexName","getIndexableStringMonad","getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","ensureNotFalsy","lastOfArray","now","PROMISE_RESOLVE_VOID","toArray","queryFoundationDB","INDEX_MAX","attachmentMapKey","RxStorageInstanceFoundationDB","storage","databaseName","collectionName","schema","internals","options","settings","closed","changes$","primaryPath","primaryKey","bulkWrite","documentWrites","context","dbsPromise","dbs","categorized","root","doTransaction","tx","ret","success","error","ids","map","row","document","mainTx","at","main","subspace","attachmentTx","attachments","docsInDB","Map","Promise","all","id","get","doc","set","errors","bulkInsertDocs","forEach","writeRow","docId","Object","values","indexes","indexMeta","indexString","getIndexableString","indexTx","db","bulkUpdateDocs","oldIndexString","previous","newIndexString","attachmentsAdd","attachment","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","result","eventBulk","events","length","lastState","checkpoint","lwt","_meta","next","findDocumentsById","withDeleted","docInDb","_deleted","query","preparedQuery","count","documents","mode","getAttachmentData","data","getChangedDocumentsSince","limit","require","keySelector","StreamingMode","index","indexName","lowerBoundString","checkpointPartialDoc","innerResult","getRangeAll","firstGreaterThan","streamingMode","Exact","range","docIds","docsData","concat","lastDoc","changeStream","asObservable","remove","clearRange","close","cleanup","minimumDeletedTime","maxDeletionTime","upperBoundString","noMoreUndeleted","batchSize","pop","indexMetaInner","subIndexDB","docData","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","reject","Error","complete","createFoundationDBStorageInstance","params","open","directory","encoders","connection","clusterFile","createOrOpen","dir","version","withKeyEncoding","string","withValueEncoding","json","indexDBs","useIndexes","slice","push","useIndexesFinal","indexAr","unshift","indexDB","instance","resolve"],"sources":["../../../../src/plugins/storage-foundationdb/rx-storage-instance-foundationdb.ts"],"sourcesContent":["import { Observable, Subject } from 'rxjs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type {\n BulkWriteRow,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport type {\n FoundationDBDatabase,\n FoundationDBIndexMeta,\n FoundationDBPreparedQuery,\n FoundationDBStorageInternals,\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n// import {\n// open as foundationDBOpen,\n// directory as foundationDBDirectory,\n// encoders as foundationDBEncoders,\n// keySelector as foundationDBKeySelector,\n// StreamingMode as foundationDBStreamingMode\n// } from 'foundationdb';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport {\n\n CLEANUP_INDEX,\n getFoundationDBIndexName\n} from './foundationdb-helpers';\nimport {\n getIndexableStringMonad,\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport {\n ensureNotFalsy,\n lastOfArray,\n now,\n PROMISE_RESOLVE_VOID,\n toArray\n} from '../../plugins/utils';\nimport { queryFoundationDB } from './foundationdb-query';\nimport { INDEX_MAX } from '../../query-planner';\nimport { attachmentMapKey } from '../storage-memory';\n\nexport class RxStorageInstanceFoundationDB implements RxStorageInstance<\n RxDocType,\n FoundationDBStorageInternals,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n\n public closed = false;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n\n constructor(\n public readonly storage: RxStorageFoundationDB,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: FoundationDBStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageFoundationDBSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n const dbs = await this.internals.dbsPromise;\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n const result = await dbs.root.doTransaction(async (tx: any) => {\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const ids = documentWrites.map(row => (row.document as any)[this.primaryPath]);\n const mainTx = tx.at(dbs.main.subspace);\n const attachmentTx = tx.at(dbs.attachments.subspace);\n const docsInDB = new Map>();\n /**\n * TODO this might be faster if fdb\n * any time adds a bulk-fetch-by-key method.\n */\n await Promise.all(\n ids.map(async (id) => {\n const doc = await mainTx.get(id);\n docsInDB.set(id, doc);\n })\n );\n\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDB,\n documentWrites,\n context\n );\n\n ret.error = categorized.errors;\n\n // INSERTS\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n ret.success[docId] = writeRow.document as any;\n\n // insert document data\n mainTx.set(docId, writeRow.document);\n\n // insert secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const indexString = indexMeta.getIndexableString(writeRow.document as any);\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.set(indexString, docId);\n });\n });\n // UPDATES\n categorized.bulkUpdateDocs.forEach((writeRow: BulkWriteRow) => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n\n // overwrite document data\n mainTx.set(docId, writeRow.document);\n\n // update secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const oldIndexString = indexMeta.getIndexableString(ensureNotFalsy(writeRow.previous));\n const newIndexString = indexMeta.getIndexableString(writeRow.document as any);\n if (oldIndexString !== newIndexString) {\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.delete(oldIndexString);\n indexTx.set(newIndexString, docId);\n }\n });\n ret.success[docId] = writeRow.document as any;\n });\n\n // attachments\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentTx.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n\n return ret;\n });\n /**\n * The events must be emitted AFTER the transaction\n * has finished.\n * Otherwise an observable changestream might cause a read\n * to a document that does not already exist outside of the transaction.\n */\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(result.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n return result;\n }\n\n async findDocumentsById(ids: string[], withDeleted: boolean): Promise> {\n const dbs = await this.internals.dbsPromise;\n return dbs.main.doTransaction(async (tx: any) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n ids.map(async (docId) => {\n const docInDb = await tx.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n })\n );\n return ret;\n });\n }\n query(preparedQuery: FoundationDBPreparedQuery): Promise> {\n return queryFoundationDB(this, preparedQuery);\n }\n async count(\n preparedQuery: FoundationDBPreparedQuery\n ): Promise {\n /**\n * At this point in time (end 2022), FoundationDB does not support\n * range counts. So we have to run a normal query and use the result set length.\n * @link https://github.com/apple/foundationdb/issues/5981\n */\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n async getAttachmentData(documentId: string, attachmentId: string): Promise {\n const dbs = await this.internals.dbsPromise;\n const attachment = await dbs.attachments.get(attachmentMapKey(documentId, attachmentId));\n return attachment.data;\n }\n async getChangedDocumentsSince(limit: number, checkpoint?: RxStorageDefaultCheckpoint): Promise<{ documents: RxDocumentData[]; checkpoint: RxStorageDefaultCheckpoint; }> {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const dbs = await this.internals.dbsPromise;\n const index = [\n '_meta.lwt',\n this.primaryPath as any\n ];\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n let lowerBoundString = '';\n if (checkpoint) {\n const checkpointPartialDoc: any = {\n [this.primaryPath]: checkpoint.id,\n _meta: {\n lwt: checkpoint.lwt\n }\n };\n lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc);\n }\n const result: RxDocumentData[] = await dbs.root.doTransaction(async (tx: any) => {\n let innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n INDEX_MAX,\n {\n limit,\n streamingMode: StreamingMode.Exact\n }\n );\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(\n docIds.map((docId: string) => mainTx.get(docId))\n );\n innerResult = innerResult.concat(docsData);\n return innerResult;\n });\n const lastDoc = lastOfArray(result);\n return {\n documents: result,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n changeStream(): Observable, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async remove(): Promise {\n const dbs = await this.internals.dbsPromise;\n await dbs.root.doTransaction((tx: any) => {\n tx.clearRange('', INDEX_MAX);\n return PROMISE_RESOLVE_VOID;\n });\n return this.close();\n }\n async cleanup(minimumDeletedTime: number): Promise {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const maxDeletionTime = now() - minimumDeletedTime;\n const dbs = await this.internals.dbsPromise;\n const index = CLEANUP_INDEX;\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n /**\n * Do not use 0 here,\n * because 1 is the minimum value for _meta.lwt\n */\n 1\n ],\n false\n );\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n [\n true,\n maxDeletionTime\n ],\n true\n );\n let noMoreUndeleted: boolean = true;\n await dbs.root.doTransaction(async (tx: any) => {\n const batchSize = ensureNotFalsy(this.settings.batchSize);\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n upperBoundString,\n {\n limit: batchSize + 1, // get one more extra to detect what to return from cleanup()\n streamingMode: StreamingMode.Exact\n }\n );\n if (range.length > batchSize) {\n noMoreUndeleted = false;\n range.pop();\n }\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n\n Object\n .values(dbs.indexes)\n .forEach(indexMetaInner => {\n const subIndexDB = tx.at(indexMetaInner.db.subspace);\n docsData.forEach(docData => {\n const indexString = indexMetaInner.getIndexableString(docData);\n subIndexDB.delete(indexString);\n });\n });\n docIds.forEach((id: string) => mainTx.delete(id));\n });\n\n return noMoreUndeleted;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject().asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n\n async close() {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n\n const dbs = await this.internals.dbsPromise;\n dbs.root.close();\n\n // TODO shouldn't we close the index databases?\n // Object.values(dbs.indexes).forEach(db => db.close());\n }\n}\n\n\nexport function createFoundationDBStorageInstance(\n storage: RxStorageFoundationDB,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageFoundationDBSettings\n): Promise> {\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n const {\n open,\n directory,\n encoders\n } = require('foundationdb');\n\n const connection = open(settings.clusterFile);\n const dbsPromise = (async () => {\n const dir = await directory.createOrOpen(connection, 'rxdb');\n\n const root = connection\n .at(dir)\n .at(params.databaseName + '.')\n .at(params.collectionName + '.')\n .at(params.schema.version + '.');\n const main: FoundationDBDatabase = root\n .at('main.')\n .withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples\n .withValueEncoding(encoders.json) as any; // and values using JSON\n\n\n const events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>> = root\n .at('events.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n const attachments: FoundationDBDatabase = root\n .at('attachments.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n\n const indexDBs: { [indexName: string]: FoundationDBIndexMeta; } = {};\n const useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : [];\n useIndexes.push([primaryPath]);\n const useIndexesFinal = useIndexes.map(index => {\n const indexAr = toArray(index);\n indexAr.unshift('_deleted');\n return indexAr;\n });\n // used for `getChangedDocumentsSince()`\n useIndexesFinal.push([\n '_meta.lwt',\n primaryPath\n ]);\n useIndexesFinal.push(CLEANUP_INDEX);\n useIndexesFinal.forEach(indexAr => {\n const indexName = getFoundationDBIndexName(indexAr);\n const indexDB = root.at(indexName + '.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.string);\n indexDBs[indexName] = {\n indexName,\n db: indexDB,\n getIndexableString: getIndexableStringMonad(params.schema, indexAr),\n index: indexAr\n };\n });\n\n return {\n root,\n main,\n events,\n attachments,\n indexes: indexDBs\n };\n })();\n\n\n const internals: FoundationDBStorageInternals = {\n connection,\n dbsPromise: dbsPromise\n };\n\n const instance = new RxStorageInstanceFoundationDB(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;AAAA,SAAqBA,OAAO,QAAQ,MAAM;AAC1C,SAASC,2BAA2B,QAAQ,wBAAwB;AA6BpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SACIC,uBAAuB,EACvBC,yBAAyB,QACtB,yBAAyB;AAChC,SAEIC,aAAa,EACbC,wBAAwB,QACrB,wBAAwB;AAC/B,SACIC,uBAAuB,EACvBC,iCAAiC,EACjCC,iCAAiC,QAC9B,oBAAoB;AAC3B,SACIC,cAAc,EACdC,WAAW,EACXC,GAAG,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sC,MAAM,EAANA,MAAM;YACNnC,WAAW,EAAXA,WAAW;YACXgB,OAAO,EAAE2F;UACb,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACJ,IAAG;EAGJ,IAAMvI,SAAkD,GAAG;IACvD8H,UAAU,EAAVA,UAAU;IACVpH,UAAU,EAAEA;EAChB,CAAC;EAED,IAAMqI,QAAQ,GAAG,IAAIpJ,6BAA6B,CAC9CC,OAAO,EACP8H,MAAM,CAAC7H,YAAY,EACnB6H,MAAM,CAAC5H,cAAc,EACrB4H,MAAM,CAAC3H,MAAM,EACbC,SAAS,EACT0H,MAAM,CAACzH,OAAO,EACdC,QAAQ,CACX;EACD,OAAO6B,OAAO,CAACiH,OAAO,CAACD,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/index.js b/dist/es/plugins/storage-lokijs/index.js similarity index 100% rename from dist/es/plugins/lokijs/index.js rename to dist/es/plugins/storage-lokijs/index.js diff --git a/dist/es/plugins/storage-lokijs/index.js.map b/dist/es/plugins/storage-lokijs/index.js.map new file mode 100644 index 00000000000..49e5d7e1a4d --- /dev/null +++ b/dist/es/plugins/storage-lokijs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/storage-lokijs/index.ts"],"sourcesContent":["export * from './rx-storage-lokijs';\nexport * from './lokijs-helper';\nexport * from './rx-storage-instance-loki';\n"],"mappings":"AAAA,cAAc,qBAAqB;AACnC,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/loki-save-queue.js b/dist/es/plugins/storage-lokijs/loki-save-queue.js similarity index 58% rename from dist/es/plugins/lokijs/loki-save-queue.js rename to dist/es/plugins/storage-lokijs/loki-save-queue.js index dda1d4974a6..2af902c25af 100644 --- a/dist/es/plugins/lokijs/loki-save-queue.js +++ b/dist/es/plugins/storage-lokijs/loki-save-queue.js @@ -1,4 +1,6 @@ -import { PROMISE_RESOLVE_VOID, requestIdlePromise } from '../../util'; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { PROMISE_RESOLVE_VOID, requestIdlePromise } from '../utils'; /** * The autosave feature of lokijs has strange behaviors @@ -37,34 +39,34 @@ export var LokiSaveQueue = /*#__PURE__*/function () { return this.saveQueue; } this.saveQueueC = this.saveQueueC + 1; - this.saveQueue = this.saveQueue.then(function () { - try { - /** - * Always wait until the JavaScript process is idle. - * This ensures that CPU blocking writes are finished - * before we proceed. - */ - return Promise.resolve(requestIdlePromise()).then(function () { - // no write happened since the last save call - if (_this.writesSinceLastRun === 0) { - return; - } - - /** - * Because LokiJS is a in-memory database, - * we can just wait until the JavaScript process is idle - * via requestIdlePromise(). Then we know that nothing important - * is running at the moment. - */ - return Promise.resolve(requestIdlePromise().then(function () { + this.saveQueue = this.saveQueue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var writeAmount; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; return requestIdlePromise(); - })).then(function () { - if (_this.writesSinceLastRun === 0) { - return; + case 2: + if (!(_this.writesSinceLastRun === 0)) { + _context.next = 4; + break; + } + return _context.abrupt("return"); + case 4: + _context.next = 6; + return requestIdlePromise().then(function () { + return requestIdlePromise(); + }); + case 6: + if (!(_this.writesSinceLastRun === 0)) { + _context.next = 8; + break; } - var writeAmount = _this.writesSinceLastRun; + return _context.abrupt("return"); + case 8: + writeAmount = _this.writesSinceLastRun; _this.writesSinceLastRun = 0; - return new Promise(function (res, rej) { + return _context.abrupt("return", new Promise(function (res, rej) { _this.lokiDatabase.saveDatabase(function (err) { if (err) { _this.writesSinceLastRun = _this.writesSinceLastRun + writeAmount; @@ -76,13 +78,13 @@ export var LokiSaveQueue = /*#__PURE__*/function () { res(); } }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })["catch"](function () {}).then(function () { + })); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })))["catch"](function () {}).then(function () { _this.saveQueueC = _this.saveQueueC - 1; }); return this.saveQueue; diff --git a/dist/es/plugins/storage-lokijs/loki-save-queue.js.map b/dist/es/plugins/storage-lokijs/loki-save-queue.js.map new file mode 100644 index 00000000000..e1cf2b1416f --- /dev/null +++ b/dist/es/plugins/storage-lokijs/loki-save-queue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"loki-save-queue.js","names":["PROMISE_RESOLVE_VOID","requestIdlePromise","LokiSaveQueue","lokiDatabase","databaseSettings","writesSinceLastRun","saveQueue","saveQueueC","addWrite","run","adapter","then","writeAmount","Promise","res","rej","saveDatabase","err","autosaveCallback"],"sources":["../../../../src/plugins/storage-lokijs/loki-save-queue.ts"],"sourcesContent":["import type { LokiDatabaseSettings } from '../../types';\nimport {\n PROMISE_RESOLVE_VOID,\n requestIdlePromise\n} from '../utils';\n\n/**\n * The autosave feature of lokijs has strange behaviors\n * and often runs a save in critical moments when other\n * more important tasks are running.\n * So instead we use a custom save queue that ensures we\n * only run loki.saveDatabase() when nothing else is running.\n */\nexport class LokiSaveQueue {\n public writesSinceLastRun: number = 0;\n\n /**\n * Ensures that we do not run multiple saves\n * in parallel\n */\n public saveQueue: Promise = PROMISE_RESOLVE_VOID;\n // track amount of non-finished save calls in the queue.\n public saveQueueC = 0;\n\n constructor(\n public readonly lokiDatabase: Loki,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n\n }\n\n public addWrite() {\n this.writesSinceLastRun = this.writesSinceLastRun + 1;\n this.run();\n }\n\n public run() {\n if (\n // no persistence adapter given, so we do not need to save\n !this.databaseSettings.adapter ||\n // do not add more then two pending calls to the queue.\n this.saveQueueC > 2\n\n ) {\n return this.saveQueue;\n }\n\n this.saveQueueC = this.saveQueueC + 1;\n this.saveQueue = this.saveQueue\n .then(async () => {\n /**\n * Always wait until the JavaScript process is idle.\n * This ensures that CPU blocking writes are finished\n * before we proceed.\n */\n await requestIdlePromise();\n\n // no write happened since the last save call\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n /**\n * Because LokiJS is a in-memory database,\n * we can just wait until the JavaScript process is idle\n * via requestIdlePromise(). Then we know that nothing important\n * is running at the moment.\n */\n await requestIdlePromise().then(() => requestIdlePromise());\n\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n const writeAmount = this.writesSinceLastRun;\n this.writesSinceLastRun = 0;\n return new Promise((res, rej) => {\n this.lokiDatabase.saveDatabase(err => {\n if (err) {\n this.writesSinceLastRun = this.writesSinceLastRun + writeAmount;\n rej(err);\n } else {\n if (this.databaseSettings.autosaveCallback) {\n this.databaseSettings.autosaveCallback();\n }\n res();\n }\n });\n });\n })\n .catch(() => { })\n .then(() => {\n this.saveQueueC = this.saveQueueC - 1;\n });\n return this.saveQueue;\n }\n}\n"],"mappings":";;AACA,SACIA,oBAAoB,EACpBC,kBAAkB,QACf,UAAU;;AAEjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAaC,aAAa;EAGtB;AACJ;AACA;AACA;;EAEI;;EAGA,uBACoBC,YAAkB,EAClBC,gBAAsC,EACxD;IAAA,KAbKC,kBAAkB,GAAW,CAAC;IAAA,KAM9BC,SAAS,GAAkBN,oBAAoB;IAAA,KAE/CO,UAAU,GAAG,CAAC;IAAA,KAGDJ,YAAkB,GAAlBA,YAAkB;IAAA,KAClBC,gBAAsC,GAAtCA,gBAAsC;EAG1D;EAAC;EAAA,OAEMI,QAAQ,GAAf,oBAAkB;IACd,IAAI,CAACH,kBAAkB,GAAG,IAAI,CAACA,kBAAkB,GAAG,CAAC;IACrD,IAAI,CAACI,GAAG,EAAE;EACd,CAAC;EAAA,OAEMA,GAAG,GAAV,eAAa;IAAA;IACT;IACI;IACA,CAAC,IAAI,CAACL,gBAAgB,CAACM,OAAO;IAC9B;IACA,IAAI,CAACH,UAAU,GAAG,CAAC,EAErB;MACE,OAAO,IAAI,CAACD,SAAS;IACz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ist/es/plugins/storage-lokijs/lokijs-helper.js b/dist/es/plugins/storage-lokijs/lokijs-helper.js new file mode 100644 index 00000000000..49bb115c243 --- /dev/null +++ b/dist/es/plugins/storage-lokijs/lokijs-helper.js @@ -0,0 +1,501 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { createLokiLocalState } from './rx-storage-instance-loki'; +import lokijs from 'lokijs'; +import { add as unloadAdd } from 'unload'; +import { ensureNotFalsy, flatClone, promiseWait, randomCouchString } from '../utils'; +import { LokiSaveQueue } from './loki-save-queue'; +import { newRxError } from '../../rx-error'; +import objectPath from 'object-path'; +import { getBroadcastChannelReference } from '../../rx-storage-multiinstance'; +import { getLeaderElectorByBroadcastChannel } from '../leader-election'; +export var CHANGES_COLLECTION_SUFFIX = '-rxdb-changes'; +export var LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request'; +export var LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object'; +export var RX_STORAGE_NAME_LOKIJS = 'lokijs'; + +/** + * Loki attaches a $loki property to all data + * which must be removed before returning the data back to RxDB. + */ +export function stripLokiKey(docData) { + if (!docData.$loki) { + return docData; + } + var cloned = flatClone(docData); + + /** + * In RxDB version 12.0.0, + * we introduced the _meta field that already contains the last write time. + * To be backwards compatible, we have to move the $lastWriteAt to the _meta field. + * TODO remove this in the next major version. + */ + if (cloned.$lastWriteAt) { + cloned._meta = { + lwt: cloned.$lastWriteAt + }; + delete cloned.$lastWriteAt; + } + delete cloned.$loki; + return cloned; +} + +/** + * Used to check in tests if all instances have been cleaned up. + */ +export var OPEN_LOKIJS_STORAGE_INSTANCES = new Set(); +export var LOKIJS_COLLECTION_DEFAULT_OPTIONS = { + disableChangesApi: true, + disableMeta: true, + disableDeltaChangesApi: true, + disableFreeze: true, + // TODO use 'immutable' like WatermelonDB does it + cloneMethod: 'shallow-assign', + clone: false, + transactional: false, + autoupdate: false +}; +var LOKI_DATABASE_STATE_BY_NAME = new Map(); +export function getLokiDatabase(databaseName, databaseSettings) { + var databaseState = LOKI_DATABASE_STATE_BY_NAME.get(databaseName); + if (!databaseState) { + /** + * We assume that as soon as an adapter is passed, + * the database has to be persistend. + */ + var hasPersistence = !!databaseSettings.adapter; + databaseState = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var persistenceMethod, useSettings, database, lokiSaveQueue, loadDatabasePromise, unloads, state; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + persistenceMethod = hasPersistence ? 'adapter' : 'memory'; + if (databaseSettings.persistenceMethod) { + persistenceMethod = databaseSettings.persistenceMethod; + } + useSettings = Object.assign( + // defaults + { + autoload: hasPersistence, + persistenceMethod: persistenceMethod, + verbose: true + }, databaseSettings, + // overwrites + { + /** + * RxDB uses its custom load and save handling + * so we disable the LokiJS save/load handlers. + */ + autoload: false, + autosave: false, + throttledSaves: false + }); + database = new lokijs(databaseName + '.db', flatClone(useSettings)); + lokiSaveQueue = new LokiSaveQueue(database, useSettings); + /** + * Wait until all data is loaded from persistence adapter. + * Wrap the loading into the saveQueue to ensure that when many + * collections are created at the same time, the load-calls do not interfere + * with each other and cause error logs. + */ + if (!hasPersistence) { + _context.next = 10; + break; + } + loadDatabasePromise = new Promise(function (res, rej) { + try { + database.loadDatabase({ + recursiveWait: false + }, function (err) { + if (useSettings.autoloadCallback) { + useSettings.autoloadCallback(err); + } + if (err) { + rej(err); + } else { + res(); + } + }); + } catch (err) { + rej(err); + } + }); + lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(function () { + return loadDatabasePromise; + }); + _context.next = 10; + return loadDatabasePromise; + case 10: + /** + * Autosave database on process end + */ + unloads = []; + if (hasPersistence) { + unloads.push(unloadAdd(function () { + return lokiSaveQueue.run(); + })); + } + state = { + database: database, + databaseSettings: useSettings, + saveQueue: lokiSaveQueue, + collections: {}, + unloads: unloads + }; + return _context.abrupt("return", state); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))(); + LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState); + } + return databaseState; +} +export function closeLokiCollections(_x, _x2) { + return _closeLokiCollections.apply(this, arguments); +} + +/** + * This function is at lokijs-helper + * because we need it in multiple places. + */ +function _closeLokiCollections() { + _closeLokiCollections = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(databaseName, collections) { + var databaseState; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return LOKI_DATABASE_STATE_BY_NAME.get(databaseName); + case 2: + databaseState = _context2.sent; + if (databaseState) { + _context2.next = 5; + break; + } + return _context2.abrupt("return"); + case 5: + _context2.next = 7; + return databaseState.saveQueue.run(); + case 7: + collections.forEach(function (collection) { + var collectionName = collection.name; + delete databaseState.collections[collectionName]; + }); + if (!(Object.keys(databaseState.collections).length === 0)) { + _context2.next = 13; + break; + } + // all collections closed -> also close database + LOKI_DATABASE_STATE_BY_NAME["delete"](databaseName); + databaseState.unloads.forEach(function (u) { + return u.remove(); + }); + _context2.next = 13; + return new Promise(function (res, rej) { + databaseState.database.close(function (err) { + if (err) { + rej(err); + } else { + res(); + } + }); + }); + case 13: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _closeLokiCollections.apply(this, arguments); +} +export function getLokiSortComparator(_schema, query) { + if (!query.sort) { + throw newRxError('SNH', { + query: query + }); + } + var sortOptions = query.sort; + var fun = function fun(a, b) { + var compareResult = 0; // 1 | -1 + sortOptions.find(function (sortPart) { + var fieldName = Object.keys(sortPart)[0]; + var direction = Object.values(sortPart)[0]; + var directionMultiplier = direction === 'asc' ? 1 : -1; + var valueA = objectPath.get(a, fieldName); + var valueB = objectPath.get(b, fieldName); + if (valueA === valueB) { + return false; + } else { + if (valueA > valueB) { + compareResult = 1 * directionMultiplier; + return true; + } else { + compareResult = -1 * directionMultiplier; + return true; + } + } + }); + + /** + * Two different objects should never have the same sort position. + * We ensure this by having the unique primaryKey in the sort params + * which is added by RxDB if not existing yet. + */ + if (!compareResult) { + throw newRxError('SNH', { + args: { + query: query, + a: a, + b: b + } + }); + } + return compareResult; + }; + return fun; +} +export function getLokiLeaderElector(databaseInstanceToken, broadcastChannelRefObject, databaseName) { + var broadcastChannel = getBroadcastChannelReference(databaseInstanceToken, databaseName, broadcastChannelRefObject); + var elector = getLeaderElectorByBroadcastChannel(broadcastChannel); + return elector; +} + +/** + * For multi-instance usage, we send requests to the RxStorage + * to the current leading instance over the BroadcastChannel. + */ +export function requestRemoteInstance(_x3, _x4, _x5) { + return _requestRemoteInstance.apply(this, arguments); +} + +/** + * Handles a request that came from a remote instance via requestRemoteInstance() + * Runs the requested operation over the local db instance and sends back the result. + */ +function _requestRemoteInstance() { + _requestRemoteInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(instance, operation, params) { + var isRxStorageInstanceLoki, messageType, leaderElector, broadcastChannel, whenDeathListener, leaderDeadPromise, requestId, responseListener, responsePromise; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + isRxStorageInstanceLoki = typeof instance.query === 'function'; + messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE; + leaderElector = ensureNotFalsy(instance.internals.leaderElector); + _context3.next = 5; + return waitUntilHasLeader(leaderElector); + case 5: + broadcastChannel = leaderElector.broadcastChannel; + leaderDeadPromise = new Promise(function (res) { + whenDeathListener = function whenDeathListener(msg) { + if (msg.context === 'leader' && msg.action === 'death') { + res({ + retry: true + }); + } + }; + broadcastChannel.addEventListener('internal', whenDeathListener); + }); + requestId = randomCouchString(12); + responsePromise = new Promise(function (res, _rej) { + responseListener = function responseListener(msg) { + if (msg.type === messageType && msg.response === true && msg.requestId === requestId) { + if (msg.isError) { + res({ + retry: false, + error: msg.result + }); + } else { + res({ + retry: false, + result: msg.result + }); + } + } + }; + broadcastChannel.addEventListener('message', responseListener); + }); // send out the request to the other instance + broadcastChannel.postMessage({ + response: false, + type: messageType, + operation: operation, + params: params, + requestId: requestId, + databaseName: instance.databaseName, + collectionName: instance.collectionName + }); + return _context3.abrupt("return", Promise.race([leaderDeadPromise, responsePromise]).then(function (firstResolved) { + // clean up listeners + broadcastChannel.removeEventListener('message', responseListener); + broadcastChannel.removeEventListener('internal', whenDeathListener); + if (firstResolved.retry) { + var _ref2; + /** + * The leader died while a remote request was running + * we re-run the whole operation. + * We cannot just re-run requestRemoteInstance() + * because the current instance might be the new leader now + * and then we have to use the local state instead of requesting the remote. + */ + return (_ref2 = instance)[operation].apply(_ref2, params); + } else { + if (firstResolved.error) { + throw firstResolved.error; + } else { + return firstResolved.result; + } + } + })); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _requestRemoteInstance.apply(this, arguments); +} +export function handleRemoteRequest(_x6, _x7) { + return _handleRemoteRequest.apply(this, arguments); +} +function _handleRemoteRequest() { + _handleRemoteRequest = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(instance, msg) { + var operation, params, result, isError, _ref3, response; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE && msg.requestId && msg.databaseName === instance.databaseName && msg.collectionName === instance.collectionName && !msg.response)) { + _context4.next = 17; + break; + } + operation = msg.operation; + params = msg.params; + isError = false; + _context4.prev = 4; + _context4.next = 7; + return (_ref3 = instance)[operation].apply(_ref3, params); + case 7: + result = _context4.sent; + _context4.next = 15; + break; + case 10: + _context4.prev = 10; + _context4.t0 = _context4["catch"](4); + console.dir(_context4.t0); + isError = true; + result = _context4.t0; + case 15: + response = { + response: true, + requestId: msg.requestId, + databaseName: instance.databaseName, + collectionName: instance.collectionName, + result: result, + isError: isError, + type: msg.type + }; + ensureNotFalsy(instance.internals.leaderElector).broadcastChannel.postMessage(response); + case 17: + case "end": + return _context4.stop(); + } + }, _callee4, null, [[4, 10]]); + })); + return _handleRemoteRequest.apply(this, arguments); +} +export function waitUntilHasLeader(_x8) { + return _waitUntilHasLeader.apply(this, arguments); +} + +/** + * If the local state must be used, that one is returned. + * Returns false if a remote instance must be used. + */ +function _waitUntilHasLeader() { + _waitUntilHasLeader = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(leaderElector) { + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (leaderElector.hasLeader) { + _context5.next = 7; + break; + } + _context5.next = 3; + return leaderElector.applyOnce(); + case 3: + _context5.next = 5; + return promiseWait(0); + case 5: + _context5.next = 0; + break; + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _waitUntilHasLeader.apply(this, arguments); +} +export function mustUseLocalState(_x9) { + return _mustUseLocalState.apply(this, arguments); +} +function _mustUseLocalState() { + _mustUseLocalState = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(instance) { + var leaderElector; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!instance.closed) { + _context6.next = 2; + break; + } + throw newRxError('SNH', { + args: { + instanceClosed: instance.closed, + databaseName: instance.databaseName, + collectionName: instance.collectionName + } + }); + case 2: + if (!instance.internals.localState) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", instance.internals.localState); + case 4: + leaderElector = ensureNotFalsy(instance.internals.leaderElector); + _context6.next = 7; + return waitUntilHasLeader(leaderElector); + case 7: + if (!instance.internals.localState) { + _context6.next = 9; + break; + } + return _context6.abrupt("return", instance.internals.localState); + case 9: + if (!(leaderElector.isLeader && !instance.internals.localState)) { + _context6.next = 14; + break; + } + // own is leader, use local instance + instance.internals.localState = createLokiLocalState({ + databaseInstanceToken: instance.databaseInstanceToken, + databaseName: instance.databaseName, + collectionName: instance.collectionName, + options: instance.options, + schema: instance.schema, + multiInstance: instance.internals.leaderElector ? true : false + }, instance.databaseSettings); + return _context6.abrupt("return", ensureNotFalsy(instance.internals.localState)); + case 14: + return _context6.abrupt("return", false); + case 15: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _mustUseLocalState.apply(this, arguments); +} +//# sourceMappingURL=lokijs-helper.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-lokijs/lokijs-helper.js.map b/dist/es/plugins/storage-lokijs/lokijs-helper.js.map new file mode 100644 index 00000000000..83dcc5e70aa --- /dev/null +++ b/dist/es/plugins/storage-lokijs/lokijs-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-helper.js","names":["createLokiLocalState","lokijs","add","unloadAdd","ensureNotFalsy","flatClone","promiseWait","randomCouchString","LokiSaveQueue","newRxError","objectPath","getBroadcastChannelReference","getLeaderElectorByBroadcastChannel","CHANGES_COLLECTION_SUFFIX","LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE","LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE","RX_STORAGE_NAME_LOKIJS","stripLokiKey","docData","$loki","cloned","$lastWriteAt","_meta","lwt","OPEN_LOKIJS_STORAGE_INSTANCES","Set","LOKIJS_COLLECTION_DEFAULT_OPTIONS","disableChangesApi","disableMeta","disableDeltaChangesApi","disableFreeze","cloneMethod","clone","transactional","autoupdate","LOKI_DATABASE_STATE_BY_NAME","Map","getLokiDatabase","databaseName","databaseSettings","databaseState","get","hasPersistence","adapter","persistenceMethod","useSettings","Object","assign","autoload","verbose","autosave","throttledSaves","database","lokiSaveQueue","loadDatabasePromise","Promise","res","rej","loadDatabase","recursiveWait","err","autoloadCallback","saveQueue","then","unloads","push","run","state","collections","set","closeLokiCollections","forEach","collection","collectionName","name","keys","length","u","remove","close","getLokiSortComparator","_schema","query","sort","sortOptions","fun","a","b","compareResult","find","sortPart","fieldName","direction","values","directionMultiplier","valueA","valueB","args","getLokiLeaderElector","databaseInstanceToken","broadcastChannelRefObject","broadcastChannel","elector","requestRemoteInstance","instance","operation","params","isRxStorageInstanceLoki","messageType","leaderElector","internals","waitUntilHasLeader","leaderDeadPromise","whenDeathListener","msg","context","action","retry","addEventListener","requestId","responsePromise","_rej","responseListener","type","response","isError","error","result","postMessage","race","firstResolved","removeEventListener","handleRemoteRequest","console","dir","hasLeader","applyOnce","mustUseLocalState","closed","instanceClosed","localState","isLeader","options","schema","multiInstance"],"sources":["../../../../src/plugins/storage-lokijs/lokijs-helper.ts"],"sourcesContent":["import { createLokiLocalState, RxStorageInstanceLoki } from './rx-storage-instance-loki';\nimport lokijs, { Collection } from 'lokijs';\nimport type {\n LokiDatabaseSettings,\n LokiDatabaseState,\n LokiLocalDatabaseState,\n LokiRemoteResponseBroadcastMessage,\n MangoQuery,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport {\n add as unloadAdd,\n AddReturn\n} from 'unload';\nimport { ensureNotFalsy, flatClone, promiseWait, randomCouchString } from '../utils';\nimport { LokiSaveQueue } from './loki-save-queue';\nimport type { DeterministicSortComparator } from 'event-reduce-js';\nimport { newRxError } from '../../rx-error';\nimport objectPath from 'object-path';\nimport {\n LeaderElector,\n OnMessageHandler\n} from 'broadcast-channel';\nimport { getBroadcastChannelReference } from '../../rx-storage-multiinstance';\nimport { getLeaderElectorByBroadcastChannel } from '../leader-election';\n\nexport const CHANGES_COLLECTION_SUFFIX = '-rxdb-changes';\nexport const LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request';\nexport const LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object';\nexport const RX_STORAGE_NAME_LOKIJS = 'lokijs';\n\n/**\n * Loki attaches a $loki property to all data\n * which must be removed before returning the data back to RxDB.\n */\nexport function stripLokiKey(docData: RxDocumentData & { $loki?: number; }): T {\n if (!docData.$loki) {\n return docData;\n }\n const cloned = flatClone(docData);\n\n /**\n * In RxDB version 12.0.0,\n * we introduced the _meta field that already contains the last write time.\n * To be backwards compatible, we have to move the $lastWriteAt to the _meta field.\n * TODO remove this in the next major version.\n */\n if ((cloned as any).$lastWriteAt) {\n cloned._meta = {\n lwt: (cloned as any).$lastWriteAt\n };\n delete (cloned as any).$lastWriteAt;\n }\n\n delete cloned.$loki;\n return cloned;\n}\n\n/**\n * Used to check in tests if all instances have been cleaned up.\n */\nexport const OPEN_LOKIJS_STORAGE_INSTANCES: Set> = new Set();\n\n\nexport const LOKIJS_COLLECTION_DEFAULT_OPTIONS: Partial> = {\n disableChangesApi: true,\n disableMeta: true,\n disableDeltaChangesApi: true,\n disableFreeze: true,\n // TODO use 'immutable' like WatermelonDB does it\n cloneMethod: 'shallow-assign',\n clone: false,\n transactional: false,\n autoupdate: false\n};\n\nconst LOKI_DATABASE_STATE_BY_NAME: Map> = new Map();\nexport function getLokiDatabase(\n databaseName: string,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n let databaseState: Promise | undefined = LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n /**\n * We assume that as soon as an adapter is passed,\n * the database has to be persistend.\n */\n const hasPersistence: boolean = !!databaseSettings.adapter;\n databaseState = (async () => {\n let persistenceMethod = hasPersistence ? 'adapter' : 'memory';\n if (databaseSettings.persistenceMethod) {\n persistenceMethod = databaseSettings.persistenceMethod;\n }\n const useSettings = Object.assign(\n // defaults\n {\n autoload: hasPersistence,\n persistenceMethod,\n verbose: true\n },\n databaseSettings,\n // overwrites\n {\n /**\n * RxDB uses its custom load and save handling\n * so we disable the LokiJS save/load handlers.\n */\n autoload: false,\n autosave: false,\n throttledSaves: false\n }\n );\n const database = new lokijs(\n databaseName + '.db',\n flatClone(useSettings)\n );\n const lokiSaveQueue = new LokiSaveQueue(\n database,\n useSettings\n );\n\n /**\n * Wait until all data is loaded from persistence adapter.\n * Wrap the loading into the saveQueue to ensure that when many\n * collections are created at the same time, the load-calls do not interfere\n * with each other and cause error logs.\n */\n if (hasPersistence) {\n const loadDatabasePromise = new Promise((res, rej) => {\n try {\n database.loadDatabase({\n recursiveWait: false\n }, (err) => {\n if (useSettings.autoloadCallback) {\n useSettings.autoloadCallback(err);\n }\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n } catch (err) {\n rej(err);\n }\n });\n lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(() => loadDatabasePromise);\n await loadDatabasePromise;\n }\n\n /**\n * Autosave database on process end\n */\n const unloads: AddReturn[] = [];\n if (hasPersistence) {\n unloads.push(\n unloadAdd(() => lokiSaveQueue.run())\n );\n }\n\n const state: LokiDatabaseState = {\n database,\n databaseSettings: useSettings,\n saveQueue: lokiSaveQueue,\n collections: {},\n unloads\n };\n\n return state;\n })();\n LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState);\n }\n return databaseState;\n}\n\nexport async function closeLokiCollections(\n databaseName: string,\n collections: Collection[]\n) {\n const databaseState = await LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n // already closed\n return;\n }\n await databaseState.saveQueue.run();\n collections.forEach(collection => {\n const collectionName = collection.name;\n delete databaseState.collections[collectionName];\n });\n if (Object.keys(databaseState.collections).length === 0) {\n // all collections closed -> also close database\n LOKI_DATABASE_STATE_BY_NAME.delete(databaseName);\n databaseState.unloads.forEach(u => u.remove());\n await new Promise((res, rej) => {\n databaseState.database.close(err => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n}\n\n/**\n * This function is at lokijs-helper\n * because we need it in multiple places.\n */\nexport function getLokiSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n const sortOptions: MangoQuerySortPart[] = query.sort;\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n let compareResult: number = 0; // 1 | -1\n sortOptions.find(sortPart => {\n const fieldName: string = Object.keys(sortPart)[0];\n const direction: MangoQuerySortDirection = Object.values(sortPart)[0];\n const directionMultiplier = direction === 'asc' ? 1 : -1;\n const valueA: any = objectPath.get(a as any, fieldName);\n const valueB: any = objectPath.get(b as any, fieldName);\n if (valueA === valueB) {\n return false;\n } else {\n if (valueA > valueB) {\n compareResult = 1 * directionMultiplier;\n return true;\n } else {\n compareResult = -1 * directionMultiplier;\n return true;\n }\n }\n });\n\n /**\n * Two different objects should never have the same sort position.\n * We ensure this by having the unique primaryKey in the sort params\n * which is added by RxDB if not existing yet.\n */\n if (!compareResult) {\n throw newRxError('SNH', { args: { query, a, b } });\n }\n\n return compareResult as any;\n };\n return fun;\n}\n\nexport function getLokiLeaderElector(\n databaseInstanceToken: string,\n broadcastChannelRefObject: any,\n databaseName: string\n): LeaderElector {\n const broadcastChannel = getBroadcastChannelReference(\n databaseInstanceToken,\n databaseName,\n broadcastChannelRefObject\n );\n const elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n return elector;\n}\n\n/**\n * For multi-instance usage, we send requests to the RxStorage\n * to the current leading instance over the BroadcastChannel.\n */\nexport async function requestRemoteInstance(\n instance: RxStorageInstanceLoki,\n operation: string,\n params: any[]\n): Promise {\n const isRxStorageInstanceLoki = typeof (instance as any).query === 'function';\n const messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE;\n\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n const broadcastChannel = leaderElector.broadcastChannel;\n\n type WinningPromise = {\n retry: boolean;\n result?: any;\n error?: any;\n };\n\n let whenDeathListener: OnMessageHandler;\n const leaderDeadPromise = new Promise(res => {\n whenDeathListener = (msg: any) => {\n if (msg.context === 'leader' && msg.action === 'death') {\n res({\n retry: true\n });\n }\n };\n broadcastChannel.addEventListener('internal', whenDeathListener);\n });\n const requestId = randomCouchString(12);\n let responseListener: OnMessageHandler;\n const responsePromise = new Promise((res, _rej) => {\n responseListener = (msg: any) => {\n if (\n msg.type === messageType &&\n msg.response === true &&\n msg.requestId === requestId\n ) {\n if (msg.isError) {\n res({\n retry: false,\n error: msg.result\n });\n } else {\n res({\n retry: false,\n result: msg.result\n });\n }\n }\n };\n broadcastChannel.addEventListener('message', responseListener);\n });\n\n // send out the request to the other instance\n broadcastChannel.postMessage({\n response: false,\n type: messageType,\n operation,\n params,\n requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n });\n\n\n return Promise.race([\n leaderDeadPromise,\n responsePromise\n ]).then(firstResolved => {\n\n // clean up listeners\n broadcastChannel.removeEventListener('message', responseListener);\n broadcastChannel.removeEventListener('internal', whenDeathListener);\n\n if (firstResolved.retry) {\n /**\n * The leader died while a remote request was running\n * we re-run the whole operation.\n * We cannot just re-run requestRemoteInstance()\n * because the current instance might be the new leader now\n * and then we have to use the local state instead of requesting the remote.\n */\n return (instance as any)[operation](...params);\n } else {\n if (firstResolved.error) {\n throw firstResolved.error;\n } else {\n return firstResolved.result;\n }\n }\n });\n}\n\n/**\n * Handles a request that came from a remote instance via requestRemoteInstance()\n * Runs the requested operation over the local db instance and sends back the result.\n */\nexport async function handleRemoteRequest(\n instance: RxStorageInstanceLoki,\n msg: any\n) {\n if (\n msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE &&\n msg.requestId &&\n msg.databaseName === instance.databaseName &&\n msg.collectionName === instance.collectionName &&\n !msg.response\n ) {\n const operation = (msg as any).operation;\n const params = (msg as any).params;\n let result: any;\n let isError = false;\n try {\n result = await (instance as any)[operation](...params);\n } catch (err) {\n console.dir(err);\n isError = true;\n result = err;\n }\n const response: LokiRemoteResponseBroadcastMessage = {\n response: true,\n requestId: msg.requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n result,\n isError,\n type: msg.type\n };\n ensureNotFalsy(instance.internals.leaderElector).broadcastChannel.postMessage(response);\n }\n}\n\n\nexport async function waitUntilHasLeader(leaderElector: LeaderElector) {\n while (\n !leaderElector.hasLeader\n ) {\n await leaderElector.applyOnce();\n await promiseWait(0);\n }\n}\n\n/**\n * If the local state must be used, that one is returned.\n * Returns false if a remote instance must be used.\n */\nexport async function mustUseLocalState(\n instance: RxStorageInstanceLoki\n): Promise {\n if (instance.closed) {\n /**\n * If this happens, it means that RxDB made a call to an already closed storage instance.\n * This must never happen because when RxDB closes a collection or database,\n * all tasks must be cleared so that no more calls are made the the storage.\n */\n throw newRxError('SNH', {\n args: {\n instanceClosed: instance.closed,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n }\n });\n }\n\n\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n\n /**\n * It might already have a localState after the applying\n * because another subtask also called mustUSeLocalState()\n */\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n\n if (\n leaderElector.isLeader &&\n !instance.internals.localState\n ) {\n // own is leader, use local instance\n instance.internals.localState = createLokiLocalState({\n databaseInstanceToken: instance.databaseInstanceToken,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n options: instance.options,\n schema: (instance as RxStorageInstanceLoki).schema,\n multiInstance: instance.internals.leaderElector ? true : false\n }, instance.databaseSettings);\n return ensureNotFalsy(instance.internals.localState);\n } else {\n // other is leader, send message to remote leading instance\n return false;\n }\n}\n"],"mappings":";;AAAA,SAASA,oBAAoB,QAA+B,4BAA4B;AACxF,OAAOC,MAAM,MAAsB,QAAQ;AAY3C,SACIC,GAAG,IAAIC,SAAS,QAEb,QAAQ;AACf,SAASC,cAAc,EAAEC,SAAS,EAAEC,WAAW,EAAEC,iBAAiB,QAAQ,UAAU;AACpF,SAASC,aAAa,QAAQ,mBAAmB;AAEjD,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,OAAO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age-lokijs/rx-storage-instance-loki.js new file mode 100644 index 00000000000..dfc6ff9cf6f --- /dev/null +++ b/dist/es/plugins/storage-lokijs/rx-storage-instance-loki.js @@ -0,0 +1,557 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { Subject } from 'rxjs'; +import { flatClone, now, ensureNotFalsy, isMaybeReadonlyArray, getFromMapOrThrow, getSortDocumentsByLastWriteTimeComparator, RX_META_LWT_MINIMUM, lastOfArray } from '../utils'; +import { newRxError } from '../../rx-error'; +import { closeLokiCollections, getLokiDatabase, OPEN_LOKIJS_STORAGE_INSTANCES, LOKIJS_COLLECTION_DEFAULT_OPTIONS, stripLokiKey, getLokiSortComparator, getLokiLeaderElector, requestRemoteInstance, mustUseLocalState, handleRemoteRequest, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper'; +import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; +import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; +import { addRxStorageMultiInstanceSupport, removeBroadcastChannelReference } from '../../rx-storage-multiinstance'; +var instanceId = now(); +export var RxStorageInstanceLoki = /*#__PURE__*/function () { + function RxStorageInstanceLoki(databaseInstanceToken, storage, databaseName, collectionName, schema, internals, options, databaseSettings) { + var _this = this; + this.changes$ = new Subject(); + this.instanceId = instanceId++; + this.closed = false; + this.databaseInstanceToken = databaseInstanceToken; + this.storage = storage; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + this.databaseSettings = databaseSettings; + this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey); + OPEN_LOKIJS_STORAGE_INSTANCES.add(this); + if (this.internals.leaderElector) { + /** + * To run handleRemoteRequest(), + * the instance will call its own methods. + * But these methods could have already been swapped out by a RxStorageWrapper + * so we must store the original methods here and use them instead. + */ + var copiedSelf = { + bulkWrite: this.bulkWrite.bind(this), + changeStream: this.changeStream.bind(this), + cleanup: this.cleanup.bind(this), + close: this.close.bind(this), + query: this.query.bind(this), + count: this.count.bind(this), + findDocumentsById: this.findDocumentsById.bind(this), + collectionName: this.collectionName, + databaseName: this.databaseName, + conflictResultionTasks: this.conflictResultionTasks.bind(this), + getAttachmentData: this.getAttachmentData.bind(this), + getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this), + internals: this.internals, + options: this.options, + remove: this.remove.bind(this), + resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this), + schema: this.schema + }; + this.internals.leaderElector.awaitLeadership().then(function () { + // this instance is leader now, so it has to reply to queries from other instances + ensureNotFalsy(_this.internals.leaderElector).broadcastChannel.addEventListener('message', function (msg) { + return handleRemoteRequest(copiedSelf, msg); + }); + }); + } + } + var _proto = RxStorageInstanceLoki.prototype; + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(documentWrites, context) { + var _this2 = this; + var localState, ret, docsInDb, docsInDbWithLokiKey, categorized, lastState; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(documentWrites.length === 0)) { + _context.next = 2; + break; + } + throw newRxError('P2', { + args: { + documentWrites: documentWrites + } + }); + case 2: + _context.next = 4; + return mustUseLocalState(this); + case 4: + localState = _context.sent; + if (localState) { + _context.next = 7; + break; + } + return _context.abrupt("return", requestRemoteInstance(this, 'bulkWrite', [documentWrites])); + case 7: + ret = { + success: {}, + error: {} + }; + docsInDb = new Map(); + docsInDbWithLokiKey = new Map(); + documentWrites.forEach(function (writeRow) { + var id = writeRow.document[_this2.primaryPath]; + var documentInDb = localState.collection.by(_this2.primaryPath, id); + if (documentInDb) { + docsInDbWithLokiKey.set(id, documentInDb); + docsInDb.set(id, stripLokiKey(documentInDb)); + } + }); + categorized = categorizeBulkWriteRows(this, this.primaryPath, docsInDb, documentWrites, context); + ret.error = categorized.errors; + categorized.bulkInsertDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this2.primaryPath]; + localState.collection.insert(flatClone(writeRow.document)); + ret.success[docId] = writeRow.document; + }); + categorized.bulkUpdateDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this2.primaryPath]; + var documentInDbWithLokiKey = getFromMapOrThrow(docsInDbWithLokiKey, docId); + var writeDoc = Object.assign({}, writeRow.document, { + $loki: documentInDbWithLokiKey.$loki + }); + localState.collection.update(writeDoc); + ret.success[docId] = writeRow.document; + }); + localState.databaseState.saveQueue.addWrite(); + if (categorized.eventBulk.events.length > 0) { + lastState = getNewestOfDocumentStates(this.primaryPath, Object.values(ret.success)); + categorized.eventBulk.checkpoint = { + id: lastState[this.primaryPath], + lwt: lastState._meta.lwt + }; + this.changes$.next(categorized.eventBulk); + } + return _context.abrupt("return", ret); + case 18: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function bulkWrite(_x, _x2) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(); + _proto.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(ids, deleted) { + var _this3 = this; + var localState, ret; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return mustUseLocalState(this); + case 2: + localState = _context2.sent; + if (localState) { + _context2.next = 5; + break; + } + return _context2.abrupt("return", requestRemoteInstance(this, 'findDocumentsById', [ids, deleted])); + case 5: + ret = {}; + ids.forEach(function (id) { + var documentInDb = localState.collection.by(_this3.primaryPath, id); + if (documentInDb && (!documentInDb._deleted || deleted)) { + ret[id] = stripLokiKey(documentInDb); + } + }); + return _context2.abrupt("return", ret); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function findDocumentsById(_x3, _x4) { + return _findDocumentsById.apply(this, arguments); + } + return findDocumentsById; + }(); + _proto.query = /*#__PURE__*/function () { + var _query = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(preparedQuery) { + var localState, query, foundDocuments; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return mustUseLocalState(this); + case 2: + localState = _context3.sent; + if (localState) { + _context3.next = 5; + break; + } + return _context3.abrupt("return", requestRemoteInstance(this, 'query', [preparedQuery])); + case 5: + query = localState.collection.chain().find(preparedQuery.selector); + if (preparedQuery.sort) { + query = query.sort(getLokiSortComparator(this.schema, preparedQuery)); + } + + /** + * Offset must be used before limit in LokiJS + * @link https://github.com/techfort/LokiJS/issues/570 + */ + if (preparedQuery.skip) { + query = query.offset(preparedQuery.skip); + } + if (preparedQuery.limit) { + query = query.limit(preparedQuery.limit); + } + foundDocuments = query.data().map(function (lokiDoc) { + return stripLokiKey(lokiDoc); + }); + return _context3.abrupt("return", { + documents: foundDocuments + }); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function query(_x5) { + return _query.apply(this, arguments); + } + return query; + }(); + _proto.count = /*#__PURE__*/function () { + var _count = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(preparedQuery) { + var result; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return this.query(preparedQuery); + case 2: + result = _context4.sent; + return _context4.abrupt("return", { + count: result.documents.length, + mode: 'fast' + }); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function count(_x6) { + return _count.apply(this, arguments); + } + return count; + }(); + _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { + throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.'); + }; + _proto.getChangedDocumentsSince = /*#__PURE__*/function () { + var _getChangedDocumentsSince = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(limit, checkpoint) { + var localState, sinceLwt, query, changedDocs, first, lastDoc; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return mustUseLocalState(this); + case 2: + localState = _context5.sent; + if (localState) { + _context5.next = 5; + break; + } + return _context5.abrupt("return", requestRemoteInstance(this, 'getChangedDocumentsSince', [limit, checkpoint])); + case 5: + sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM; + query = localState.collection.chain().find({ + '_meta.lwt': { + $gte: sinceLwt + } + }).sort(getSortDocumentsByLastWriteTimeComparator(this.primaryPath)); + changedDocs = query.data(); + first = changedDocs[0]; + if (checkpoint && first && first[this.primaryPath] === checkpoint.id && first._meta.lwt === checkpoint.lwt) { + changedDocs.shift(); + } + changedDocs = changedDocs.slice(0, limit); + lastDoc = lastOfArray(changedDocs); + return _context5.abrupt("return", { + documents: changedDocs.map(function (docData) { + return stripLokiKey(docData); + }), + checkpoint: lastDoc ? { + id: lastDoc[this.primaryPath], + lwt: lastDoc._meta.lwt + } : checkpoint ? checkpoint : { + id: '', + lwt: 0 + } + }); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getChangedDocumentsSince(_x7, _x8) { + return _getChangedDocumentsSince.apply(this, arguments); + } + return getChangedDocumentsSince; + }(); + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + _proto.cleanup = /*#__PURE__*/function () { + var _cleanup = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(minimumDeletedTime) { + var localState, deleteAmountPerRun, maxDeletionTime, query, foundDocuments; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return mustUseLocalState(this); + case 2: + localState = _context6.sent; + if (localState) { + _context6.next = 5; + break; + } + return _context6.abrupt("return", requestRemoteInstance(this, 'cleanup', [minimumDeletedTime])); + case 5: + deleteAmountPerRun = 10; + maxDeletionTime = now() - minimumDeletedTime; + query = localState.collection.chain().find({ + _deleted: true, + '_meta.lwt': { + $lt: maxDeletionTime + } + }).limit(deleteAmountPerRun); + foundDocuments = query.data(); + if (foundDocuments.length > 0) { + localState.collection.remove(foundDocuments); + localState.databaseState.saveQueue.addWrite(); + } + return _context6.abrupt("return", foundDocuments.length !== deleteAmountPerRun); + case 11: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function cleanup(_x9) { + return _cleanup.apply(this, arguments); + } + return cleanup; + }(); + _proto.close = /*#__PURE__*/function () { + var _close = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { + var localState, dbState; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + if (!this.closed) { + _context7.next = 2; + break; + } + return _context7.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.changes$.complete(); + OPEN_LOKIJS_STORAGE_INSTANCES["delete"](this); + if (!this.internals.localState) { + _context7.next = 16; + break; + } + _context7.next = 8; + return this.internals.localState; + case 8: + localState = _context7.sent; + _context7.next = 11; + return getLokiDatabase(this.databaseName, this.databaseSettings); + case 11: + dbState = _context7.sent; + _context7.next = 14; + return dbState.saveQueue.run(); + case 14: + _context7.next = 16; + return closeLokiCollections(this.databaseName, [localState.collection]); + case 16: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function close() { + return _close.apply(this, arguments); + } + return close; + }(); + _proto.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() { + var localState; + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return mustUseLocalState(this); + case 2: + localState = _context8.sent; + if (localState) { + _context8.next = 5; + break; + } + return _context8.abrupt("return", requestRemoteInstance(this, 'remove', [])); + case 5: + localState.databaseState.database.removeCollection(localState.collection.name); + _context8.next = 8; + return localState.databaseState.saveQueue.run(); + case 8: + return _context8.abrupt("return", this.close()); + case 9: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function remove() { + return _remove.apply(this, arguments); + } + return remove; + }(); + _proto.conflictResultionTasks = function conflictResultionTasks() { + return new Subject(); + }; + _proto.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(_taskSolution) { + return _regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + function resolveConflictResultionTask(_x10) { + return _resolveConflictResultionTask.apply(this, arguments); + } + return resolveConflictResultionTask; + }(); + return RxStorageInstanceLoki; +}(); +export function createLokiLocalState(_x11, _x12) { + return _createLokiLocalState.apply(this, arguments); +} +function _createLokiLocalState() { + _createLokiLocalState = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10(params, databaseSettings) { + var databaseState, indices, primaryKey, lokiCollectionName, collectionOptions, collection, ret; + return _regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + if (!params.options) { + params.options = {}; + } + _context10.next = 3; + return getLokiDatabase(params.databaseName, databaseSettings); + case 3: + databaseState = _context10.sent; + /** + * Construct loki indexes from RxJsonSchema indexes. + * TODO what about compound indexes? Are they possible in lokijs? + */ + indices = []; + if (params.schema.indexes) { + params.schema.indexes.forEach(function (idx) { + if (!isMaybeReadonlyArray(idx)) { + indices.push(idx); + } + }); + } + /** + * LokiJS has no concept of custom primary key, they use a number-id that is generated. + * To be able to query fast by primary key, we always add an index to the primary. + */ + primaryKey = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey); + indices.push(primaryKey); + lokiCollectionName = params.collectionName + '-' + params.schema.version; + collectionOptions = Object.assign({}, lokiCollectionName, { + indices: indices, + unique: [primaryKey] + }, LOKIJS_COLLECTION_DEFAULT_OPTIONS); + collection = databaseState.database.addCollection(lokiCollectionName, collectionOptions); + databaseState.collections[params.collectionName] = collection; + ret = { + databaseState: databaseState, + collection: collection + }; + return _context10.abrupt("return", ret); + case 14: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + return _createLokiLocalState.apply(this, arguments); +} +export function createLokiStorageInstance(_x13, _x14, _x15) { + return _createLokiStorageInstance.apply(this, arguments); +} +function _createLokiStorageInstance() { + _createLokiStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(storage, params, databaseSettings) { + var internals, broadcastChannelRefObject, leaderElector, instance, closeBefore, removeBefore; + return _regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + internals = {}; + broadcastChannelRefObject = {}; + if (!params.multiInstance) { + _context11.next = 7; + break; + } + leaderElector = getLokiLeaderElector(params.databaseInstanceToken, broadcastChannelRefObject, params.databaseName); + internals.leaderElector = leaderElector; + _context11.next = 10; + break; + case 7: + // optimisation shortcut, directly create db is non multi instance. + internals.localState = createLokiLocalState(params, databaseSettings); + _context11.next = 10; + return internals.localState; + case 10: + instance = new RxStorageInstanceLoki(params.databaseInstanceToken, storage, params.databaseName, params.collectionName, params.schema, internals, params.options, databaseSettings); + addRxStorageMultiInstanceSupport(RX_STORAGE_NAME_LOKIJS, params, instance, internals.leaderElector ? internals.leaderElector.broadcastChannel : undefined); + if (params.multiInstance) { + /** + * Clean up the broadcast-channel reference on close() + */ + closeBefore = instance.close.bind(instance); + instance.close = function () { + removeBroadcastChannelReference(params.databaseInstanceToken, broadcastChannelRefObject); + return closeBefore(); + }; + removeBefore = instance.remove.bind(instance); + instance.remove = function () { + removeBroadcastChannelReference(params.databaseInstanceToken, broadcastChannelRefObject); + return removeBefore(); + }; + + /** + * Directly create the localState when/if the db becomes leader. + */ + ensureNotFalsy(internals.leaderElector).awaitLeadership().then(function () { + if (!instance.closed) { + mustUseLocalState(instance); + } + }); + } + return _context11.abrupt("return", instance); + case 14: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + return _createLokiStorageInstance.apply(this, arguments); +} +//# sourceMappingURL=rx-storage-instance-loki.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-lokijs/rx-storage-instance-loki.js.map b/dist/es/plugins/storage-lokijs/rx-storage-instance-loki.js.map new file mode 100644 index 00000000000..632434df55c --- /dev/null +++ b/dist/es/plugins/storage-lokijs/rx-storage-instance-loki.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-loki.js","names":["Subject","flatClone","now","ensureNotFalsy","isMaybeReadonlyArray","getFromMapOrThrow","getSortDocumentsByLastWriteTimeComparator","RX_META_LWT_MINIMUM","lastOfArray","newRxError","closeLokiCollections","getLokiDatabase","OPEN_LOKIJS_STORAGE_INSTANCES","LOKIJS_COLLECTION_DEFAULT_OPTIONS","stripLokiKey","getLokiSortComparator","getLokiLeaderElector","requestRemoteInstance","mustUseLocalState","handleRemoteRequest","RX_STORAGE_NAME_LOKIJS","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","addRxStorageMultiInstanceSupport","removeBroadcastChannelReference","instanceId","RxStorageInstanceLoki","databaseInstanceToken","storage","databaseName","collectionName","schema","internals","options","databaseSettings","changes$","closed","primaryPath","primaryKey","add","leaderElector","copiedSelf","bulkWrite","bind","changeStream","cleanup","close","query","count","findDocumentsById","conflictResultionTasks","getAttachmentData","getChangedDocumentsSince","remove","resolveConflictResultionTask","awaitLeadership","then","broadcastChannel","addEventListener","msg","documentWrites","context","length","args","localState","ret","success","error","docsInDb","Map","docsInDbWithLokiKey","forEach","writeRow","id","document","documentInDb","collection","by","set","categorized","errors","bulkInsertDocs","docId","insert","bulkUpdateDocs","documentInDbWithLokiKey","writeDoc","Object","assign","$loki","update","databaseState","saveQueue","addWrite","eventBulk","events","lastState","values","checkpoint","lwt","_meta","next","ids","deleted","_deleted","preparedQuery","chain","find","selector","sort","skip","offset","limit","foundDocuments","data","map","lokiDoc","documents","result","mode","_documentId","_attachmentId","Error","sinceLwt","$gte","changedDocs","first","shift","slice","lastDoc","docData","asObservable","minimumDeletedTime","deleteAmountPerRun","maxDeletionTime","$lt","Promise","reject","complete","dbState","run","database","removeCollection","name","_taskSolution","createLokiLocalState","params","indices","indexes","idx","push","lokiCollectionName","version","collectionOptions","unique","addCollection","collections","createLokiStorageInstance","broadcastChannelRefObject","multiInstance","instance","undefined","closeBefore","removeBefore"],"sources":["../../../../src/plugins/storage-lokijs/rx-storage-instance-loki.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n flatClone,\n now,\n ensureNotFalsy,\n isMaybeReadonlyArray,\n getFromMapOrThrow,\n getSortDocumentsByLastWriteTimeComparator,\n RX_META_LWT_MINIMUM,\n lastOfArray\n} from '../utils';\nimport { newRxError } from '../../rx-error';\nimport type {\n RxStorageInstance,\n LokiSettings,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n MangoQuery,\n LokiStorageInternals,\n RxStorageInstanceCreationParams,\n LokiDatabaseSettings,\n LokiLocalDatabaseState,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n DeepReadonly,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n RxStorageCountResult\n} from '../../types';\nimport {\n closeLokiCollections,\n getLokiDatabase,\n OPEN_LOKIJS_STORAGE_INSTANCES,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS,\n stripLokiKey,\n getLokiSortComparator,\n getLokiLeaderElector,\n requestRemoteInstance,\n mustUseLocalState,\n handleRemoteRequest,\n RX_STORAGE_NAME_LOKIJS\n} from './lokijs-helper';\nimport type {\n Collection\n} from 'lokijs';\nimport type { RxStorageLoki } from './rx-storage-lokijs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport, removeBroadcastChannelReference } from '../../rx-storage-multiinstance';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceLoki implements RxStorageInstance<\n RxDocType,\n LokiStorageInternals,\n LokiSettings,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n\n public closed = false;\n\n constructor(\n public readonly databaseInstanceToken: string,\n public readonly storage: RxStorageLoki,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: LokiStorageInternals,\n public readonly options: Readonly,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n OPEN_LOKIJS_STORAGE_INSTANCES.add(this);\n if (this.internals.leaderElector) {\n\n\n /**\n * To run handleRemoteRequest(),\n * the instance will call its own methods.\n * But these methods could have already been swapped out by a RxStorageWrapper\n * so we must store the original methods here and use them instead.\n */\n const copiedSelf: RxStorageInstance = {\n bulkWrite: this.bulkWrite.bind(this),\n changeStream: this.changeStream.bind(this),\n cleanup: this.cleanup.bind(this),\n close: this.close.bind(this),\n query: this.query.bind(this),\n count: this.count.bind(this),\n findDocumentsById: this.findDocumentsById.bind(this),\n collectionName: this.collectionName,\n databaseName: this.databaseName,\n conflictResultionTasks: this.conflictResultionTasks.bind(this),\n getAttachmentData: this.getAttachmentData.bind(this),\n getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this),\n internals: this.internals,\n options: this.options,\n remove: this.remove.bind(this),\n resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this),\n schema: this.schema\n };\n\n this.internals.leaderElector.awaitLeadership().then(() => {\n // this instance is leader now, so it has to reply to queries from other instances\n ensureNotFalsy(this.internals.leaderElector).broadcastChannel\n .addEventListener('message', (msg) => handleRemoteRequest(copiedSelf as any, msg));\n });\n }\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n if (documentWrites.length === 0) {\n throw newRxError('P2', {\n args: {\n documentWrites\n }\n });\n }\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'bulkWrite', [documentWrites]);\n }\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const docsInDb: Map[StringKeys], RxDocumentData> = new Map();\n const docsInDbWithLokiKey: Map<\n RxDocumentData[StringKeys],\n RxDocumentData & { $loki: number; }\n > = new Map();\n documentWrites.forEach(writeRow => {\n const id = writeRow.document[this.primaryPath];\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (documentInDb) {\n docsInDbWithLokiKey.set(id as any, documentInDb);\n docsInDb.set(id as any, stripLokiKey(documentInDb));\n }\n });\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDb,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n localState.collection.insert(flatClone(writeRow.document));\n ret.success[docId as any] = writeRow.document;\n });\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n const documentInDbWithLokiKey = getFromMapOrThrow(docsInDbWithLokiKey, docId as any);\n const writeDoc: any = Object.assign(\n {},\n writeRow.document,\n {\n $loki: documentInDbWithLokiKey.$loki\n }\n );\n localState.collection.update(writeDoc);\n ret.success[docId as any] = writeRow.document;\n });\n localState.databaseState.saveQueue.addWrite();\n\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(categorized.eventBulk);\n }\n\n return ret;\n }\n async findDocumentsById(ids: string[], deleted: boolean): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'findDocumentsById', [ids, deleted]);\n }\n\n const ret: RxDocumentDataById = {};\n ids.forEach(id => {\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = stripLokiKey(documentInDb);\n }\n });\n return ret;\n }\n async query(preparedQuery: MangoQuery): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'query', [preparedQuery]);\n }\n\n let query = localState.collection\n .chain()\n .find(preparedQuery.selector);\n\n if (preparedQuery.sort) {\n query = query.sort(getLokiSortComparator(this.schema, preparedQuery));\n }\n\n /**\n * Offset must be used before limit in LokiJS\n * @link https://github.com/techfort/LokiJS/issues/570\n */\n if (preparedQuery.skip) {\n query = query.offset(preparedQuery.skip);\n }\n\n if (preparedQuery.limit) {\n query = query.limit(preparedQuery.limit);\n }\n\n const foundDocuments = query.data().map(lokiDoc => stripLokiKey(lokiDoc));\n return {\n documents: foundDocuments\n };\n }\n async count(\n preparedQuery: MangoQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.');\n }\n\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint | null\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'getChangedDocumentsSince', [limit, checkpoint]);\n }\n\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const query = localState.collection\n .chain()\n .find({\n '_meta.lwt': {\n $gte: sinceLwt\n }\n })\n .sort(getSortDocumentsByLastWriteTimeComparator(this.primaryPath as any));\n let changedDocs = query.data();\n\n const first = changedDocs[0];\n if (\n checkpoint &&\n first &&\n first[this.primaryPath] === checkpoint.id &&\n first._meta.lwt === checkpoint.lwt\n ) {\n changedDocs.shift();\n }\n\n changedDocs = changedDocs.slice(0, limit);\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs.map(docData => stripLokiKey(docData)),\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath],\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'cleanup', [minimumDeletedTime]);\n }\n\n const deleteAmountPerRun = 10;\n const maxDeletionTime = now() - minimumDeletedTime;\n const query = localState.collection\n .chain()\n .find({\n _deleted: true,\n '_meta.lwt': {\n $lt: maxDeletionTime\n }\n }).limit(deleteAmountPerRun);\n const foundDocuments = query.data();\n if (foundDocuments.length > 0) {\n localState.collection.remove(foundDocuments);\n localState.databaseState.saveQueue.addWrite();\n }\n\n return foundDocuments.length !== deleteAmountPerRun;\n }\n\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n OPEN_LOKIJS_STORAGE_INSTANCES.delete(this);\n\n if (this.internals.localState) {\n const localState = await this.internals.localState;\n const dbState = await getLokiDatabase(\n this.databaseName,\n this.databaseSettings\n );\n await dbState.saveQueue.run();\n await closeLokiCollections(\n this.databaseName,\n [\n localState.collection\n ]\n );\n }\n }\n async remove(): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'remove', []);\n }\n localState.databaseState.database.removeCollection(localState.collection.name);\n await localState.databaseState.saveQueue.run();\n return this.close();\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\nexport async function createLokiLocalState(\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n if (!params.options) {\n params.options = {};\n }\n\n const databaseState = await getLokiDatabase(\n params.databaseName,\n databaseSettings\n );\n\n /**\n * Construct loki indexes from RxJsonSchema indexes.\n * TODO what about compound indexes? Are they possible in lokijs?\n */\n const indices: string[] = [];\n if (params.schema.indexes) {\n params.schema.indexes.forEach(idx => {\n if (!isMaybeReadonlyArray(idx)) {\n indices.push(idx);\n }\n });\n }\n /**\n * LokiJS has no concept of custom primary key, they use a number-id that is generated.\n * To be able to query fast by primary key, we always add an index to the primary.\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n indices.push(primaryKey as string);\n\n const lokiCollectionName = params.collectionName + '-' + params.schema.version;\n const collectionOptions: Partial>> = Object.assign(\n {},\n lokiCollectionName,\n {\n indices: indices as string[],\n unique: [primaryKey]\n } as any,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS\n );\n\n const collection: Collection = databaseState.database.addCollection(\n lokiCollectionName,\n collectionOptions as any\n );\n databaseState.collections[params.collectionName] = collection;\n const ret: LokiLocalDatabaseState = {\n databaseState,\n collection\n };\n\n return ret;\n}\n\n\nexport async function createLokiStorageInstance(\n storage: RxStorageLoki,\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise> {\n const internals: LokiStorageInternals = {};\n\n const broadcastChannelRefObject: DeepReadonly = {};\n\n\n if (params.multiInstance) {\n const leaderElector = getLokiLeaderElector(\n params.databaseInstanceToken,\n broadcastChannelRefObject,\n params.databaseName\n );\n internals.leaderElector = leaderElector;\n } else {\n // optimisation shortcut, directly create db is non multi instance.\n internals.localState = createLokiLocalState(params, databaseSettings);\n await internals.localState;\n }\n\n const instance = new RxStorageInstanceLoki(\n params.databaseInstanceToken,\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n databaseSettings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_LOKIJS,\n params,\n instance,\n internals.leaderElector ? internals.leaderElector.broadcastChannel : undefined\n );\n\n if (params.multiInstance) {\n /**\n * Clean up the broadcast-channel reference on close()\n */\n const closeBefore = instance.close.bind(instance);\n instance.close = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return closeBefore();\n };\n const removeBefore = instance.remove.bind(instance);\n instance.remove = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return removeBefore();\n };\n\n /**\n * Directly create the localState when/if the db becomes leader.\n */\n ensureNotFalsy(internals.leaderElector)\n .awaitLeadership()\n .then(() => {\n if (!instance.closed) {\n mustUseLocalState(instance);\n }\n });\n }\n\n\n return instance;\n}\n"],"mappings":";;AAAA,SACIA,OAAO,QAEJ,MAAM;AACb,SACIC,SAAS,EACTC,GAAG,EACHC,cAAc,EACdC,oBAAoB,EACpBC,iBAAiB,EACjBC,yCAAyC,EACzCC,mBAAmB,EACnBC,WAAW,QACR,UAAU;AACjB,SAASC,UAAU,QAAQ,gBAAgB;AAwB3C,SACIC,oBAAoB,EACpBC,eAAe,EACfC,6BAA6B,EAC7BC,iCAAiC,EACjCC,YAAY,EACZC,qBAAqB,EACrBC,oBAAoB,EACpBC,qBAAqB,EACrBC,iBAAiB,EACjBC,mBAAmB,EACnBC,sBAAsB,QACnB,iBAAiB;AAKxB,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SAASC,uBAAuB,EAAEC,yBAAyB,QAAQ,yBAAyB;AAC5F,SAASC,gCAAgC,EAAEC,+BAA+B,QAAQ,gCAAgC;AAElH,IAAIC,UAAU,GAAGxB,GAAG,EAAE;AAEtB,WAAayB,qBAAqB;EAa9B,+BACoBC,qBAA6B,EAC7BC,OAAsB,EACtBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAA+B,EAC/BC,OAA+B,EAC/BC,gBAAsC,EACxD;IAAA;IAAA,KAdMC,QAAQ,GAAoG,IAAIpC,OAAO,EAAE;IAAA,KACjH0B,UAAU,GAAGA,UAAU,EAAE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EAAE;YACzB,CAAC;;YAED;AACR;AACA;YACQjK,cAAc,CAAC8B,SAAS,CAACQ,aAAa,CAAC,CAClCe,eAAe,EAAE,CACjBC,IAAI,CAAC,YAAM;cACR,IAAI,CAACwG,QAAQ,CAAC5H,MAAM,EAAE;gBAClBnB,iBAAiB,CAAC+I,QAAQ,CAAC;cAC/B;YACJ,CAAC,CAAC;UACV;UAAC,mCAGMA,QAAQ;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAClB;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/lokijs/rx-storage-lokijs.js b/dist/es/plugins/storage-lokijs/rx-storage-lokijs.js similarity index 98% rename from dist/es/plugins/lokijs/rx-storage-lokijs.js rename to dist/es/plugins/storage-lokijs/rx-storage-lokijs.js index f138909d162..36184bf0e6e 100644 --- a/dist/es/plugins/lokijs/rx-storage-lokijs.js +++ b/dist/es/plugins/storage-lokijs/rx-storage-lokijs.js @@ -1,5 +1,5 @@ import lokijs from 'lokijs'; -import { ensureNotFalsy, flatClone } from '../../util'; +import { ensureNotFalsy, flatClone } from '../utils'; import { createLokiStorageInstance } from './rx-storage-instance-loki'; import { getLokiSortComparator, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper'; import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper'; diff --git a/dist/es/plugins/storage-lokijs/rx-storage-lokijs.js.map b/dist/es/plugins/storage-lokijs/rx-storage-lokijs.js.map new file mode 100644 index 00000000000..3932699847f --- /dev/null +++ b/dist/es/plugins/storage-lokijs/rx-storage-lokijs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-lokijs.js","names":["lokijs","ensureNotFalsy","flatClone","createLokiStorageInstance","getLokiSortComparator","RX_STORAGE_NAME_LOKIJS","ensureRxStorageInstanceParamsAreCorrect","DEFAULT_CHECKPOINT_SCHEMA","RxStorageLokiStatics","prepareQuery","_schema","mutateableQuery","Object","keys","selector","length","$and","_deleted","getSortComparator","schema","query","getQueryMatcher","fun","doc","docWithResetDeleted","fakeCollection","data","binaryIndices","setPrototypeOf","Collection","prototype","fakeResultSet","collection","Resultset","find","ret","filteredrows","checkpointSchema","RxStorageLoki","databaseSettings","name","statics","leaderElectorByLokiDbName","Map","createStorageInstance","params","getRxStorageLoki","storage"],"sources":["../../../../src/plugins/storage-lokijs/rx-storage-lokijs.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport lokijs from 'lokijs';\nimport type {\n FilledMangoQuery,\n LokiDatabaseSettings,\n LokiSettings,\n LokiStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageStatics\n} from '../../types';\nimport {\n ensureNotFalsy,\n flatClone\n} from '../utils';\nimport {\n createLokiStorageInstance,\n RxStorageInstanceLoki\n} from './rx-storage-instance-loki';\nimport { getLokiSortComparator, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper';\nimport type { LeaderElector } from 'broadcast-channel';\n\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\n\nexport const RxStorageLokiStatics: RxStorageStatics = {\n prepareQuery(\n _schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ) {\n mutateableQuery = flatClone(mutateableQuery);\n if (Object.keys(ensureNotFalsy(mutateableQuery.selector)).length > 0) {\n mutateableQuery.selector = {\n $and: [\n {\n _deleted: false\n },\n mutateableQuery.selector\n ]\n } as any;\n } else {\n mutateableQuery.selector = {\n _deleted: false\n } as any;\n }\n\n return mutateableQuery;\n },\n\n\n getSortComparator(\n schema: RxJsonSchema>,\n query: MangoQuery\n ): DeterministicSortComparator {\n return getLokiSortComparator(schema, query);\n },\n\n /**\n * Returns a function that determines if a document matches a query selector.\n * It is important to have the exact same logix as lokijs uses, to be sure\n * that the event-reduce algorithm works correct.\n * But LokisJS does not export such a function, the query logic is deep inside of\n * the Resultset prototype.\n * Because I am lazy, I do not copy paste and maintain that code.\n * Instead we create a fake Resultset and apply the prototype method Resultset.prototype.find(),\n * same with Collection.\n */\n getQueryMatcher(\n _schema: RxJsonSchema,\n query: MangoQuery\n ): QueryMatcher> {\n const fun: QueryMatcher> = (doc: RxDocumentWriteData) => {\n if (doc._deleted) {\n return false;\n }\n const docWithResetDeleted = flatClone(doc);\n docWithResetDeleted._deleted = !!docWithResetDeleted._deleted;\n\n const fakeCollection = {\n data: [docWithResetDeleted],\n binaryIndices: {}\n };\n Object.setPrototypeOf(fakeCollection, (lokijs as any).Collection.prototype);\n const fakeResultSet: any = {\n collection: fakeCollection\n };\n Object.setPrototypeOf(fakeResultSet, (lokijs as any).Resultset.prototype);\n fakeResultSet.find(query.selector, true);\n\n const ret = fakeResultSet.filteredrows.length > 0;\n return ret;\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n};\n\nexport class RxStorageLoki implements RxStorage {\n public name = RX_STORAGE_NAME_LOKIJS;\n public statics = RxStorageLokiStatics;\n\n /**\n * Create one leader elector by db name.\n * This is done inside of the storage, not globally\n * to make it easier to test multi-tab behavior.\n */\n public leaderElectorByLokiDbName: Map = new Map();\n\n constructor(\n public databaseSettings: LokiDatabaseSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n return createLokiStorageInstance(this, params, this.databaseSettings);\n }\n}\n\nexport function getRxStorageLoki(\n databaseSettings: LokiDatabaseSettings = {}\n): RxStorageLoki {\n const storage = new RxStorageLoki(databaseSettings);\n return storage;\n}\n"],"mappings":"AAIA,OAAOA,MAAM,MAAM,QAAQ;AAc3B,SACIC,cAAc,EACdC,SAAS,QACN,UAAU;AACjB,SACIC,yBAAyB,QAEtB,4BAA4B;AACnC,SAASC,qBAAqB,EAAEC,sBAAsB,QAAQ,iBAAiB;AAG/E,SAASC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C,UAAU,EAAEP;MAChB,CAAC;MACDb,MAAM,CAACgB,cAAc,CAACG,aAAa,EAAG/B,MAAM,CAASiC,SAAS,CAACH,SAAS,CAAC;MACzEC,aAAa,CAACG,IAAI,CAACd,KAAK,CAACN,QAAQ,EAAE,IAAI,CAAC;MAExC,IAAMqB,GAAG,GAAGJ,aAAa,CAACK,YAAY,CAACrB,MAAM,GAAG,CAAC;MACjD,OAAOoB,GAAG;IACd,CAAC;IACD,OAAOb,GAAG;EACd,CAAC;EAEDe,gBAAgB,EAAE9B;AACtB,CAAC;AAED,WAAa+B,aAAa;EAItB;AACJ;AACA;AACA;AACA;;EAUI,uBACWC,gBAAsC,EAC/C;IAAA,KAnBKC,IAAI,GAAGnC,sBAAsB;IAAA,KAC7BoC,OAAO,GAAGjC,oBAAoB;IAAA,KAO9BkC,yBAAyB,GAO3B,IAAIC,GAAG,EAAE;IAAA,KAGHJ,gBAAsC,GAAtCA,gBAAsC;EAC7C;EAAC;EAAA,OAEEK,qBAAqB,GAA5B,+BACIC,MAAgE,EACvB;IACzCvC,uCAAuC,CAACuC,MAAM,CAAC;IAC/C,OAAO1C,yBAAyB,CAAC,IAAI,EAAE0C,MAAM,EAAE,IAAI,CAACN,gBAAgB,CAAC;EACzE,CAAC;EAAA;AAAA;AAGL,OAAO,SAASO,gBAAgB,GAEf;EAAA,IADbP,gBAAsC,uEAAG,CAAC,CAAC;EAE3C,IAAMQ,OAAO,GAAG,IAAIT,aAAa,CAACC,gBAAgB,CAAC;EACnD,OAAOQ,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/memory/binary-search-bounds.js b/dist/es/plugins/storage-memory/binary-search-bounds.js similarity index 100% rename from dist/es/plugins/memory/binary-search-bounds.js rename to dist/es/plugins/storage-memory/binary-search-bounds.js diff --git a/dist/es/plugins/storage-memory/binary-search-bounds.js.map b/dist/es/plugins/storage-memory/binary-search-bounds.js.map new file mode 100644 index 00000000000..f773654f7a8 --- /dev/null +++ b/dist/es/plugins/storage-memory/binary-search-bounds.js.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search-bounds.js","names":["ge","a","y","c","l","h","i","m","x","p","undefined","gt","lt","le","eq","norm","f","length","boundGE","boundGT","boundLT","boundLE","boundEQ"],"sources":["../../../../src/plugins/storage-memory/binary-search-bounds.ts"],"sourcesContent":["/**\n * Everything in this file was copied and adapted from\n * @link https://github.com/mikolalysenko/binary-search-bounds\n *\n * TODO We should use the original npm module instead when this bug is fixed:\n * @link https://github.com/mikolalysenko/binary-search-bounds/pull/14\n */\n\n\n\ntype Compare = ((a: T, b: T) => number | null | undefined);\n\nfunction ge(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i: number = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x: any = a[m];\n const p: any = (c !== undefined) ? c(x, y) : (x - (y as any));\n if (p >= 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction gt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p > 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction lt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p < 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction le(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p <= 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction eq(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p === 0) {\n return m;\n }\n if (p <= 0) {\n l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return -1;\n}\n\nfunction norm(a: T[], y: T, c: Compare, l: any, h: any, f: any) {\n if (typeof c === 'function') {\n return f(a, y, c, (l === undefined) ? 0 : l | 0, (h === undefined) ? a.length - 1 : h | 0);\n }\n return f(a, y, undefined, (c === undefined) ? 0 : c | 0, (l === undefined) ? a.length - 1 : l | 0);\n}\n\n\nexport function boundGE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, ge);\n}\nexport function boundGT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, gt);\n}\nexport function boundLT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, lt);\n}\nexport function boundLE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, le);\n}\nexport function boundEQ(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, eq);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,EAAE,CAAIC,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAS,GAAGD,CAAC,GAAG,CAAC;EACrB,OAAOD,CAAC,IAAIC,CAAC,EAAE;IACX,IAAME,CAAC,GAAIH,CAAC,GAAGC,CAAC,KAAM,CAAC;IACvB,IAAMG,CAAM,GAAGP,CAAC,CAACM,CAAC,CAAC;IACnB,IAAME,CAAM,GAAIN,CAAC,KAAKO,SAAS,GAAIP,CAAC,CAACK,CAAC,EAAEN,CAAC,CAAC,GAAIM,CAAC,GAAIN,CAAU;IAC7D,IAAIO,CAAC,IAAI,CAAC,EAAE;MACRH,CAAC,GAAGC,CAAC;MAA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EC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEQ,EAAE,CAAC;AAClC;AACA,OAAO,SAASS,OAAO,CAAIrB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAES,EAAE,CAAC;AAClC"} \ No newline at end of file diff --git a/dist/es/plugins/memory/index.js b/dist/es/plugins/storage-memory/index.js similarity index 73% rename from dist/es/plugins/memory/index.js rename to dist/es/plugins/storage-memory/index.js index 1da57968205..82f8d635b5f 100644 --- a/dist/es/plugins/memory/index.js +++ b/dist/es/plugins/storage-memory/index.js @@ -1,13 +1,20 @@ import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper'; -import { flatClone } from '../../util'; -import { RxStorageDexieStatics } from '../dexie/dexie-statics'; +import { flatClone } from '../../plugins/utils'; +import { RxStorageDexieStatics } from '../storage-dexie/dexie-statics'; import { createMemoryStorageInstance } from './rx-storage-instance-memory'; + +/** + * Keep the state even when the storage instance is closed. + * This makes it easier to use the memory storage + * to test filesystem-like and multiInstance behaviors. + */ +var COLLECTION_STATES = new Map(); export function getRxStorageMemory() { var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var storage = { name: 'memory', statics: RxStorageDexieStatics, - collectionStates: new Map(), + collectionStates: COLLECTION_STATES, createStorageInstance: function createStorageInstance(params) { ensureRxStorageInstanceParamsAreCorrect(params); diff --git a/dist/es/plugins/storage-memory/index.js.map b/dist/es/plugins/storage-memory/index.js.map new file mode 100644 index 00000000000..9a2aae6faac --- /dev/null +++ b/dist/es/plugins/storage-memory/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["ensureRxStorageInstanceParamsAreCorrect","flatClone","RxStorageDexieStatics","createMemoryStorageInstance","COLLECTION_STATES","Map","getRxStorageMemory","settings","storage","name","statics","collectionStates","createStorageInstance","params","collectionName","schema","version","useSettings","Object","assign","options"],"sources":["../../../../src/plugins/storage-memory/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type { RxStorageInstanceCreationParams } from '../../types';\nimport { flatClone } from '../../plugins/utils';\nimport { RxStorageDexieStatics } from '../storage-dexie/dexie-statics';\nimport type {\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\nimport {\n createMemoryStorageInstance,\n RxStorageInstanceMemory\n} from './rx-storage-instance-memory';\n\n/**\n * Keep the state even when the storage instance is closed.\n * This makes it easier to use the memory storage\n * to test filesystem-like and multiInstance behaviors.\n */\nconst COLLECTION_STATES = new Map();\n\nexport function getRxStorageMemory(\n settings: RxStorageMemorySettings = {}\n): RxStorageMemory {\n\n const storage: RxStorageMemory = {\n name: 'memory',\n statics: RxStorageDexieStatics,\n collectionStates: COLLECTION_STATES,\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n\n // TODO we should not need to append the schema version here.\n params = flatClone(params);\n params.collectionName = params.collectionName + '-' + params.schema.version;\n\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n\n\n return createMemoryStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './memory-helper';\nexport * from './binary-search-bounds';\nexport * from './memory-types';\nexport * from './memory-indexes';\nexport * from './rx-storage-instance-memory';\n"],"mappings":"AAAA,SAASA,uCAAuC,QAAQ,yBAAyB;AAEjF,SAASC,SAAS,QAAQ,qBAAqB;AAC/C,SAASC,qBAAqB,QAAQ,gCAAgC;AAMtE,SACIC,2BAA2B,QAExB,8BAA8B;;AAErC;AACA;AACA;AACA;AACA;AACA,IAAMC,iBAAiB,GAAG,IAAIC,GAAG,EAAE;AAEnC,OAAO,SAASC,kBAAkB,GAEf;EAAA,IADfC,QAAiC,uEAAG,CAAC,CAAC;EAGtC,IAAMC,OAAwB,GAAG;IAC7BC,IAAI,EAAE,QAAQ;IACdC,OAAO,EAAER,qBAAqB;IAC9BS,gBAAgB,EAAEP,iBAAiB;IACnCQ,qBAAqB,iCACjBC,MAA0F,EAC/C;MAC3Cb,uCAAuC,CAACa,MAAM,CAAC;;MAE/C;MACAA,MAAM,GAAGZ,SAAS,CAACY,MAAM,CAAC;MAC1BA,MAAM,CAACC,cAAc,GAAGD,MAAM,CAACC,cAAc,GAAG,GAAG,GAAGD,MAAM,CAACE,MAAM,CAACC,OAAO;MAE3E,IAAMC,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFZ,QAAQ,EACRM,MAAM,CAACO,OAAO,CACjB;MAGD,OAAOjB,2BAA2B,CAAC,IAAI,EAAEU,MAAM,EAAEI,WAAW,CAAC;IACjE;EACJ,CAAC;EAED,OAAOT,OAAO;AAClB;AAGA,cAAc,iBAAiB;AAC/B,cAAc,wBAAwB;AACtC,cAAc,gBAAgB;AAC9B,cAAc,kBAAkB;AAChC,cAAc,8BAA8B"} \ No newline at end of file diff --git a/dist/es/plugins/memory/memory-helper.js b/dist/es/plugins/storage-memory/memory-helper.js similarity index 100% rename from dist/es/plugins/memory/memory-helper.js rename to dist/es/plugins/storage-memory/memory-helper.js diff --git a/dist/es/plugins/storage-memory/memory-helper.js.map b/dist/es/plugins/storage-memory/memory-helper.js.map new file mode 100644 index 00000000000..75128f45e23 --- /dev/null +++ b/dist/es/plugins/storage-memory/memory-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-helper.js","names":["pushAtSortPosition","newRxError","boundEQ","getMemoryCollectionKey","databaseName","collectionName","ensureNotRemoved","instance","internals","removed","Error","attachmentMapKey","documentId","attachmentId","SORT_BY_INDEX_STRING","a","b","indexString","putWriteRowToState","docId","state","stateByIndex","row","docInState","documents","set","document","forEach","byIndex","docsWithIndex","newIndexString","getIndexableString","id","doc","insertPosition","previousIndexString","prev","splice","next","args","indexBefore","compareDocsWithIndex","removeDocFromState","primaryPath","schema","Object","values","positionInIndex"],"sources":["../../../../src/plugins/storage-memory/memory-helper.ts"],"sourcesContent":["import type {\n BulkWriteRow,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport type {\n DocWithIndexString,\n MemoryStorageInternals,\n MemoryStorageInternalsByIndex\n} from './memory-types';\nimport type { RxStorageInstanceMemory } from './rx-storage-instance-memory';\nimport {\n pushAtSortPosition\n} from 'array-push-at-sort-position';\nimport { newRxError } from '../../rx-error';\nimport { boundEQ } from './binary-search-bounds';\n\n\nexport function getMemoryCollectionKey(\n databaseName: string,\n collectionName: string\n): string {\n return databaseName + '--memory--' + collectionName;\n}\n\n\nexport function ensureNotRemoved(\n instance: RxStorageInstanceMemory\n) {\n if (instance.internals.removed) {\n throw new Error('removed');\n }\n}\n\nexport function attachmentMapKey(documentId: string, attachmentId: string): string {\n return documentId + '||' + attachmentId;\n}\n\nconst SORT_BY_INDEX_STRING = (a: DocWithIndexString, b: DocWithIndexString) => {\n if (a.indexString < b.indexString) {\n return -1;\n } else {\n return 1;\n }\n};\n\n\n\nexport function putWriteRowToState(\n docId: string,\n state: MemoryStorageInternals,\n stateByIndex: MemoryStorageInternalsByIndex[],\n row: BulkWriteRow,\n docInState?: RxDocumentData\n) {\n state.documents.set(docId, row.document as any);\n stateByIndex.forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const newIndexString = byIndex.getIndexableString(row.document as any);\n const [, insertPosition] = pushAtSortPosition(\n docsWithIndex,\n {\n id: docId,\n doc: row.document,\n indexString: newIndexString\n },\n SORT_BY_INDEX_STRING,\n true\n );\n\n /**\n * Remove previous if it was in the state\n */\n if (docInState) {\n const previousIndexString = byIndex.getIndexableString(docInState);\n if (previousIndexString === newIndexString) {\n /**\n * Index not changed -> The old doc must be before or after the new one.\n */\n const prev = docsWithIndex[insertPosition - 1];\n if (prev && prev.id === docId) {\n docsWithIndex.splice(insertPosition - 1, 1);\n } else {\n const next = docsWithIndex[insertPosition + 1];\n if (next.id === docId) {\n docsWithIndex.splice(insertPosition + 1, 1);\n } else {\n throw newRxError('SNH', {\n args: {\n row,\n byIndex\n }\n });\n }\n }\n } else {\n /**\n * Index changed, we must search for the old one and remove it.\n */\n const indexBefore = boundEQ(\n docsWithIndex,\n {\n indexString: previousIndexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(indexBefore, 1);\n }\n }\n });\n}\n\n\nexport function removeDocFromState(\n primaryPath: string,\n schema: RxJsonSchema>,\n state: MemoryStorageInternals,\n doc: RxDocumentData\n) {\n const docId: string = (doc as any)[primaryPath];\n state.documents.delete(docId);\n\n Object.values(state.byIndex).forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const indexString = byIndex.getIndexableString(doc);\n\n const positionInIndex = boundEQ(\n docsWithIndex,\n {\n indexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(positionInIndex, 1);\n });\n}\n\n\nexport function compareDocsWithIndex(\n a: DocWithIndexString,\n b: DocWithIndexString\n): 1 | 0 | -1 {\n if (a.indexString < b.indexString) {\n return -1;\n } else if (a.indexString === b.indexString) {\n return 0;\n } else {\n return 1;\n }\n}\n"],"mappings":"AAWA,SACIA,kBAAkB,QACf,6BAA6B;AACpC,SAASC,UAAU,QAAQ,gBAAgB;AAC3C,SAASC,OAAO,QAAQ,wBAAwB;AAGhD,OAAO,SAASC,sBAAsB,CAClCC,YAAoB,EACpBC,cAAsB,EAChB;EACN,OAAOD,YAAY,GAAG,YAAY,GAAGC,cAAc;AACvD;AAGA,OAAO,SAASC,gBAAgB,CAC5BC,QAAsC,EACxC;EACE,IAAIA,QAAQ,CAACC,SAAS,CAACC,OAAO,EAAE;IAC5B,MAAM,IAAIC,KAAK,CAAC,SAAS,CAAC;EAC9B;AACJ;AAEA,OAAO,SAAS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AChCC,CAAgC,EACtB;EACV,IAAID,CAAC,CAACE,WAAW,GAAGD,CAAC,CAACC,WAAW,EAAE;IAC/B,OAAO,CAAC,CAAC;EACb,CAAC,MAAM,IAAIF,CAAC,CAACE,WAAW,KAAKD,CAAC,CAACC,WAAW,EAAE;IACxC,OAAO,CAAC;EACZ,CAAC,MAAM;IACH,OAAO,CAAC;EACZ;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/memory/memory-indexes.js b/dist/es/plugins/storage-memory/memory-indexes.js similarity index 94% rename from dist/es/plugins/memory/memory-indexes.js rename to dist/es/plugins/storage-memory/memory-indexes.js index 4cfa85d632a..4adb7c312d0 100644 --- a/dist/es/plugins/memory/memory-indexes.js +++ b/dist/es/plugins/storage-memory/memory-indexes.js @@ -1,9 +1,10 @@ import { getIndexableStringMonad } from '../../custom-index'; import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; +import { toArray } from '../../plugins/utils'; export function addIndexesToInternalsState(state, schema) { var primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey); var useIndexes = !schema.indexes ? [] : schema.indexes.map(function (row) { - return Array.isArray(row) ? row.slice(0) : [row]; + return toArray(row); }); // we need this as default index diff --git a/dist/es/plugins/storage-memory/memory-indexes.js.map b/dist/es/plugins/storage-memory/memory-indexes.js.map new file mode 100644 index 00000000000..462f6691be5 --- /dev/null +++ b/dist/es/plugins/storage-memory/memory-indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-indexes.js","names":["getIndexableStringMonad","getPrimaryFieldOfPrimaryKey","toArray","addIndexesToInternalsState","state","schema","primaryPath","primaryKey","useIndexes","indexes","map","row","push","forEach","indexAr","unshift","byIndex","getMemoryIndexName","index","docsWithIndex","getIndexableString","changesIndex","indexName","join"],"sources":["../../../../src/plugins/storage-memory/memory-indexes.ts"],"sourcesContent":["import { getIndexableStringMonad } from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type { RxDocumentData, RxJsonSchema } from '../../types';\nimport { toArray } from '../../plugins/utils';\nimport type { MemoryStorageInternals } from './memory-types';\n\nexport function addIndexesToInternalsState(\n state: MemoryStorageInternals,\n schema: RxJsonSchema>\n) {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const useIndexes: string[][] = !schema.indexes ? [] : schema.indexes.map(row => toArray(row)) as any;\n\n // we need this as default index\n useIndexes.push([\n primaryPath\n ]);\n\n // we need this index for running cleanup()\n useIndexes.push([\n '_meta.lwt',\n primaryPath\n ]);\n\n\n useIndexes.forEach(indexAr => {\n /**\n * Running a query will only return non-deleted documents\n * so all indexes must have the the deleted field as first index field.\n */\n indexAr.unshift('_deleted');\n\n state.byIndex[getMemoryIndexName(indexAr)] = {\n index: indexAr,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, indexAr)\n };\n });\n\n // we need this index for the changes()\n const changesIndex = [\n '_meta.lwt',\n primaryPath\n ];\n const indexName = getMemoryIndexName(changesIndex);\n state.byIndex[indexName] = {\n index: changesIndex,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, changesIndex)\n };\n\n}\n\n\nexport function getMemoryIndexName(index: string[]): string {\n return index.join(',');\n}\n"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,oBAAoB;AAC5D,SAASC,2BAA2B,QAAQ,wBAAwB;AAEpE,SAASC,OAAO,QAAQ,qBAAqB;AAG7C,OAAO,SAASC,0BAA0B,CACtCC,KAAwC,EACxCC,MAA+C,EACjD;EACE,IAAMC,WAAW,GAAGL,2BAA2B,CAACI,MAAM,CAACE,UAAU,CAAC;EAClE,IAAMC,UAAsB,GAAG,CAACH,MAAM,CAACI,OAAO,GAAG,EAAE,GAAGJ,MAAM,CAACI,OAAO,CAACC,GAAG,CAAC,UAAAC,GAAG;IAAA,OAAIT,OAAO,CAACS,GAAG,CAAC;EAAA,EAAQ;;EAEpG;EACAH,UAAU,CAACI,IAAI,CAAC,CACZN,WAAW,CACd,CAAC;;EAEF;EACAE,UAAU,CAACI,IAAI,CAAC,CACZ,WAAW,EACXN,WAAW,CACd,CAAC;EAGFE,UAAU,CAACK,OAAO,CAAC,UAAAC,OAAO,EAAI;IAC1B;AACR;AACA;AACA;IACQA,OAAO,CAACC,OAAO,CAAC,UAAU,CAAC;IAE3BX,KAAK,CAACY,OAAO,CAACC,kBAAkB,CAACH,OAAO,CAAC,CAAC,GAAG;MACzCI,KAAK,EAAEJ,OAAO;MACdK,aAAa,EAAE,EAAE;MACjBC,kBAAkB,EAAEpB,uBAAuB,CAACK,MAAM,EAAES,OAAO;IAC/D,CAAC;EACL,CAAC,CAAC;;EAEF;EACA,IAAMO,YAAY,GAAG,CACjB,WAAW,EACXf,WAAW,CACd;EACD,IAAMgB,SAAS,GAAGL,kBAAkB,CAACI,YAAY,CAAC;EAClDjB,KAAK,CAACY,OAAO,CAACM,SAAS,CAAC,GAAG;IACvBJ,KAAK,EAAEG,YAAY;IACnBF,aAAa,EAAE,EAAE;IACjBC,kBAAkB,EAAEpB,uBAAuB,CAACK,MAAM,EAAEgB,YAAY;EACpE,CAAC;AAEL;AAGA,OAAO,SAASJ,kBAAkB,CAACC,KAAe,EAAU;EACxD,OAAOA,KAAK,CAACK,IAAI,CAAC,GAAG,CAAC;AAC1B"} \ No newline at end of file diff --git a/dist/es/plugins/memory/memory-types.js b/dist/es/plugins/storage-memory/memory-types.js similarity index 100% rename from dist/es/plugins/memory/memory-types.js rename to dist/es/plugins/storage-memory/memory-types.js diff --git a/dist/es/plugins/storage-memory/memory-types.js.map b/dist/es/plugins/storage-memory/memory-types.js.map new file mode 100644 index 00000000000..1f38fed151b --- /dev/null +++ b/dist/es/plugins/storage-memory/memory-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/storage-memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n DexiePreparedQuery,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n /**\n * We re-use the memory state when multiple instances\n * are created with the same params.\n * If refCount beomces 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n changes$: Subject>, RxStorageDefaultCheckpoint>>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n\nexport type MemoryPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/plugins/memory/rx-storage-instance-memory.js b/dist/es/plugins/storage-memory/rx-storage-instance-memory.js similarity index 82% rename from dist/es/plugins/memory/rx-storage-instance-memory.js rename to dist/es/plugins/storage-memory/rx-storage-instance-memory.js index 8d87ba85c16..95f617b4020 100644 --- a/dist/es/plugins/memory/rx-storage-instance-memory.js +++ b/dist/es/plugins/storage-memory/rx-storage-instance-memory.js @@ -1,16 +1,17 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { Subject } from 'rxjs'; import { getStartIndexStringFromLowerBound, getStartIndexStringFromUpperBound } from '../../custom-index'; import { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper'; import { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper'; -import { getFromMapOrThrow, lastOfArray, now, PROMISE_RESOLVE_TRUE, PROMISE_RESOLVE_VOID, RX_META_LWT_MINIMUM } from '../../util'; -import { RxStorageDexieStatics } from '../dexie/dexie-statics'; +import { getFromMapOrThrow, lastOfArray, now, PROMISE_RESOLVE_TRUE, PROMISE_RESOLVE_VOID, RX_META_LWT_MINIMUM } from '../../plugins/utils'; +import { RxStorageDexieStatics } from '../storage-dexie/dexie-statics'; import { boundGE, boundGT, boundLE } from './binary-search-bounds'; import { attachmentMapKey, compareDocsWithIndex, ensureNotRemoved, getMemoryCollectionKey, putWriteRowToState, removeDocFromState } from './memory-helper'; import { addIndexesToInternalsState, getMemoryIndexName } from './memory-indexes'; export var RxStorageInstanceMemory = /*#__PURE__*/function () { function RxStorageInstanceMemory(storage, databaseName, collectionName, schema, internals, options, settings) { this.closed = false; - this.changes$ = new Subject(); this.storage = storage; this.databaseName = databaseName; this.collectionName = collectionName; @@ -65,7 +66,7 @@ export var RxStorageInstanceMemory = /*#__PURE__*/function () { id: lastState[this.primaryPath], lwt: lastState._meta.lwt }; - this.changes$.next(categorized.eventBulk); + this.internals.changes$.next(categorized.eventBulk); } return Promise.resolve(ret); }; @@ -133,19 +134,31 @@ export var RxStorageInstanceMemory = /*#__PURE__*/function () { documents: rows }); }; - _proto.count = function count(preparedQuery) { - try { - var _this3 = this; - return Promise.resolve(_this3.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); + _proto.count = /*#__PURE__*/function () { + var _count = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(preparedQuery) { + var result; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.query(preparedQuery); + case 2: + result = _context.sent; + return _context.abrupt("return", { + count: result.documents.length, + mode: 'fast' + }); + case 4: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function count(_x) { + return _count.apply(this, arguments); } - }; + return count; + }(); _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { var sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM; var sinceId = checkpoint ? checkpoint.id : ''; @@ -204,29 +217,35 @@ export var RxStorageInstanceMemory = /*#__PURE__*/function () { }; _proto.changeStream = function changeStream() { ensureNotRemoved(this); - return this.changes$.asObservable(); + return this.internals.changes$.asObservable(); }; - _proto.remove = function remove() { - try { - var _this4 = this; - ensureNotRemoved(_this4); - _this4.internals.removed = true; - _this4.storage.collectionStates["delete"](getMemoryCollectionKey(_this4.databaseName, _this4.collectionName)); - return Promise.resolve(_this4.close()).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + ensureNotRemoved(this); + this.internals.removed = true; + this.storage.collectionStates["delete"](getMemoryCollectionKey(this.databaseName, this.collectionName)); + _context2.next = 5; + return this.close(); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _proto.close = function close() { if (this.closed) { return Promise.reject(new Error('already closed')); } this.closed = true; - this.changes$.complete(); this.internals.refCount = this.internals.refCount - 1; - if (this.internals.refCount === 0) { - this.storage.collectionStates["delete"](getMemoryCollectionKey(this.databaseName, this.collectionName)); - } return PROMISE_RESOLVE_VOID; }; _proto.conflictResultionTasks = function conflictResultionTasks() { @@ -247,7 +266,8 @@ export function createMemoryStorageInstance(storage, params, settings) { documents: new Map(), attachments: params.schema.attachments ? new Map() : undefined, byIndex: {}, - conflictResultionTasks$: new Subject() + conflictResultionTasks$: new Subject(), + changes$: new Subject() }; addIndexesToInternalsState(internals, params.schema); storage.collectionStates.set(collectionKey, internals); diff --git a/dist/es/plugins/storage-memory/rx-storage-instance-memory.js.map b/dist/es/plugins/storage-memory/rx-storage-instance-memory.js.map new file mode 100644 index 00000000000..491908a961e --- /dev/null +++ b/dist/es/plugins/storage-memory/rx-storage-instance-memory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-memory.js","names":["Subject","getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","getNewestOfDocumentStates","getFromMapOrThrow","lastOfArray","now","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_VOID","RX_META_LWT_MINIMUM","RxStorageDexieStatics","boundGE","boundGT","boundLE","attachmentMapKey","compareDocsWithIndex","ensureNotRemoved","getMemoryCollectionKey","putWriteRowToState","removeDocFromState","addIndexesToInternalsState","getMemoryIndexName","RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","primaryPath","primaryKey","bulkWrite","documentWrites","context","ret","success","error","categorized","documents","errors","stateByIndex","Object","values","byIndex","bulkInsertDocs","forEach","writeRow","docId","document","undefined","bulkUpdateDocs","get","attachmentsMap","attachments","attachmentsAdd","attachment","set","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","eventBulk","events","length","lastState","checkpoint","id","lwt","_meta","changes$","next","Promise","resolve","findDocumentsById","docIds","withDeleted","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","concat","lowerBound","startKeys","lowerBoundString","inclusiveStart","upperBound","endKeys","upperBoundString","inclusiveEnd","indexName","docsWithIndex","indexOfLower","indexString","indexOfUpper","rows","done","currentDoc","doc","push","sortComparator","getSortComparator","sort","slice","count","result","mode","getChangedDocumentsSince","sinceLwt","sinceId","lastDoc","cleanup","minimumDeletedTime","maxDeletionTime","getAttachmentData","data","changeStream","asObservable","remove","removed","collectionStates","close","reject","Error","refCount","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","instance"],"sources":["../../../../src/plugins/storage-memory/rx-storage-instance-memory.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport {\n getFromMapOrThrow,\n lastOfArray,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM\n} from '../../plugins/utils';\nimport { RxStorageDexieStatics } from '../storage-dexie/dexie-statics';\nimport {\n boundGE,\n boundGT,\n boundLE\n} from './binary-search-bounds';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes';\nimport type {\n MemoryPreparedQuery,\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotRemoved(this);\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n this.internals.documents,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n undefined\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n this.internals.documents.get(docId as any)\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n /**\n * Handle attachments\n */\n const attachmentsMap = this.internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.internals.changes$.next(categorized.eventBulk);\n }\n return Promise.resolve(ret);\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise> {\n const ret: RxDocumentDataById = {};\n docIds.forEach(docId => {\n const docInDb = this.internals.documents.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n });\n return Promise.resolve(ret);\n }\n\n query(preparedQuery: MemoryPreparedQuery): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n this.schema,\n preparedQuery\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n const index: string[] | undefined = ['_deleted'].concat(queryPlanFields);\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound,\n queryPlan.inclusiveEnd\n );\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGE(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n const indexOfUpper = boundLE(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n\n\n if (\n !currentDoc ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n\n if (!queryMatcher || queryMatcher(currentDoc.doc)) {\n rows.push(currentDoc.doc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort) ||\n indexOfLower >= docsWithIndex.length\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(this.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: MemoryPreparedQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n\n const index = ['_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n ['_meta.lwt', this.primaryPath as any],\n [\n sinceLwt,\n sinceId\n ],\n false\n );\n\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n // TODO use array.slice() so we do not have to iterate here\n const rows: RxDocumentData[] = [];\n while (rows.length < limit && indexOfLower < docsWithIndex.length) {\n const currentDoc = docsWithIndex[indexOfLower];\n rows.push(currentDoc.doc);\n indexOfLower++;\n }\n\n const lastDoc = lastOfArray(rows);\n return Promise.resolve({\n documents: rows,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n });\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ],\n false\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n ensureNotRemoved(this);\n const data = getFromMapOrThrow(\n this.internals.attachments,\n attachmentMapKey(documentId, attachmentId)\n );\n return Promise.resolve(data.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.internals.changes$.asObservable();\n }\n\n async remove(): Promise {\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(this.databaseName, this.collectionName)\n );\n await this.close();\n }\n\n close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n\n this.internals.refCount = this.internals.refCount - 1;\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(params.databaseName, params.collectionName);\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject(),\n changes$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;AACA,SAEIA,OAAO,QACJ,MAAM;AACb,SACIC,iCAAiC,EACjCC,iCAAiC,QAC9B,oBAAoB;AAC3B,SAASC,2BAA2B,QAAQ,wBAAwB;AACpE,SACIC,uBAAuB,EACvBC,yBAAyB,QACtB,yBAAyB;AAkBhC,SACIC,iBAAiB,EACjBC,WAAW,EACXC,GAAG,EACHC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,QAChB,qBAAqB;AAC5B,SAASC,qBAAqB,QAAQ,gCAAgC;AACtE,SACIC,OAAO,EACPC,OAAO,EACPC,OAAO,QACJ,wBAAwB;AAC/B,SACIC,gBAAgB,EAChBC,oBAAoB,EACpBC,gBAAgB,EAChBC,sBAAsB,EACtBC,kBAAkB,EAClBC,kBAAkB,QACf,iBAAiB;AACxB,SACIC,0B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age-remote/remote.js index 4fd4039b4e9..cb5e1cc8e22 100644 --- a/dist/es/plugins/storage-remote/remote.js +++ b/dist/es/plugins/storage-remote/remote.js @@ -1,5 +1,7 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { filter } from 'rxjs'; -import { ensureNotFalsy } from '../../util'; +import { ensureNotFalsy } from '../../plugins/utils'; import { createAnswer, createErrorAnswer } from './storage-remote-helpers'; import deepEqual from 'fast-deep-equal'; @@ -7,146 +9,168 @@ import deepEqual from 'fast-deep-equal'; * Run this on the 'remote' part, * so that RxStorageMessageChannel can connect to it. */ - -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} export function exposeRxStorageRemote(settings) { var instanceByFullName = new Map(); settings.messages$.pipe(filter(function (msg) { return msg.method === 'create'; - })).subscribe(function (msg) { - try { - var _temp3 = function _temp3(_result2) { - if (_exit) return _result2; - state.connectionIds.add(msg.connectionId); - var subs = []; - /** - * Automatically subscribe to the streams$ - * because we always need them. - */ - subs.push(state.storageInstance.changeStream().subscribe(function (changes) { - var message = { - connectionId: connectionId, - answerTo: 'changestream', - method: 'changeStream', - "return": changes - }; - settings.send(message); - })); - subs.push(state.storageInstance.conflictResultionTasks().subscribe(function (conflicts) { - var message = { - connectionId: connectionId, - answerTo: 'conflictResultionTasks', - method: 'conflictResultionTasks', - "return": conflicts - }; - settings.send(message); - })); - subs.push(settings.messages$.pipe(filter(function (subMsg) { - return subMsg.connectionId === connectionId; - })).subscribe(function (plainMessage) { - try { - var message = plainMessage; - if (message.method === 'create') { - return Promise.resolve(); + })).subscribe( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(msg) { + var connectionId, params, fullName, state, newRxStorageInstance, subs; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + connectionId = msg.connectionId; + /** + * Do an isArray check here + * for runtime check types to ensure we have + * instance creation params and not method input params. + */ + if (!Array.isArray(msg.params)) { + _context2.next = 3; + break; } - if (!Array.isArray(message.params)) { - return Promise.resolve(); + return _context2.abrupt("return"); + case 3: + params = msg.params; + /** + * We de-duplicate the storage instances. + * This makes sense in many environments like + * electron where on main process contains the storage + * for multiple renderer processes. Same goes for SharedWorkers etc. + */ + fullName = [params.databaseName, params.collectionName, params.schema.version].join('|'); + state = instanceByFullName.get(fullName); + if (state) { + _context2.next = 21; + break; } - var result; - return Promise.resolve(_catch(function () { - /** - * On calls to 'close()', - * we only close the main instance if there are no other - * ports connected. - */ - if (message.method === 'close' && ensureNotFalsy(state).connectionIds.size > 1) { - settings.send(createAnswer(message, null)); - ensureNotFalsy(state).connectionIds["delete"](connectionId); - subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - return; - } - return Promise.resolve(ensureNotFalsy(state).storageInstance[message.method](message.params[0], message.params[1], message.params[2], message.params[3])).then(function (_message$method) { - result = _message$method; - if (message.method === 'close' || message.method === 'remove') { - subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - ensureNotFalsy(state).connectionIds["delete"](connectionId); - instanceByFullName["delete"](fullName); - /** - * TODO how to notify the other ports on remove() ? - */ - } - - settings.send(createAnswer(message, result)); - }); - }, function (err) { - settings.send(createErrorAnswer(message, err)); + _context2.prev = 7; + _context2.next = 10; + return settings.storage.createStorageInstance(params); + case 10: + newRxStorageInstance = _context2.sent; + state = { + storageInstance: newRxStorageInstance, + connectionIds: new Set(), + params: params + }; + instanceByFullName.set(fullName, state); + _context2.next = 19; + break; + case 15: + _context2.prev = 15; + _context2.t0 = _context2["catch"](7); + settings.send(createErrorAnswer(msg, _context2.t0)); + return _context2.abrupt("return"); + case 19: + _context2.next = 22; + break; + case 21: + // if instance already existed, ensure that the schema is equal + if (!deepEqual(params.schema, state.params.schema)) { + settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage'))); + } + case 22: + state.connectionIds.add(msg.connectionId); + subs = []; + /** + * Automatically subscribe to the streams$ + * because we always need them. + */ + subs.push(state.storageInstance.changeStream().subscribe(function (changes) { + var message = { + connectionId: connectionId, + answerTo: 'changestream', + method: 'changeStream', + "return": changes + }; + settings.send(message); + })); + subs.push(state.storageInstance.conflictResultionTasks().subscribe(function (conflicts) { + var message = { + connectionId: connectionId, + answerTo: 'conflictResultionTasks', + method: 'conflictResultionTasks', + "return": conflicts + }; + settings.send(message); })); - } catch (e) { - return Promise.reject(e); - } - })); - settings.send(createAnswer(msg, 'ok')); - }; - var _exit = false; - var connectionId = msg.connectionId; - /** - * Do an isArray check here - * for runtime check types to ensure we have - * instance creation params and not method input params. - */ - if (Array.isArray(msg.params)) { - return Promise.resolve(); - } - var params = msg.params; - /** - * We de-duplicate the storage instances. - * This makes sense in many environments like - * electron where on main process contains the storage - * for multiple renderer processes. Same goes for SharedWorkers etc. - */ - var fullName = [params.databaseName, params.collectionName, params.schema.version].join('|'); - var state = instanceByFullName.get(fullName); - var _temp2 = function () { - if (!state) { - var _temp = _catch(function () { - return Promise.resolve(settings.storage.createStorageInstance(params)).then(function (newRxStorageInstance) { - state = { - storageInstance: newRxStorageInstance, - connectionIds: new Set(), - params: params + subs.push(settings.messages$.pipe(filter(function (subMsg) { + return subMsg.connectionId === connectionId; + })).subscribe( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(plainMessage) { + var message, result; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + message = plainMessage; + if (!(message.method === 'create')) { + _context.next = 3; + break; + } + return _context.abrupt("return"); + case 3: + if (Array.isArray(message.params)) { + _context.next = 5; + break; + } + return _context.abrupt("return"); + case 5: + _context.prev = 5; + if (!(message.method === 'close' && ensureNotFalsy(state).connectionIds.size > 1)) { + _context.next = 11; + break; + } + settings.send(createAnswer(message, null)); + ensureNotFalsy(state).connectionIds["delete"](connectionId); + subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + return _context.abrupt("return"); + case 11: + _context.next = 13; + return ensureNotFalsy(state).storageInstance[message.method](message.params[0], message.params[1], message.params[2], message.params[3]); + case 13: + result = _context.sent; + if (message.method === 'close' || message.method === 'remove') { + subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + ensureNotFalsy(state).connectionIds["delete"](connectionId); + instanceByFullName["delete"](fullName); + /** + * TODO how to notify the other ports on remove() ? + */ + } + + settings.send(createAnswer(message, result)); + _context.next = 21; + break; + case 18: + _context.prev = 18; + _context.t0 = _context["catch"](5); + settings.send(createErrorAnswer(message, _context.t0)); + case 21: + case "end": + return _context.stop(); + } + }, _callee, null, [[5, 18]]); + })); + return function (_x2) { + return _ref2.apply(this, arguments); }; - instanceByFullName.set(fullName, state); - }); - }, function (err) { - settings.send(createErrorAnswer(msg, err)); - _exit = true; - }); - if (_temp && _temp.then) return _temp.then(function () {}); - } else { - if (!deepEqual(params.schema, state.params.schema)) { - settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage'))); - } + }())); + settings.send(createAnswer(msg, 'ok')); + case 28: + case "end": + return _context2.stop(); } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } - }); + }, _callee2, null, [[7, 15]]); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); return { instanceByFullName: instanceByFullName }; diff --git a/dist/es/plugins/storage-remote/remote.js.map b/dist/es/plugins/storage-remote/remote.js.map index 25a13020c1d..651dcded356 100644 --- a/dist/es/plugins/storage-remote/remote.js.map +++ b/dist/es/plugins/storage-remote/remote.js.map @@ -1 +1 @@ -{"version":3,"file":"remote.js","names":["filter","ensureNotFalsy","createAnswer","createErrorAnswer","deepEqual","body","recover","result","e","then","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","msg","method","subscribe","state","connectionIds","add","connectionId","subs","push","storageInstance","changeStream","changes","message","answerTo","send","conflictResultionTasks","conflicts","subMsg","plainMessage","Array","isArray","params","size","forEach","sub","unsubscribe","fullName","err","databaseName","collectionName","schema","version","join","get","storage","createStorageInstance","newRxStorageInstance","Set","set","Error"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNotFalsy\n} from '../../util';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeType\n} from './storage-remote-types';\nimport deepEqual from 'fast-deep-equal';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstance: RxStorageInstance;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n const connectionId = msg.connectionId;\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n const newRxStorageInstance = await settings.storage.createStorageInstance(params);\n state = {\n storageInstance: newRxStorageInstance,\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n /**\n * Automatically subscribe to the streams$\n * because we always need them.\n */\n subs.push(\n state.storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n\n settings.send(message);\n })\n );\n subs.push(\n state.storageInstance.conflictResultionTasks().subscribe(conflicts => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'conflictResultionTasks',\n method: 'conflictResultionTasks',\n return: conflicts\n };\n settings.send(message);\n })\n );\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (message.method === 'create') {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n result = await (ensureNotFalsy(state).storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":"AAAA,SAASA,MAAM,QAAsB,MAAM;AAK3C,SACIC,cAAc,QACX,YAAY;AACnB,SAASC,YAAY,EA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AK;UAAA,+BACF;YAAA,uBACmCR,QAAQ,CAACuC,OAAO,CAACC,qBAAqB,CAACd,MAAM,CAAC,iBAA3Ee,oBAAoB;cAC1BjC,KAAK,GAAG;gBACJM,eAAe,EAAE2B,oBAAoB;gBACrChC,aAAa,EAAE,IAAIiC,GAAG,EAAE;gBACxBhB,MAAM,EAANA;cACJ,CAAC;cACDzB,kBAAkB,CAAC0C,GAAG,CAACZ,QAAQ,EAAEvB,KAAK,CAAC;YAAC;UAC5C,CAAC,YAAQwB,GAAQ,EAAE;YACfhC,QAAQ,CAACmB,IAAI,CAAC3B,iBAAiB,CAACa,GAAG,EAAE2B,GAAG,CAAC,CAAC;YAAC;UAE/C,CAAC;UAAA;QAAA;UAAA,IAGG,CAACvC,SAAS,CAACiC,MAAM,CAACS,MAAM,EAAE3B,KAAK,CAACkB,MAAM,CAACS,MAAM,CAAC;YAC9CnC,QAAQ,CAACmB,IAAI,CAAC3B,iBAAiB,CAACa,GAAG,EAAE,IAAIuC,KAAK,CAAC,sDAAsD,CAAC,CAAC,CAAC;UAAC;QAAA;MAAA;MAAA;IAoFrH,CAAC;MAAA;IAAA;EAAA,EAAC;EAEF,OAAO;IACH3C,kBAAkB,EAAlBA;EACJ,CAAC;AACL"} \ No newline at end of file +{"version":3,"file":"remote.js","names":["filter","ensureNotFalsy","createAnswer","createErrorAnswer","deepEqual","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","msg","method","subscribe","connectionId","Array","isArray","params","fullName","databaseName","collectionName","schema","version","join","state","get","storage","createStorageInstance","newRxStorageInstance","storageInstance","connectionIds","Set","set","send","Error","add","subs","push","changeStream","changes","message","answerTo","conflictResultionTasks","conflicts","subMsg","plainMessage","size","forEach","sub","unsubscribe","result"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNotFalsy\n} from '../../plugins/utils';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeType\n} from './storage-remote-types';\nimport deepEqual from 'fast-deep-equal';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstance: RxStorageInstance;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n const connectionId = msg.connectionId;\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n const newRxStorageInstance = await settings.storage.createStorageInstance(params);\n state = {\n storageInstance: newRxStorageInstance,\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n /**\n * Automatically subscribe to the streams$\n * because we always need them.\n */\n subs.push(\n state.storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n\n settings.send(message);\n })\n );\n subs.push(\n state.storageInstance.conflictResultionTasks().subscribe(conflicts => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'conflictResultionTasks',\n method: 'conflictResultionTasks',\n return: conflicts\n };\n settings.send(message);\n })\n );\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (message.method === 'create') {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n result = await (ensureNotFalsy(state).storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":";;AAAA,SAASA,MAAM,QAAsB,MAAM;AAK3C,SACIC,cAAc,QACX,qBAAqB;AAC5B,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,0BAA0B;AAO1E,OAAOC,SAAS,MAAM,iBAAiB;;AAEvC;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqB,CAACC,QAAuC,EAA6B;EAMtG,IAAMC,kBAA8C,GAAG,IAAIC,GAAG,EAAE;EAGhEF,QAAQ,CAACG,SAAS,CAACC,IAAI,CACnBV,MAAM,CAAC,UAAAW,GAAG;IAAA,OAAIA,GAAG,CAACC,MAAM,KAAK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A;cAAA,CAEtD;cAAA;gBAAA;cAAA;YAAA,IAAC,CACL;YAEDlC,QAAQ,CAAC2B,IAAI,CAAC/B,YAAY,CAACS,GAAG,EAAE,IAAI,CAAC,CAAC;UAAC;UAAA;YAAA;QAAA;MAAA;IAAA,CAC1C;IAAA;MAAA;IAAA;EAAA,IAAC;EAEF,OAAO;IACHJ,kBAAkB,EAAlBA;EACJ,CAAC;AACL"} \ No newline at end of file diff --git a/dist/es/plugins/storage-remote/rx-storage-remote.js b/dist/es/plugins/storage-remote/rx-storage-remote.js index 7718129e2a7..ddd2e56bbff 100644 --- a/dist/es/plugins/storage-remote/rx-storage-remote.js +++ b/dist/es/plugins/storage-remote/rx-storage-remote.js @@ -1,6 +1,8 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { ensureNotFalsy } from 'event-reduce-js'; import { firstValueFrom, filter, Subject } from 'rxjs'; -import { randomCouchString } from '../../util'; +import { randomCouchString } from '../../plugins/utils'; export var RxStorageRemote = /*#__PURE__*/function () { function RxStorageRemote(settings) { this.name = 'remote'; @@ -14,37 +16,52 @@ export var RxStorageRemote = /*#__PURE__*/function () { var newId = this.lastRequestId++; return this.requestIdSeed + '|' + newId; }; - _proto.createStorageInstance = function createStorageInstance(params) { - try { - var _this = this; - var requestId = _this.getRequestId(); - var waitForOkPromise = firstValueFrom(_this.settings.messages$.pipe(filter(function (msg) { - return msg.answerTo === requestId; - }))); - _this.settings.send({ - connectionId: _this.getRequestId(), - method: 'create', - requestId: requestId, - params: params - }); - return Promise.resolve(waitForOkPromise).then(function (waitForOkResult) { - if (waitForOkResult.error) { - throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error)); + _proto.createStorageInstance = /*#__PURE__*/function () { + var _createStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(params) { + var requestId, waitForOkPromise, waitForOkResult; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + requestId = this.getRequestId(); + waitForOkPromise = firstValueFrom(this.settings.messages$.pipe(filter(function (msg) { + return msg.answerTo === requestId; + }))); + this.settings.send({ + connectionId: this.getRequestId(), + method: 'create', + requestId: requestId, + params: params + }); + _context.next = 5; + return waitForOkPromise; + case 5: + waitForOkResult = _context.sent; + if (!waitForOkResult.error) { + _context.next = 8; + break; + } + throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error)); + case 8: + return _context.abrupt("return", new RxStorageInstanceRemote(this, params.databaseName, params.collectionName, params.schema, { + params: params, + connectionId: ensureNotFalsy(waitForOkResult.connectionId) + }, params.options)); + case 9: + case "end": + return _context.stop(); } - return new RxStorageInstanceRemote(_this, params.databaseName, params.collectionName, params.schema, { - params: params, - connectionId: ensureNotFalsy(waitForOkResult.connectionId) - }, params.options); - }); - } catch (e) { - return Promise.reject(e); + }, _callee, this); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - }; + return createStorageInstance; + }(); return RxStorageRemote; }(); export var RxStorageInstanceRemote = /*#__PURE__*/function () { function RxStorageInstanceRemote(storage, databaseName, collectionName, schema, internals, options) { - var _this2 = this; + var _this = this; this.changes$ = new Subject(); this.conflicts$ = new Subject(); this.subs = []; @@ -56,43 +73,57 @@ export var RxStorageInstanceRemote = /*#__PURE__*/function () { this.internals = internals; this.options = options; this.messages$ = this.storage.settings.messages$.pipe(filter(function (msg) { - return msg.connectionId === _this2.internals.connectionId; + return msg.connectionId === _this.internals.connectionId; })); this.subs.push(this.messages$.subscribe(function (msg) { if (msg.method === 'changeStream') { - _this2.changes$.next(msg["return"]); + _this.changes$.next(msg["return"]); } if (msg.method === 'conflictResultionTasks') { - _this2.conflicts$.next(msg["return"]); + _this.conflicts$.next(msg["return"]); } })); } var _proto2 = RxStorageInstanceRemote.prototype; - _proto2.requestRemote = function requestRemote(methodName, params) { - try { - var _this3 = this; - var requestId = _this3.storage.getRequestId(); - var responsePromise = firstValueFrom(_this3.messages$.pipe(filter(function (msg) { - return msg.answerTo === requestId; - }))); - var message = { - connectionId: _this3.internals.connectionId, - requestId: requestId, - method: methodName, - params: params - }; - _this3.storage.settings.send(message); - return Promise.resolve(responsePromise).then(function (response) { - if (response.error) { - throw new Error('could not requestRemote: ' + JSON.stringify(response.error)); - } else { - return response["return"]; + _proto2.requestRemote = /*#__PURE__*/function () { + var _requestRemote = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(methodName, params) { + var requestId, responsePromise, message, response; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + requestId = this.storage.getRequestId(); + responsePromise = firstValueFrom(this.messages$.pipe(filter(function (msg) { + return msg.answerTo === requestId; + }))); + message = { + connectionId: this.internals.connectionId, + requestId: requestId, + method: methodName, + params: params + }; + this.storage.settings.send(message); + _context2.next = 6; + return responsePromise; + case 6: + response = _context2.sent; + if (!response.error) { + _context2.next = 11; + break; + } + throw new Error('could not requestRemote: ' + JSON.stringify(response.error)); + case 11: + return _context2.abrupt("return", response["return"]); + case 12: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); + }, _callee2, this); + })); + function requestRemote(_x2, _x3) { + return _requestRemote.apply(this, arguments); } - }; + return requestRemote; + }(); _proto2.bulkWrite = function bulkWrite(documentWrites, context) { return this.requestRemote('bulkWrite', [documentWrites, context]); }; @@ -117,42 +148,75 @@ export var RxStorageInstanceRemote = /*#__PURE__*/function () { _proto2.cleanup = function cleanup(minDeletedTime) { return this.requestRemote('cleanup', [minDeletedTime]); }; - _proto2.close = function close() { - try { - var _this4 = this; - if (_this4.closed) { - return Promise.reject(new Error('already closed')); - } - _this4.closed = true; - _this4.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - _this4.changes$.complete(); - return Promise.resolve(_this4.requestRemote('close', [])).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto2.close = /*#__PURE__*/function () { + var _close = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!this.closed) { + _context3.next = 2; + break; + } + return _context3.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + this.changes$.complete(); + _context3.next = 7; + return this.requestRemote('close', []); + case 7: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function close() { + return _close.apply(this, arguments); } - }; - _proto2.remove = function remove() { - try { - var _this5 = this; - _this5.closed = true; - return Promise.resolve(_this5.requestRemote('remove', [])).then(function () {}); - } catch (e) { - return Promise.reject(e); + return close; + }(); + _proto2.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + this.closed = true; + _context4.next = 3; + return this.requestRemote('remove', []); + case 3: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _proto2.conflictResultionTasks = function conflictResultionTasks() { return this.conflicts$; }; - _proto2.resolveConflictResultionTask = function resolveConflictResultionTask(taskSolution) { - try { - var _this6 = this; - return Promise.resolve(_this6.requestRemote('resolveConflictResultionTask', [taskSolution])).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto2.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(taskSolution) { + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return this.requestRemote('resolveConflictResultionTask', [taskSolution]); + case 2: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function resolveConflictResultionTask(_x4) { + return _resolveConflictResultionTask.apply(this, arguments); } - }; + return resolveConflictResultionTask; + }(); return RxStorageInstanceRemote; }(); export function getRxStorageRemote(settings) { diff --git a/dist/es/plugins/storage-remote/rx-storage-remote.js.map b/dist/es/plugins/storage-remote/rx-storage-remote.js.map index fc32ee05c56..e0cd259e50a 100644 --- a/dist/es/plugins/storage-remote/rx-storage-remote.js.map +++ b/dist/es/plugins/storage-remote/rx-storage-remote.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-remote.js","names":["ensureNotFalsy","firstValueFrom","filter","Subject","randomCouchString","RxStorageRemote","settings","name","requestIdSeed","lastRequestId","statics","getRequestId","newId","createStorageInstance","params","requestId","waitForOkPromise","messages$","pipe","msg","answerTo","send","connectionId","method","waitForOkResult","error","Error","JSON","stringify","RxStorageInstanceRemote","databaseName","collectionName","schema","options","storage","internals","changes$","conflicts$","subs","closed","push","subscribe","next","requestRemote","methodName","responsePromise","message","response","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","close","Promise","reject","forEach","sub","unsubscribe","complete","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution","getRxStorageRemote"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import { ensureNotFalsy } from 'event-reduce-js';\nimport {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n RxStorageStatics\n} from '../../types';\nimport {\n randomCouchString\n} from '../../util';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types';\n\n\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly statics: RxStorageStatics;\n public readonly name: string = 'remote';\n private requestIdSeed: string = randomCouchString(10);\n private lastRequestId: number = 0;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n this.statics = settings.statics;\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.requestIdSeed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(this.settings.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n this.settings.send({\n connectionId: this.getRequestId(),\n method: 'create',\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId: ensureNotFalsy(waitForOkResult.connectionId)\n },\n params.options\n );\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.storage.settings.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(msg.return);\n }\n if (msg.method === 'conflictResultionTasks') {\n this.conflicts$.next(msg.return);\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n method: methodName,\n params\n };\n this.storage.settings.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify(response.error));\n } else {\n return response.return;\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n }\n async remove(): Promise {\n this.closed = true;\n await this.requestRemote('remove', []);\n }\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.requestRemote('resolveConflictResultionTask', [taskSolution]);\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n return new RxStorageRemote(settings);\n}\n"],"mappings":"AAAA,SAASA,cAAc,QAAQ,iBAAiB;AAChD,SACIC,cAAc,EACdC,MAAM,EAENC,OAAO,QAEJ,MAAM;AAkBb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MAAC,uBACb,OAAKI,aAAa,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC1C,CAAC;MAAA;IAAA;EAAA;EAAA,QACDgC,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAI,CAACtC,UAAU;EAC1B,CAAC;EAAA,QACKuC,4BAA4B,yCAACC,YAAwD;IAAA,IAAiB;MAAA,aAClG,IAAI;MAAA,uBAAJ,OAAKlC,aAAa,CAAC,8BAA8B,EAAE,CAACkC,YAAY,CAAC,CAAC;IAC5E,CAAC;MAAA;IAAA;EAAA;EAAA;AAAA;AAGL,OAAO,SAASC,kBAAkB,CAACxE,QAAiC,EAAmB;EACnF,OAAO,IAAID,eAAe,CAACC,QAAQ,CAAC;AACxC"} \ No newline at end of file +{"version":3,"file":"rx-storage-remote.js","names":["ensureNotFalsy","firstValueFrom","filter","Subject","randomCouchString","RxStorageRemote","settings","name","requestIdSeed","lastRequestId","statics","getRequestId","newId","createStorageInstance","params","requestId","waitForOkPromise","messages$","pipe","msg","answerTo","send","connectionId","method","waitForOkResult","error","Error","JSON","stringify","RxStorageInstanceRemote","databaseName","collectionName","schema","options","storage","internals","changes$","conflicts$","subs","closed","push","subscribe","next","requestRemote","methodName","responsePromise","message","response","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","close","Promise","reject","forEach","sub","unsubscribe","complete","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution","getRxStorageRemote"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import { ensureNotFalsy } from 'event-reduce-js';\nimport {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n RxStorageStatics\n} from '../../types';\nimport {\n randomCouchString\n} from '../../plugins/utils';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types';\n\n\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly statics: RxStorageStatics;\n public readonly name: string = 'remote';\n private requestIdSeed: string = randomCouchString(10);\n private lastRequestId: number = 0;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n this.statics = settings.statics;\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.requestIdSeed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(this.settings.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n this.settings.send({\n connectionId: this.getRequestId(),\n method: 'create',\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId: ensureNotFalsy(waitForOkResult.connectionId)\n },\n params.options\n );\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.storage.settings.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(msg.return);\n }\n if (msg.method === 'conflictResultionTasks') {\n this.conflicts$.next(msg.return);\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n method: methodName,\n params\n };\n this.storage.settings.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify(response.error));\n } else {\n return response.return;\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n }\n async remove(): Promise {\n this.closed = true;\n await this.requestRemote('remove', []);\n }\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.requestRemote('resolveConflictResultionTask', [taskSolution]);\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n return new RxStorageRemote(settings);\n}\n"],"mappings":";;AAAA,SAASA,cAAc,QAAQ,iBAAiB;AAChD,SACIC,cAAc,EACdC,MAAM,EAENC,OAAO,QAEJ,MAAM;AAkBb,SACIC,iBAAiB,QACd,qBAAqB;AAW5B,WAAaC,eAAe;EAKxB,yBACoBC,QAAiC,EACnD;IAAA,KALcC,IAAI,GAAW,QAAQ;IAAA,KAC/BC,aAAa,GAAWJ,iBAAiB,CAAC,EAAE,CAAC;IAAA,KAC7CK,aAAa,GAAW,CAAC;IAAA,KAEbH,QAAiC,GAAjCA,QAAiC;IAEjD,IAAI,CAACI,OAAO,GAAGJ,QAAQ,CAACI,OAAO;EACnC;EAAC;EAAA,OAEMC,YAAY,GAAnB,wBAAsB;IAClB,IAAMC,KAAK,GAAG,IAAI,CAACH,aAAa,EAAE;IAClC,OAAO,IAAI,CAACD,aAAa,GAAG,GAAG,GAAGI,KAAK;EAC3C,CAAC;EAAA,OAEKC,qBAAqB;IAAA,sFAA3B,iBACIC,MAAuD;MAAA;MAAA;QAAA;UAAA;YAGjDC,SAAS,GAAG,IAAI,CAACJ,YAAY,EAAE;YAC/BK,gBAAgB,GAAGf,cAAc,CAAC,IAAI,CAACK,QAAQ,CAACW,SAAS,CAACC,IAAI,CAChEhB,MAAM,CAAC,UAAAiB,GAAG;cAAA,OAAIA,GAAG,CAACC,QAAQ,KAAKL,SAAS;YAAA,EAAC,CAC5C,CAAC;YACF,IAAI,CAACT,QAAQ,CAACe,IAAI,CAAC;cACfC,YAAY,EAAE,IAAI,CAACX,YAAY,EAAE;cACjCY,MAAM,EAAE,QAAQ;cAChBR,SAAS,EAATA,SAAS;cACTD,MAAM,EAANA;YACJ,CAAC,CAAC;YAAC;YAAA,OAE2BE,gBAAgB;UAAA;YAAxCQ,eAAe;YAAA,KACjBA,eAAe,CAACC,KAAK;cAAA;cA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AAK,CAAC,gBAAgB,CAAC,CAAC;UAAA;YAEtD,IAAI,CAACa,MAAM,GAAG,IAAI;YAClB,IAAI,CAACD,IAAI,CAACgC,OAAO,CAAC,UAAAC,GAAG;cAAA,OAAIA,GAAG,CAACC,WAAW,EAAE;YAAA,EAAC;YAC3C,IAAI,CAACpC,QAAQ,CAACqC,QAAQ,EAAE;YAAC;YAAA,OACnB,IAAI,CAAC9B,aAAa,CAAC,OAAO,EAAE,EAAE,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACxC;IAAA;MAAA;IAAA;IAAA;EAAA;EAAA,QACK+B,MAAM;IAAA,uEAAZ;MAAA;QAAA;UAAA;YACI,IAAI,CAACnC,MAAM,GAAG,IAAI;YAAC;YAAA,OACb,IAAI,CAACI,aAAa,CAAC,QAAQ,EAAE,EAAE,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACzC;IAAA;MAAA;IAAA;IAAA;EAAA;EAAA,QACDgC,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAI,CAACtC,UAAU;EAC1B,CAAC;EAAA,QACKuC,4BAA4B;IAAA,6FAAlC,kBAAmCC,YAAwD;MAAA;QAAA;UAAA;YAAA;YAAA,OACjF,IAAI,CAAClC,aAAa,CAAC,8BAA8B,EAAE,CAACkC,YAAY,CAAC,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CAC3E;IAAA;MAAA;IAAA;IAAA;EAAA;EAAA;AAAA;AAGL,OAAO,SAASC,kBAAkB,CAACxE,QAAiC,EAAmB;EACnF,OAAO,IAAID,eAAe,CAACC,QAAQ,CAAC;AACxC"} \ No newline at end of file diff --git a/dist/es/plugins/storage-remote/storage-remote-helpers.js b/dist/es/plugins/storage-remote/storage-remote-helpers.js index fbcfbd44cbd..b757fb65150 100644 --- a/dist/es/plugins/storage-remote/storage-remote-helpers.js +++ b/dist/es/plugins/storage-remote/storage-remote-helpers.js @@ -1,4 +1,4 @@ -import { errorToPlainJson } from '../../util'; +import { errorToPlainJson } from '../../plugins/utils'; export function createErrorAnswer(msg, error) { return { connectionId: msg.connectionId, diff --git a/dist/es/plugins/storage-remote/storage-remote-helpers.js.map b/dist/es/plugins/storage-remote/storage-remote-helpers.js.map index 175ed2bc92b..c5080b8b241 100644 --- a/dist/es/plugins/storage-remote/storage-remote-helpers.js.map +++ b/dist/es/plugins/storage-remote/storage-remote-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"storage-remote-helpers.js","names":["errorToPlainJson","createErrorAnswer","msg","error","connectionId","answerTo","requestId","method","createAnswer","ret"],"sources":["../../../../src/plugins/storage-remote/storage-remote-helpers.ts"],"sourcesContent":["import type {\n RxError,\n RxTypeError\n} from '../../types';\nimport { errorToPlainJson } from '../../util';\nimport type {\n MessageFromRemote,\n MessageToRemote\n} from './storage-remote-types';\n\nexport function createErrorAnswer(\n msg: MessageToRemote,\n error: Error | TypeError | RxError | RxTypeError\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n error: errorToPlainJson(error)\n };\n}\n\nexport function createAnswer(\n msg: MessageToRemote,\n ret: any\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n return: ret\n };\n}\n"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,YAAY;AAM7C,OAAO,SAASC,iBAAiB,CAC7BC,GAAoB,EACpBC,KAAgD,EAC/B;EACjB,OAAO;IACHC,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClBJ,KAAK,EAAEH,gBAAgB,CAACG,KAAK;EACjC,CAAC;AACL;AAEA,OAAO,SAASK,YAAY,CACxBN,GAAoB,EACpBO,GAAQ,EACS;EACjB,OAAO;IACHL,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClB,UAAQE;EACZ,CAAC;AACL"} \ No newline at end of file +{"version":3,"file":"storage-remote-helpers.js","names":["errorToPlainJson","createErrorAnswer","msg","error","connectionId","answerTo","requestId","method","createAnswer","ret"],"sources":["../../../../src/plugins/storage-remote/storage-remote-helpers.ts"],"sourcesContent":["import type {\n RxError,\n RxTypeError\n} from '../../types';\nimport { errorToPlainJson } from '../../plugins/utils';\nimport type {\n MessageFromRemote,\n MessageToRemote\n} from './storage-remote-types';\n\nexport function createErrorAnswer(\n msg: MessageToRemote,\n error: Error | TypeError | RxError | RxTypeError\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n error: errorToPlainJson(error)\n };\n}\n\nexport function createAnswer(\n msg: MessageToRemote,\n ret: any\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n return: ret\n };\n}\n"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,qBAAqB;AAMtD,OAAO,SAASC,iBAAiB,CAC7BC,GAAoB,EACpBC,KAAgD,EAC/B;EACjB,OAAO;IACHC,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClBJ,KAAK,EAAEH,gBAAgB,CAACG,KAAK;EACjC,CAAC;AACL;AAEA,OAAO,SAASK,YAAY,CACxBN,GAAoB,EACpBO,GAAQ,EACS;EACjB,OAAO;IACHL,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClB,UAAQE;EACZ,CAAC;AACL"} \ No newline at end of file diff --git a/dist/es/plugins/storage-remote/websocket.js b/dist/es/plugins/storage-remote/websocket.js index b085d918149..1005075ba81 100644 --- a/dist/es/plugins/storage-remote/websocket.js +++ b/dist/es/plugins/storage-remote/websocket.js @@ -1,5 +1,5 @@ import { Subject } from 'rxjs'; -import { getFromMapOrThrow } from '../../util'; +import { getFromMapOrThrow } from '../../plugins/utils'; import { getWebSocket, startSocketServer } from '../replication-websocket'; import { exposeRxStorageRemote } from './remote'; import { getRxStorageRemote } from './rx-storage-remote'; diff --git a/dist/es/plugins/storage-remote/websocket.js.map b/dist/es/plugins/storage-remote/websocket.js.map index 190adf6dfcf..eb3882f8920 100644 --- a/dist/es/plugins/storage-remote/websocket.js.map +++ b/dist/es/plugins/storage-remote/websocket.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket.js","names":["Subject","getFromMapOrThrow","getWebSocket","startSocketServer","exposeRxStorageRemote","getRxStorageRemote","createErrorAnswer","startRxStorageRemoteWebsocketServer","options","serverState","websocketByConnectionId","Map","messages$","exposeSettings","asObservable","storage","send","msg","ws","connectionId","JSON","stringify","exposeState","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","Error","set","next","WebsocketClientByUrl","getRxStorageRemoteWebsocket","identifier","url","websocketClientPromise","statics","then","websocketClient","socket","message$"],"sources":["../../../../src/plugins/storage-remote/websocket.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport type {\n RxStorage\n} from '../../types';\nimport {\n getFromMapOrThrow\n} from '../../util';\nimport {\n getWebSocket,\n startSocketServer,\n WebsocketWithRefCount\n} from '../replication-websocket';\nimport { exposeRxStorageRemote } from './remote';\nimport { getRxStorageRemote } from './rx-storage-remote';\nimport { createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './storage-remote-types';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (message.method !== 'create') {\n ws.send(JSON.stringify(createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))));\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\n\n\n/**\n * Reuse connections to the same url.\n * This makes testing easier because we do not run into a connection limit.\n * It might be better to instead track the amount of open storage instances\n * and open/close the websocket client depending on the counter.\n */\nconst WebsocketClientByUrl = new Map>();\n\nexport function getRxStorageRemoteWebsocket(options: RxStorageRemoteWebsocketClientOptions): RxStorage {\n const identifier = options.url + 'rx-remote-storage-websocket';\n const messages$ = new Subject();\n const websocketClientPromise = WebsocketClientByUrl.has(options.url) ?\n getFromMapOrThrow(WebsocketClientByUrl, options.url) :\n getWebSocket(options.url, identifier);\n WebsocketClientByUrl.set(options.url, websocketClientPromise);\n const storage = getRxStorageRemote({\n identifier,\n statics: options.statics,\n messages$,\n send(msg) {\n return websocketClientPromise\n .then(websocketClient => websocketClient.socket.send(JSON.stringify(msg)));\n }\n });\n websocketClientPromise.then((websocketClient) => {\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n });\n return storage;\n}\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,MAAM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IA,eAAe,CAACC,MAAM,CAAC9B,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;MAAA,EAAC;IAClF;EACJ,CAAC,CAAC;EACFyB,sBAAsB,CAACE,IAAI,CAAC,UAACC,eAAe,EAAK;IAC7CA,eAAe,CAACE,QAAQ,CAACvB,SAAS,CAAC,UAAAP,GAAG;MAAA,OAAIL,SAAS,CAACyB,IAAI,CAACpB,GAAG,CAAC;IAAA,EAAC;EAClE,CAAC,CAAC;EACF,OAAOF,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"websocket.js","names":["Subject","getFromMapOrThrow","getWebSocket","startSocketServer","exposeRxStorageRemote","getRxStorageRemote","createErrorAnswer","startRxStorageRemoteWebsocketServer","options","serverState","websocketByConnectionId","Map","messages$","exposeSettings","asObservable","storage","send","msg","ws","connectionId","JSON","stringify","exposeState","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","Error","set","next","WebsocketClientByUrl","getRxStorageRemoteWebsocket","identifier","url","websocketClientPromise","statics","then","websocketClient","socket","message$"],"sources":["../../../../src/plugins/storage-remote/websocket.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport type {\n RxStorage\n} from '../../types';\nimport {\n getFromMapOrThrow\n} from '../../plugins/utils';\nimport {\n getWebSocket,\n startSocketServer,\n WebsocketWithRefCount\n} from '../replication-websocket';\nimport { exposeRxStorageRemote } from './remote';\nimport { getRxStorageRemote } from './rx-storage-remote';\nimport { createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './storage-remote-types';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (message.method !== 'create') {\n ws.send(JSON.stringify(createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))));\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\n\n\n/**\n * Reuse connections to the same url.\n * This makes testing easier because we do not run into a connection limit.\n * It might be better to instead track the amount of open storage instances\n * and open/close the websocket client depending on the counter.\n */\nconst WebsocketClientByUrl = new Map>();\n\nexport function getRxStorageRemoteWebsocket(options: RxStorageRemoteWebsocketClientOptions): RxStorage {\n const identifier = options.url + 'rx-remote-storage-websocket';\n const messages$ = new Subject();\n const websocketClientPromise = WebsocketClientByUrl.has(options.url) ?\n getFromMapOrThrow(WebsocketClientByUrl, options.url) :\n getWebSocket(options.url, identifier);\n WebsocketClientByUrl.set(options.url, websocketClientPromise);\n const storage = getRxStorageRemote({\n identifier,\n statics: options.statics,\n messages$,\n send(msg) {\n return websocketClientPromise\n .then(websocketClient => websocketClient.socket.send(JSON.stringify(msg)));\n }\n });\n websocketClientPromise.then((websocketClient) => {\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n });\n return storage;\n}\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,MAAM;AAO9B,SACIC,iBAAiB,QACd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AAC9B,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;MAAA,EAAC;IAClF;EACJ,CAAC,CAAC;EACFyB,sBAAsB,CAACE,IAAI,CAAC,UAACC,eAAe,EAAK;IAC7CA,eAAe,CAACE,QAAQ,CAACvB,SAAS,CAAC,UAAAP,GAAG;MAAA,OAAIL,SAAS,CAACyB,IAAI,CAACpB,GAAG,CAAC;IAAA,EAAC;EAClE,CAAC,CAAC;EACF,OAAOF,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/worker/in-worker.js b/dist/es/plugins/storage-worker/in-worker.js similarity index 70% rename from dist/es/plugins/worker/in-worker.js rename to dist/es/plugins/storage-worker/in-worker.js index 7a74d70bfbf..56a3cb01569 100644 --- a/dist/es/plugins/worker/in-worker.js +++ b/dist/es/plugins/storage-worker/in-worker.js @@ -1,10 +1,12 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * This file contains everything * that is supposed to run inside of the worker. */ import { expose } from 'threads/worker'; -import { getFromMapOrThrow } from '../../util'; +import { getFromMapOrThrow } from '../utils'; export function wrappedWorkerRxStorage(args) { var nextId = 0; var instanceById = new Map(); @@ -12,17 +14,30 @@ export function wrappedWorkerRxStorage(args) { /** * RxStorageInstance */ - createStorageInstance: function createStorageInstance(params) { - try { - var _instanceId = nextId++; - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (instance) { - instanceById.set(_instanceId, instance); - return _instanceId; - }); - } catch (e) { - return Promise.reject(e); + createStorageInstance: function () { + var _createStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(params) { + var instanceId, instance; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + instanceId = nextId++; + _context.next = 3; + return args.storage.createStorageInstance(params); + case 3: + instance = _context.sent; + instanceById.set(instanceId, instance); + return _context.abrupt("return", instanceId); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - }, + return createStorageInstance; + }(), bulkWrite: function bulkWrite(instanceId, documentWrites, context) { var instance = getFromMapOrThrow(instanceById, instanceId); return instance.bulkWrite(documentWrites, context); diff --git a/dist/es/plugins/storage-worker/in-worker.js.map b/dist/es/plugins/storage-worker/in-worker.js.map new file mode 100644 index 00000000000..f48204185d3 --- /dev/null +++ b/dist/es/plugins/storage-worker/in-worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"in-worker.js","names":["expose","getFromMapOrThrow","wrappedWorkerRxStorage","args","nextId","instanceById","Map","exposeMe","createStorageInstance","params","instanceId","storage","instance","set","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","cleanup","minDeletedTime","close","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution"],"sources":["../../../../src/plugins/storage-worker/in-worker.ts"],"sourcesContent":["/**\n * This file contains everything\n * that is supposed to run inside of the worker.\n */\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types';\nimport { expose } from 'threads/worker';\nimport { getFromMapOrThrow } from '../utils';\nimport { Observable } from 'rxjs';\n\n\nexport type InWorkerStorage = {\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise;\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise>;\n findDocumentsById(\n instanceId: number,\n ids: string[], deleted: boolean\n ): Promise>;\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise>;\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise;\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise;\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }>;\n changeStream(\n instanceById: number\n ): Observable>, CheckpointType>>;\n cleanup(instanceId: number, minDeletedTime: number): Promise;\n close(instanceId: number): Promise;\n remove(instanceId: number): Promise;\n\n conflictResultionTasks(\n instanceById: number\n ): Observable>;\n resolveConflictResultionTask(\n instanceById: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise;\n};\n\nexport function wrappedWorkerRxStorage(\n args: {\n storage: RxStorage;\n }\n) {\n let nextId = 0;\n const instanceById: Map = new Map();\n\n const exposeMe: InWorkerStorage = {\n /**\n * RxStorageInstance\n */\n async createStorageInstance(params) {\n const instanceId = nextId++;\n const instance = await args.storage.createStorageInstance(params);\n instanceById.set(instanceId, instance);\n return instanceId;\n },\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.bulkWrite(documentWrites, context);\n },\n findDocumentsById(\n instanceId: number,\n ids: string[],\n deleted: boolean\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.findDocumentsById(ids, deleted);\n },\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.query(preparedQuery);\n },\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.count(preparedQuery);\n },\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getAttachmentData(\n documentId,\n attachmentId\n );\n },\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint: any\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getChangedDocumentsSince(\n limit,\n checkpoint\n );\n },\n changeStream(\n instanceId: number\n ): Observable>, CheckpointType>> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.changeStream();\n },\n cleanup(\n instanceId: number,\n minDeletedTime: number\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.cleanup(minDeletedTime);\n },\n close(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.close();\n },\n remove(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.remove();\n },\n\n conflictResultionTasks(\n instanceId: number\n ): Observable> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.conflictResultionTasks();\n },\n resolveConflictResultionTask(\n instanceId: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.resolveConflictResultionTask(taskSolution);\n }\n };\n expose(exposeMe);\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;;AAeA,SAASA,MAAM,QAAQ,gBAAgB;AACvC,SAASC,iBAAiB,QAAQ,UAAU;AAsD5C,OAAO,SAASC,sBAAsB,CAClCC,IAEC,EACH;EACE,IAAIC,MAAM,GAAG,CAAC;EACd,IAAMC,YAA8B,GAAG,IAAIC,GAAG,EAAE;EAEhD,IAAMC,QAA8C,GAAG;IACnD;AACR;AACA;IACcC,qBAAqB;MAAA,uGAACC,MAAM;QAAA;QAAA;UAAA;YAAA;cACxBC,UAAU,GAAGN,MAAM,EAAE;cAAA;cAAA,OACJD,IAAI,CAACQ,OAAO,CAACH,qBAAqB,CAACC,MAAM,CAAC;YAAA;cAA3DG,QAAQ;cACdP,YAAY,CAACQ,GAAG,CAACH,UAAU,EAAEE,QAAQ,CAAC;cAAC,iCAChCF,UAAU;YAAA;YAAA;cAAA;UAAA;QAAA;MAAA;MAAA;QAAA;MAAA;MAAA;IAAA;IAErBI,SAAS,qBACLJ,UAAkB,EAClBK,cAA4C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EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACiB,YAAY,EAAE;IAClC,CAAC;IACDC,OAAO,mBACHpB,UAAkB,EAClBqB,cAAsB,EACxB;MACE,IAAMnB,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACkB,OAAO,CAACC,cAAc,CAAC;IAC3C,CAAC;IACDC,KAAK,iBAACtB,UAAkB,EAAE;MACtB,IAAME,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACoB,KAAK,EAAE;IAC3B,CAAC;IACDC,MAAM,kBAACvB,UAAkB,EAAE;MACvB,IAAME,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACqB,MAAM,EAAE;IAC5B,CAAC;IAEDC,sBAAsB,kCAClBxB,UAAkB,EAC4B;MAC9C,IAAME,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACsB,sBAAsB,EAAE;IAC5C,CAAC;IACDC,4BAA4B,wCACxBzB,UAAkB,EAClB0B,YAAwD,EAC3C;MACb,IAAMxB,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACuB,4BAA4B,CAACC,YAAY,CAAC;IAC9D;EACJ,CAAC;EACDpC,MAAM,CAACO,QAAQ,CAAC;AACpB"} \ No newline at end of file diff --git a/dist/es/plugins/worker/index.js b/dist/es/plugins/storage-worker/index.js similarity index 100% rename from dist/es/plugins/worker/index.js rename to dist/es/plugins/storage-worker/index.js diff --git a/dist/es/plugins/storage-worker/index.js.map b/dist/es/plugins/storage-worker/index.js.map new file mode 100644 index 00000000000..7864fb99862 --- /dev/null +++ b/dist/es/plugins/storage-worker/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/storage-worker/index.ts"],"sourcesContent":["export * from './in-worker';\nexport * from './non-worker';\n"],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,cAAc"} \ No newline at end of file diff --git a/dist/es/plugins/worker/non-worker.js b/dist/es/plugins/storage-worker/non-worker.js similarity index 52% rename from dist/es/plugins/worker/non-worker.js rename to dist/es/plugins/storage-worker/non-worker.js index addfafa3d03..8a77ced1538 100644 --- a/dist/es/plugins/worker/non-worker.js +++ b/dist/es/plugins/storage-worker/non-worker.js @@ -1,30 +1,8 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { Subject } from 'rxjs'; import { spawn, Worker, Thread } from 'threads'; -import { ensureNotFalsy, getFromMapOrThrow } from '../../util'; -/** - * TODO we have a bug. - * When the exact same RxStorage opens and closes - * many RxStorage instances, then it might happen - * that some calls to createStorageInstance() time out, - * because the worker thread is in the closing state. - */ -export var removeWorkerRef = function removeWorkerRef(instance) { - try { - var workerState = getFromMapOrThrow(WORKER_BY_INSTANCE, instance.storage); - workerState.refs["delete"](instance); - var _temp = function () { - if (workerState.refs.size === 0) { - WORKER_BY_INSTANCE["delete"](instance.storage); - return Promise.resolve(workerState.workerPromise.then(function (worker) { - return Thread.terminate(worker); - })).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; +import { ensureNotFalsy, getFromMapOrThrow } from '../../plugins/utils'; /** * We have no way to detect if a worker is no longer needed. * So we create the worker process on the first RxStorageInstance @@ -112,49 +90,120 @@ export var RxStorageInstanceWorker = /*#__PURE__*/function () { _proto2.cleanup = function cleanup(minDeletedTime) { return this.internals.worker.cleanup(this.internals.instanceId, minDeletedTime); }; - _proto2.close = function close() { - try { - var _this3 = this; - if (_this3.closed) { - return Promise.reject(new Error('already closed')); - } - _this3.closed = true; - _this3.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - return Promise.resolve(_this3.internals.worker.close(_this3.internals.instanceId)).then(function () { - return Promise.resolve(removeWorkerRef(_this3)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + _proto2.close = /*#__PURE__*/function () { + var _close = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!this.closed) { + _context.next = 2; + break; + } + return _context.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + _context.next = 6; + return this.internals.worker.close(this.internals.instanceId); + case 6: + _context.next = 8; + return removeWorkerRef(this); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function close() { + return _close.apply(this, arguments); } - }; - _proto2.remove = function remove() { - try { - var _this4 = this; - return Promise.resolve(_this4.internals.worker.remove(_this4.internals.instanceId)).then(function () { - _this4.closed = true; - return Promise.resolve(removeWorkerRef(_this4)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + return close; + }(); + _proto2.remove = /*#__PURE__*/function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.internals.worker.remove(this.internals.instanceId); + case 2: + this.closed = true; + _context2.next = 5; + return removeWorkerRef(this); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _proto2.conflictResultionTasks = function conflictResultionTasks() { return this.conflicts$; }; - _proto2.resolveConflictResultionTask = function resolveConflictResultionTask(taskSolution) { - try { - var _this5 = this; - return Promise.resolve(_this5.internals.worker.resolveConflictResultionTask(_this5.internals.instanceId, taskSolution)).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto2.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(taskSolution) { + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.internals.worker.resolveConflictResultionTask(this.internals.instanceId, taskSolution); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveConflictResultionTask(_x) { + return _resolveConflictResultionTask.apply(this, arguments); } - }; + return resolveConflictResultionTask; + }(); return RxStorageInstanceWorker; }(); export function getRxStorageWorker(settings) { var storage = new RxStorageWorker(settings, settings.statics); return storage; } + +/** + * TODO we have a bug. + * When the exact same RxStorage opens and closes + * many RxStorage instances, then it might happen + * that some calls to createStorageInstance() time out, + * because the worker thread is in the closing state. + */ +export function removeWorkerRef(_x2) { + return _removeWorkerRef.apply(this, arguments); +} +function _removeWorkerRef() { + _removeWorkerRef = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(instance) { + var workerState; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + workerState = getFromMapOrThrow(WORKER_BY_INSTANCE, instance.storage); + workerState.refs["delete"](instance); + if (!(workerState.refs.size === 0)) { + _context4.next = 6; + break; + } + WORKER_BY_INSTANCE["delete"](instance.storage); + _context4.next = 6; + return workerState.workerPromise.then(function (worker) { + return Thread.terminate(worker); + }); + case 6: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _removeWorkerRef.apply(this, arguments); +} //# sourceMappingURL=non-worker.js.map \ No newline at end of file diff --git a/dist/es/plugins/storage-worker/non-worker.js.map b/dist/es/plugins/storage-worker/non-worker.js.map new file mode 100644 index 00000000000..cbf72575f48 --- /dev/null +++ b/dist/es/plugins/storage-worker/non-worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"non-worker.js","names":["Subject","spawn","Worker","Thread","ensureNotFalsy","getFromMapOrThrow","WORKER_BY_INSTANCE","Map","RxStorageWorker","settings","statics","name","createStorageInstance","params","workerState","get","workerPromise","workerInput","refs","Set","set","then","worker","instanceId","instance","RxStorageInstanceWorker","databaseName","collectionName","schema","rxStorage","options","add","storage","internals","changes$","conflicts$","subs","closed","push","changeStream","subscribe","ev","next","conflictResultionTasks","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","asObservable","cleanup","minDeletedTime","close","Promise","reject","Error","forEach","sub","unsubscribe","removeWorkerRef","remove","resolveConflictResultionTask","taskSolution","getRxStorageWorker","size","terminate"],"sources":["../../../../src/plugins/storage-worker/non-worker.ts"],"sourcesContent":["import {\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n spawn,\n Worker,\n Thread\n} from 'threads';\nimport type {\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageInstance,\n BulkWriteRow,\n RxDocumentData,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageQueryResult,\n EventBulk,\n RxStorageStatics,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageCountResult\n} from '../../types';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from '../../plugins/utils';\nimport { InWorkerStorage } from './in-worker';\n\ndeclare type WorkerStorageInternals = {\n rxStorage: RxStorageWorker;\n instanceId: number;\n worker: InWorkerStorage;\n};\ndeclare type RxStorageWorkerSettings = {\n statics: RxStorageStatics;\n workerInput: any;\n};\n\n\n/**\n * We have no way to detect if a worker is no longer needed.\n * So we create the worker process on the first RxStorageInstance\n * and have to close it again of no more RxStorageInstances are non-closed.\n */\nconst WORKER_BY_INSTANCE: Map>;\n refs: Set>;\n}> = new Map();\n\nexport class RxStorageWorker implements RxStorage {\n public name = 'worker';\n\n constructor(\n public readonly settings: RxStorageWorkerSettings,\n public readonly statics: RxStorageStatics\n ) { }\n\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n let workerState = WORKER_BY_INSTANCE.get(this);\n if (!workerState) {\n workerState = {\n workerPromise: spawn>(new Worker(this.settings.workerInput)) as any,\n refs: new Set()\n };\n WORKER_BY_INSTANCE.set(this, workerState);\n }\n\n return workerState.workerPromise.then(worker => {\n return worker.createStorageInstance(params)\n .then(instanceId => {\n const instance = new RxStorageInstanceWorker(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n rxStorage: this,\n instanceId,\n worker\n },\n params.options\n );\n ensureNotFalsy(workerState).refs.add(instance);\n return instance;\n });\n });\n }\n}\n\n\nexport class RxStorageInstanceWorker implements RxStorageInstance {\n /**\n * threads.js uses observable-fns instead of rxjs\n * so we have to transform it.\n */\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n\n constructor(\n public readonly storage: RxStorageWorker,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: WorkerStorageInternals,\n public readonly options: Readonly\n ) {\n this.subs.push(\n this.internals.worker.changeStream(\n this.internals.instanceId\n ).subscribe(ev => this.changes$.next(ev as any))\n );\n this.subs.push(\n this.internals.worker.conflictResultionTasks(\n this.internals.instanceId\n ).subscribe(ev => this.conflicts$.next(ev as any))\n );\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.internals.worker.bulkWrite(\n this.internals.instanceId,\n documentWrites,\n context\n );\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.internals.worker.findDocumentsById(\n this.internals.instanceId,\n ids,\n deleted\n );\n }\n query(preparedQuery: any): Promise> {\n return this.internals.worker.query(\n this.internals.instanceId,\n preparedQuery\n );\n }\n count(preparedQuery: any): Promise {\n return this.internals.worker.count(\n this.internals.instanceId,\n preparedQuery\n );\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.internals.worker.getAttachmentData(\n this.internals.instanceId,\n documentId,\n attachmentId\n );\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ) {\n return this.internals.worker.getChangedDocumentsSince(\n this.internals.instanceId,\n limit,\n checkpoint\n );\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number) {\n return this.internals.worker.cleanup(\n this.internals.instanceId,\n minDeletedTime\n );\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n await this.internals.worker.close(\n this.internals.instanceId\n );\n await removeWorkerRef(this);\n }\n async remove(): Promise {\n await this.internals.worker.remove(\n this.internals.instanceId\n );\n this.closed = true;\n await removeWorkerRef(this);\n }\n\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.internals.worker.resolveConflictResultionTask(\n this.internals.instanceId,\n taskSolution\n );\n }\n\n}\n\nexport function getRxStorageWorker(\n settings: RxStorageWorkerSettings\n): RxStorageWorker {\n const storage = new RxStorageWorker(settings, settings.statics);\n return storage;\n}\n\n/**\n * TODO we have a bug.\n * When the exact same RxStorage opens and closes\n * many RxStorage instances, then it might happen\n * that some calls to createStorageInstance() time out,\n * because the worker thread is in the closing state.\n */\nexport async function removeWorkerRef(\n instance: RxStorageInstanceWorker\n) {\n const workerState = getFromMapOrThrow(WORKER_BY_INSTANCE, instance.storage);\n workerState.refs.delete(instance);\n if (workerState.refs.size === 0) {\n WORKER_BY_INSTANCE.delete(instance.storage);\n await workerState.workerPromise\n .then(worker => Thread.terminate(worker as any));\n }\n}\n"],"mappings":";;AAAA,SAEIA,OAAO,QAEJ,MAAM;AACb,SACIC,KAAK,EACLC,MAAM,EACNC,MAAM,QACH,SAAS;AAkBhB,SACIC,cAAc,EACdC,iBAAiB,QACd,qBAAqB;AAc5B;AACA;AACA;AACA;AACA;AACA,IAAMC,k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EAAEA,QAAQ,CAACC,OAAO,CAAC;EAC/D,OAAOsB,OAAO;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAsBqC,eAAe;EAAA;AAAA;AAUpC;EAAA,4EAVM,kBACH7C,QAAsC;IAAA;IAAA;MAAA;QAAA;UAEhCV,WAAW,GAAGT,iBAAiB,CAACC,kBAAkB,EAAEkB,QAAQ,CAACQ,OAAO,CAAC;UAC3ElB,WAAW,CAACI,IAAI,UAAO,CAACM,QAAQ,CAAC;UAAC,MAC9BV,WAAW,CAACI,IAAI,CAACwD,IAAI,KAAK,CAAC;YAAA;YAAA;UAAA;UAC3BpE,kBAAkB,UAAO,CAACkB,QAAQ,CAACQ,OAAO,CAAC;UAAC;UAAA,OACtClB,WAAW,CAACE,aAAa,CAC1BK,IAAI,CAAC,UAAAC,MAAM;YAAA,OAAInB,MAAM,CAACwE,SAAS,CAACrD,MAAM,CAAQ;UAAA,EAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAE3D;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/dexie-memory.worker.js b/dist/es/plugins/storage-worker/workers/dexie-memory.worker.js similarity index 66% rename from dist/es/plugins/worker/workers/dexie-memory.worker.js rename to dist/es/plugins/storage-worker/workers/dexie-memory.worker.js index 150cfab7773..e92285f9f1e 100644 --- a/dist/es/plugins/worker/workers/dexie-memory.worker.js +++ b/dist/es/plugins/storage-worker/workers/dexie-memory.worker.js @@ -1,5 +1,5 @@ -import { getRxStorageDexie } from '../../dexie'; -import { wrappedWorkerRxStorage } from '../../worker'; +import { getRxStorageDexie } from '../../storage-dexie'; +import { wrappedWorkerRxStorage } from '../../storage-worker'; import { indexedDB, IDBKeyRange } from 'fake-indexeddb'; var storage = getRxStorageDexie({ indexedDB: indexedDB, diff --git a/dist/es/plugins/storage-worker/workers/dexie-memory.worker.js.map b/dist/es/plugins/storage-worker/workers/dexie-memory.worker.js.map new file mode 100644 index 00000000000..77cf2cdc79e --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/dexie-memory.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-memory.worker.js","names":["getRxStorageDexie","wrappedWorkerRxStorage","indexedDB","IDBKeyRange","storage"],"sources":["../../../../../src/plugins/storage-worker/workers/dexie-memory.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../storage-dexie';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nimport {\n indexedDB,\n IDBKeyRange\n} from 'fake-indexeddb';\n\nconst storage = getRxStorageDexie({\n indexedDB,\n IDBKeyRange\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AACvD,SAASC,sBAAsB,QAAQ,sBAAsB;AAE7D,SACIC,SAAS,EACTC,WAAW,QACR,gBAAgB;AAEvB,IAAMC,OAAO,GAAGJ,iBAAiB,CAAC;EAC9BE,SAAS,EAATA,SAAS;EACTC,WAAW,EAAXA;AACJ,CAAC,CAAC;AACFF,sBAAsB,CAAC;EACnBG,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/dexie.worker.js b/dist/es/plugins/storage-worker/workers/dexie.worker.js similarity index 50% rename from dist/es/plugins/worker/workers/dexie.worker.js rename to dist/es/plugins/storage-worker/workers/dexie.worker.js index 45b1fdc458b..dbeccc1e21a 100644 --- a/dist/es/plugins/worker/workers/dexie.worker.js +++ b/dist/es/plugins/storage-worker/workers/dexie.worker.js @@ -1,5 +1,5 @@ -import { getRxStorageDexie } from '../../dexie'; -import { wrappedWorkerRxStorage } from '../../worker'; +import { getRxStorageDexie } from '../../storage-dexie'; +import { wrappedWorkerRxStorage } from '../../storage-worker'; var storage = getRxStorageDexie(); wrappedWorkerRxStorage({ storage: storage diff --git a/dist/es/plugins/storage-worker/workers/dexie.worker.js.map b/dist/es/plugins/storage-worker/workers/dexie.worker.js.map new file mode 100644 index 00000000000..fcfa7133100 --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/dexie.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.worker.js","names":["getRxStorageDexie","wrappedWorkerRxStorage","storage"],"sources":["../../../../../src/plugins/storage-worker/workers/dexie.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../storage-dexie';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nconst storage = getRxStorageDexie();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AACvD,SAASC,sBAAsB,QAAQ,sBAAsB;AAE7D,IAAMC,OAAO,GAAGF,iBAAiB,EAAE;AACnCC,sBAAsB,CAAC;EACnBC,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-fs.worker.js b/dist/es/plugins/storage-worker/workers/lokijs-fs.worker.js similarity index 66% rename from dist/es/plugins/worker/workers/lokijs-fs.worker.js rename to dist/es/plugins/storage-worker/workers/lokijs-fs.worker.js index 10ccb4b7af5..02948f552c7 100644 --- a/dist/es/plugins/worker/workers/lokijs-fs.worker.js +++ b/dist/es/plugins/storage-worker/workers/lokijs-fs.worker.js @@ -1,5 +1,5 @@ -import { getRxStorageLoki } from '../../lokijs'; -import { wrappedWorkerRxStorage } from '../../worker'; +import { getRxStorageLoki } from '../../storage-lokijs'; +import { wrappedWorkerRxStorage } from '../../storage-worker'; var lfsa = require('lokijs/src/loki-fs-structured-adapter.js'); var adapter = new lfsa(); var storage = getRxStorageLoki({ diff --git a/dist/es/plugins/storage-worker/workers/lokijs-fs.worker.js.map b/dist/es/plugins/storage-worker/workers/lokijs-fs.worker.js.map new file mode 100644 index 00000000000..f07b97cb0d9 --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/lokijs-fs.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-fs.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","lfsa","require","adapter","storage"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-fs.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nconst lfsa = require('lokijs/src/loki-fs-structured-adapter.js');\nconst adapter = new lfsa();\nconst storage = getRxStorageLoki({\n adapter\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,sBAAsB;AACvD,SAASC,sBAAsB,QAAQ,sBAAsB;AAE7D,IAAMC,IAAI,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAChE,IAAMC,OAAO,GAAG,IAAIF,IAAI,EAAE;AAC1B,IAAMG,OAAO,GAAGL,gBAAgB,CAAC;EAC7BI,OAAO,EAAPA;AACJ,CAAC,CAAC;AACFH,sBAAsB,CAAC;EACnBI,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js b/dist/es/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js similarity index 70% rename from dist/es/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js rename to dist/es/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js index 54e18f9ca96..83f7858d810 100644 --- a/dist/es/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js +++ b/dist/es/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js @@ -1,5 +1,5 @@ -import { getRxStorageLoki } from '../../lokijs'; -import { wrappedWorkerRxStorage } from '../../worker'; +import { getRxStorageLoki } from '../../storage-lokijs'; +import { wrappedWorkerRxStorage } from '../../storage-worker'; var LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter'); var storage = getRxStorageLoki({ adapter: new LokiIncrementalIndexedDBAdapter() diff --git a/dist/es/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js.map b/dist/es/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js.map new file mode 100644 index 00000000000..81d0e03bcab --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-incremental-indexeddb.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","LokiIncrementalIndexedDBAdapter","require","storage","adapter"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\nconst LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIncrementalIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,sBAAsB;AACvD,SAASC,sBAAsB,QAAQ,sBAAsB;AAC7D,IAAMC,+BAA+B,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAE3F,IAAMC,OAAO,GAAGJ,gBAAgB,CAAC;EAC7BK,OAAO,EAAE,IAAIH,+BAA+B;AAChD,CAAC,CAAC;AACFD,sBAAsB,CAAC;EACnBG,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-indexeddb.worker.js b/dist/es/plugins/storage-worker/workers/lokijs-indexeddb.worker.js similarity index 67% rename from dist/es/plugins/worker/workers/lokijs-indexeddb.worker.js rename to dist/es/plugins/storage-worker/workers/lokijs-indexeddb.worker.js index f96f03c9c77..d73cc6182f5 100644 --- a/dist/es/plugins/worker/workers/lokijs-indexeddb.worker.js +++ b/dist/es/plugins/storage-worker/workers/lokijs-indexeddb.worker.js @@ -1,5 +1,5 @@ -import { getRxStorageLoki } from '../../lokijs'; -import { wrappedWorkerRxStorage } from '../../worker'; +import { getRxStorageLoki } from '../../storage-lokijs'; +import { wrappedWorkerRxStorage } from '../../storage-worker'; var LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter'); var storage = getRxStorageLoki({ adapter: new LokiIndexedDBAdapter() diff --git a/dist/es/plugins/storage-worker/workers/lokijs-indexeddb.worker.js.map b/dist/es/plugins/storage-worker/workers/lokijs-indexeddb.worker.js.map new file mode 100644 index 00000000000..281eb857597 --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/lokijs-indexeddb.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-indexeddb.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","LokiIndexedDBAdapter","require","storage","adapter"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\nconst LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,sBAAsB;AACvD,SAASC,sBAAsB,QAAQ,sBAAsB;AAC7D,IAAMC,oBAAoB,GAAGC,OAAO,CAAC,iCAAiC,CAAC;AAEvE,IAAMC,OAAO,GAAGJ,gBAAgB,CAAC;EAC7BK,OAAO,EAAE,IAAIH,oBAAoB;AACrC,CAAC,CAAC;AACFD,sBAAsB,CAAC;EACnBG,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-memory.worker.js b/dist/es/plugins/storage-worker/workers/lokijs-memory.worker.js similarity index 52% rename from dist/es/plugins/worker/workers/lokijs-memory.worker.js rename to dist/es/plugins/storage-worker/workers/lokijs-memory.worker.js index 154d5ad0723..72b0b5fbf0f 100644 --- a/dist/es/plugins/worker/workers/lokijs-memory.worker.js +++ b/dist/es/plugins/storage-worker/workers/lokijs-memory.worker.js @@ -1,5 +1,5 @@ -import { getRxStorageLoki } from '../../lokijs'; -import { wrappedWorkerRxStorage } from '../../worker'; +import { getRxStorageLoki } from '../../storage-lokijs'; +import { wrappedWorkerRxStorage } from '../../storage-worker'; var storage = getRxStorageLoki(); wrappedWorkerRxStorage({ storage: storage diff --git a/dist/es/plugins/storage-worker/workers/lokijs-memory.worker.js.map b/dist/es/plugins/storage-worker/workers/lokijs-memory.worker.js.map new file mode 100644 index 00000000000..db3ca6c9d20 --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/lokijs-memory.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-memory.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","storage"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-memory.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nconst storage = getRxStorageLoki();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,sBAAsB;AACvD,SAASC,sBAAsB,QAAQ,sBAAsB;AAE7D,IAAMC,OAAO,GAAGF,gBAAgB,EAAE;AAClCC,sBAAsB,CAAC;EACnBC,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/webpack.config.js b/dist/es/plugins/storage-worker/workers/webpack.config.js similarity index 71% rename from dist/es/plugins/worker/workers/webpack.config.js rename to dist/es/plugins/storage-worker/workers/webpack.config.js index d3a6313b5ec..2f00a7fc6fa 100644 --- a/dist/es/plugins/worker/workers/webpack.config.js +++ b/dist/es/plugins/storage-worker/workers/webpack.config.js @@ -4,14 +4,12 @@ var projectRootPath = path.resolve(__dirname, '../../../../'); var babelConfig = require('../../../../babel.config'); module.exports = { entry: { - 'lokijs-incremental-indexeddb': './src/plugins/worker/workers/lokijs-incremental-indexeddb.worker.ts', - 'lokijs-indexeddb': './src/plugins/worker/workers/lokijs-indexeddb.worker.ts', - 'lokijs-memory': './src/plugins/worker/workers/lokijs-memory.worker.ts', - 'lokijs-fs': './src/plugins/worker/workers/lokijs-fs.worker.ts', - 'pouchdb-idb': './src/plugins/worker/workers/pouchdb-idb.worker.ts', - 'pouchdb-memory': './src/plugins/worker/workers/pouchdb-memory.worker.ts', - 'dexie': './src/plugins/worker/workers/dexie.worker.ts', - 'dexie-memory': './src/plugins/worker/workers/dexie-memory.worker.ts' + 'lokijs-incremental-indexeddb': './src/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.ts', + 'lokijs-indexeddb': './src/plugins/storage-worker/workers/lokijs-indexeddb.worker.ts', + 'lokijs-memory': './src/plugins/storage-worker/workers/lokijs-memory.worker.ts', + 'lokijs-fs': './src/plugins/storage-worker/workers/lokijs-fs.worker.ts', + 'dexie': './src/plugins/storage-worker/workers/dexie.worker.ts', + 'dexie-memory': './src/plugins/storage-worker/workers/dexie-memory.worker.ts' }, output: { filename: '[name].worker.js', diff --git a/dist/es/plugins/storage-worker/workers/webpack.config.js.map b/dist/es/plugins/storage-worker/workers/webpack.config.js.map new file mode 100644 index 00000000000..38099306696 --- /dev/null +++ b/dist/es/plugins/storage-worker/workers/webpack.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webpack.config.js","names":["path","require","TerserPlugin","projectRootPath","resolve","__dirname","babelConfig","module","exports","entry","output","filename","clean","mode","cache","type","cacheDirectory","devtool","rules","test","exclude","use","loader","options","extensions","fallback","fs","optimization","moduleIds","minimize","minimizer","terserOptions","format","comments","extractComments"],"sources":["../../../../../src/plugins/storage-worker/workers/webpack.config.js"],"sourcesContent":["const path = require('path');\nconst TerserPlugin = require('terser-webpack-plugin');\n\nconst projectRootPath = path.resolve(\n __dirname,\n '../../../../'\n);\n\nconst babelConfig = require('../../../../babel.config');\nmodule.exports = {\n entry: {\n 'lokijs-incremental-indexeddb': './src/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.ts',\n 'lokijs-indexeddb': './src/plugins/storage-worker/workers/lokijs-indexeddb.worker.ts',\n 'lokijs-memory': './src/plugins/storage-worker/workers/lokijs-memory.worker.ts',\n 'lokijs-fs': './src/plugins/storage-worker/workers/lokijs-fs.worker.ts',\n 'dexie': './src/plugins/storage-worker/workers/dexie.worker.ts',\n 'dexie-memory': './src/plugins/storage-worker/workers/dexie-memory.worker.ts'\n },\n output: {\n filename: '[name].worker.js',\n clean: true,\n path: path.resolve(\n projectRootPath,\n 'dist/workers'\n ),\n },\n mode: 'production',\n cache: {\n type: 'filesystem',\n cacheDirectory: path.resolve(\n projectRootPath,\n 'test_tmp',\n 'webpack-cache-worker'\n ),\n },\n devtool: 'source-map',\n module: {\n rules: [\n /**\n * We transpile the typscript via babel instead of ts-loader.\n * This ensures we have the exact same babel config\n * as the root RxDB project.\n */\n {\n test: /\\.tsx?$/,\n exclude: /(node_modules)/,\n use: {\n loader: 'babel-loader',\n options: babelConfig\n },\n }\n ],\n },\n resolve: {\n extensions: ['.tsx', '.ts', '.js'],\n /**\n * Fix LokiJS bundle error\n * @link https://rxdb.info/rx-storage-lokijs.html\n */\n fallback: {\n fs: false\n }\n },\n optimization: {\n moduleIds: 'deterministic',\n minimize: true,\n minimizer: [new TerserPlugin({\n terserOptions: {\n format: {\n comments: false,\n },\n },\n /**\n * Disable creating the license files.\n * @link https://github.com/webpack/webpack/issues/12506#issuecomment-789314176\n */\n extractComments: false,\n })],\n }\n};\n"],"mappings":"AAAA,IAAMA,IAAI,GAAGC,OAAO,CAAC,MAAM,CAAC;AAC5B,IAAMC,YAAY,GAAGD,OAAO,CAAC,uBAAuB,CAAC;AAErD,IAAME,eAAe,GAAGH,IAAI,CAACI,OAAO,CAChCC,SAAS,EACT,cAAc,CACjB;AAED,IAAMC,WAAW,GAAGL,OAAO,CAAC,0BAA0B,CAAC;AACvDM,MAAM,CAACC,OAAO,GAAG;EACbC,KAAK,EAAE;IACH,8BAA8B,EAAE,6EAA6E;IAC7G,kBAAkB,EAAE,iEAAiE;IACrF,eAAe,EAAE,8DAA8D;IAC/E,WAAW,EAAE,0DAA0D;IACvE,OAAO,EAAE,sDAAsD;IAC/D,cAAc,EAAE;EACpB,CAAC;EACDC,MAAM,EAAE;IACJC,QAAQ,EAAE,kBAAkB;IAC5BC,KAAK,EAAE,IAAI;IACXZ,IAAI,EAAEA,IAAI,CAACI,OAAO,CACdD,eAAe,EACf,cAAc;EAEtB,CAAC;EACDU,IAAI,EAAE,YAAY;EAClBC,KAAK,EAAE;IACHC,IAAI,EAAE,YAAY;IAClBC,cAAc,EAAEhB,IAAI,CAACI,OAAO,CACxBD,eAAe,EACf,UAAU,EACV,sBAAsB;EAE9B,CAAC;EACDc,OAAO,EAAE,YAAY;EACrBV,MAAM,EAAE;IACJW,KAAK,EAAE;IACH;AACZ;AACA;AACA;AACA;IACY;MACIC,IAAI,EAAE,SAAS;MACfC,OAAO,EAAE,gBAAgB;MACzBC,GAAG,EAAE;QACDC,MAAM,EAAE,cAAc;QACtBC,OAAO,EAAEjB;MACb;IACJ,CAAC;EAET,CAAC;EACDF,OAAO,EAAE;IACLoB,UAAU,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC;IAClC;AACR;AACA;AACA;IACQC,QAAQ,EAAE;MACNC,EAAE,EAAE;IACR;EACJ,CAAC;EACDC,YAAY,EAAE;IACVC,SAAS,EAAE,eAAe;IAC1BC,QAAQ,EAAE,IAAI;IACdC,SAAS,EAAE,CAAC,IAAI5B,YAAY,CAAC;MACzB6B,aAAa,EAAE;QACXC,MAAM,EAAE;UACJC,QAAQ,EAAE;QACd;MACJ,CAAC;MACD;AACZ;AACA;AACA;MACYC,eAAe,EAAE;IACrB,CAAC,CAAC;EACN;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/update/index.js b/dist/es/plugins/update/index.js index 9dc940fd7bf..b8b316340f6 100644 --- a/dist/es/plugins/update/index.js +++ b/dist/es/plugins/update/index.js @@ -4,6 +4,12 @@ * @link https://github.com/lgandecki/modifyjs */ import modifyjs from 'modifyjs'; +export function incrementalUpdate(updateObj) { + return this.incrementalModify(function (docData) { + var newDocData = modifyjs(docData, updateObj); + return newDocData; + }); +} export function update(updateObj) { var oldDocData = this._data; var newDocData = modifyjs(oldDocData, updateObj); @@ -34,6 +40,7 @@ export var RxDBUpdatePlugin = { prototypes: { RxDocument: function RxDocument(proto) { proto.update = update; + proto.incrementalUpdate = incrementalUpdate; }, RxQuery: function RxQuery(proto) { proto.update = RxQueryUpdate; diff --git a/dist/es/plugins/update/index.js.map b/dist/es/plugins/update/index.js.map index 9946e3342a0..d26fbf751d5 100644 --- a/dist/es/plugins/update/index.js.map +++ b/dist/es/plugins/update/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["modifyjs","update","updateObj","oldDocData","_data","newDocData","_saveData","RxQueryUpdate","exec","then","docs","Array","isArray","Promise","all","map","doc","RxDBUpdatePlugin","name","rxdb","prototypes","RxDocument","proto","RxQuery"],"sources":["../../../../src/plugins/update/index.ts"],"sourcesContent":["/**\n * this plugin allows delta-updates with mongo-like-syntax\n * It's using modifyjs internally\n * @link https://github.com/lgandecki/modifyjs\n */\nimport modifyjs from 'modifyjs';\nimport type {\n RxDocument,\n RxQuery,\n RxPlugin,\n UpdateQuery\n} from '../../types';\n\nexport function update(this: RxDocument, updateObj: any) {\n const oldDocData = this._data;\n const newDocData = modifyjs(oldDocData, updateObj);\n return this._saveData(newDocData, oldDocData);\n}\n\nexport function RxQueryUpdate(\n this: RxQuery,\n updateObj: UpdateQuery\n): Promise {\n return this.exec()\n .then(docs => {\n if (!docs) {\n return null;\n }\n if (Array.isArray(docs)) {\n return Promise.all(\n docs.map(doc => doc.update(updateObj))\n ).then(() => docs);\n } else {\n // via findOne()\n return docs.update(updateObj).then(() => docs);\n }\n });\n}\n\n\nexport const RxDBUpdatePlugin: RxPlugin = {\n name: 'update',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.update = update;\n },\n RxQuery: (proto: any) => {\n proto.update = RxQueryUpdate;\n }\n }\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,QAAQ,MAAM,UAAU;AAQ/B,OAAO,SAASC,MAAM,CAAmBC,SAAc,EAAE;EACrD,IAAMC,UAAU,GAAG,IAAI,CAACC,KAAK;EAC7B,IAAMC,UAAU,GAAGL,QAAQ,CAACG,UAAU,EAAED,SAAS,CAAC;EAClD,OAAO,IAAI,CAACI,SAAS,CAACD,UAAU,EAAEF,UAAU,CAAC;AACjD;AAEA,OAAO,SAASI,aAAa,CAEzBL,SAA2B,EACf;EACZ,OAAO,IAAI,CAACM,IAAI,EAAE,CACbC,IAAI,CAAC,UAAAC,IAAI,EAAI;IACV,IAAI,CAACA,IAAI,EAAE;MACP,OAAO,IAAI;IACf;IACA,IAAIC,KAAK,CAACC,OAAO,CAACF,IAAI,CAAC,EAAE;MACrB,OAAOG,OAAO,CAACC,GAAG,CACdJ,IAAI,CAACK,GAAG,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACf,MAAM,CAACC,SAAS,CAAC;MAAA,EAAC,CACzC,CAACO,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IACtB,CAAC,MAAM;MACH;MACA,OAAOA,IAAI,CAACT,MAAM,CAACC,SAAS,CAAC,CAACO,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IAClD;EACJ,CAAC,CAAC;AACV;AAGA,OAAO,IAAMO,gBAA0B,GAAG;EACtCC,IAAI,EAAE,QAAQ;EACdC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACrB,MAAM,GAAGA,MAAM;IACzB,CAAC;IACDsB,OAAO,EAAE,iBAACD,KAAU,EAAK;MACrBA,KAAK,CAACrB,MAAM,GAAGM,aAAa;IAChC;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["modifyjs","incrementalUpdate","updateObj","incrementalModify","docData","newDocData","update","oldDocData","_data","_saveData","RxQueryUpdate","exec","then","docs","Array","isArray","Promise","all","map","doc","RxDBUpdatePlugin","name","rxdb","prototypes","RxDocument","proto","RxQuery"],"sources":["../../../../src/plugins/update/index.ts"],"sourcesContent":["/**\n * this plugin allows delta-updates with mongo-like-syntax\n * It's using modifyjs internally\n * @link https://github.com/lgandecki/modifyjs\n */\nimport modifyjs from 'modifyjs';\nimport type {\n RxDocument,\n RxQuery,\n RxPlugin,\n UpdateQuery\n} from '../../types';\n\nexport function incrementalUpdate(\n this: RxDocument,\n updateObj: UpdateQuery\n): Promise> {\n return this.incrementalModify((docData) => {\n const newDocData = modifyjs(docData, updateObj);\n return newDocData;\n });\n}\n\nexport function update(\n this: RxDocument,\n updateObj: UpdateQuery\n): Promise> {\n const oldDocData = this._data;\n const newDocData = modifyjs(oldDocData, updateObj);\n return this._saveData(newDocData, oldDocData);\n}\n\nexport function RxQueryUpdate(\n this: RxQuery,\n updateObj: UpdateQuery\n): Promise {\n return this.exec()\n .then(docs => {\n if (!docs) {\n return null;\n }\n if (Array.isArray(docs)) {\n return Promise.all(\n docs.map(doc => doc.update(updateObj))\n ).then(() => docs);\n } else {\n // via findOne()\n return docs.update(updateObj).then(() => docs);\n }\n });\n}\n\n\nexport const RxDBUpdatePlugin: RxPlugin = {\n name: 'update',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.update = update;\n proto.incrementalUpdate = incrementalUpdate;\n },\n RxQuery: (proto: any) => {\n proto.update = RxQueryUpdate;\n }\n }\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,QAAQ,MAAM,UAAU;AAQ/B,OAAO,SAASC,iBAAiB,CAE7BC,SAAiC,EACH;EAC9B,OAAO,IAAI,CAACC,iBAAiB,CAAC,UAACC,OAAO,EAAK;IACvC,IAAMC,UAAU,GAAGL,QAAQ,CAACI,OAAO,EAAEF,SAAS,CAAC;IAC/C,OAAOG,UAAU;EACrB,CAAC,CAAC;AACN;AAEA,OAAO,SAASC,MAAM,CAElBJ,SAAiC,EACH;EAC9B,IAAMK,UAAU,GAAG,IAAI,CAACC,KAAK;EAC7B,IAAMH,UAAU,GAAGL,QAAQ,CAACO,UAAU,EAAEL,SAAS,CAAC;EAClD,OAAO,IAAI,CAACO,SAAS,CAACJ,UAAU,EAAEE,UAAU,CAAC;AACjD;AAEA,OAAO,SAASG,aAAa,CAEzBR,SAA2B,EACf;EACZ,OAAO,IAAI,CAACS,IAAI,EAAE,CACbC,IAAI,CAAC,UAAAC,IAAI,EAAI;IACV,IAAI,CAACA,IAAI,EAAE;MACP,OAAO,IAAI;IACf;IACA,IAAIC,KAAK,CAACC,OAAO,CAACF,IAAI,CAAC,EAAE;MACrB,OAAOG,OAAO,CAACC,GAAG,CACdJ,IAAI,CAACK,GAAG,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACb,MAAM,CAACJ,SAAS,CAAC;MAAA,EAAC,CACzC,CAACU,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IACtB,CAAC,MAAM;MACH;MACA,OAAOA,IAAI,CAACP,MAAM,CAACJ,SAAS,CAAC,CAACU,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IAClD;EACJ,CAAC,CAAC;AACV;AAGA,OAAO,IAAMO,gBAA0B,GAAG;EACtCC,IAAI,EAAE,QAAQ;EACdC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACnB,MAAM,GAAGA,MAAM;MACrBmB,KAAK,CAACxB,iBAAiB,GAAGA,iBAAiB;IAC/C,CAAC;IACDyB,OAAO,EAAE,iBAACD,KAAU,EAAK;MACrBA,KAAK,CAACnB,MAAM,GAAGI,aAAa;IAChC;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/utils/index.js b/dist/es/plugins/utils/index.js new file mode 100644 index 00000000000..bf4196e0cda --- /dev/null +++ b/dist/es/plugins/utils/index.js @@ -0,0 +1,13 @@ +export * from './utils-array'; +export * from './utils-blob-buffer'; +export * from './utils-base64'; +export * from './utils-revision'; +export * from './utils-document'; +export * from './utils-hash'; +export * from './utils-promise'; +export * from './utils-string'; +export * from './utils-object'; +export * from './utils-error'; +export * from './utils-time'; +export * from './utils-other'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/index.js.map b/dist/es/plugins/utils/index.js.map new file mode 100644 index 00000000000..62ef7d0976e --- /dev/null +++ b/dist/es/plugins/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/utils/index.ts"],"sourcesContent":["export * from './utils-array';\nexport * from './utils-blob-buffer';\nexport * from './utils-base64';\nexport * from './utils-revision';\nexport * from './utils-document';\nexport * from './utils-hash';\nexport * from './utils-promise';\nexport * from './utils-string';\nexport * from './utils-object';\nexport * from './utils-error';\nexport * from './utils-time';\nexport * from './utils-other';\n"],"mappings":"AAAA,cAAc,eAAe;AAC7B,cAAc,qBAAqB;AACnC,cAAc,gBAAgB;AAC9B,cAAc,kBAAkB;AAChC,cAAc,kBAAkB;AAChC,cAAc,cAAc;AAC5B,cAAc,iBAAiB;AAC/B,cAAc,gBAAgB;AAC9B,cAAc,gBAAgB;AAC9B,cAAc,eAAe;AAC7B,cAAc,cAAc;AAC5B,cAAc,eAAe"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-array.js b/dist/es/plugins/utils/utils-array.js new file mode 100644 index 00000000000..d675d41ce5e --- /dev/null +++ b/dist/es/plugins/utils/utils-array.js @@ -0,0 +1,72 @@ +export function lastOfArray(ar) { + return ar[ar.length - 1]; +} + +/** + * shuffle the given array + */ +export function shuffleArray(arr) { + return arr.sort(function () { + return Math.random() - 0.5; + }); +} +export function toArray(input) { + return Array.isArray(input) ? input.slice(0) : [input]; +} + +/** + * Split array with items into smaller arrays with items + * @link https://stackoverflow.com/a/7273794/3443137 + */ +export function batchArray(array, batchSize) { + array = array.slice(0); + var ret = []; + while (array.length) { + var batch = array.splice(0, batchSize); + ret.push(batch); + } + return ret; +} + +/** + * @link https://stackoverflow.com/a/15996017 + */ +export function removeOneFromArrayIfMatches(ar, condition) { + ar = ar.slice(); + var i = ar.length; + var done = false; + while (i-- && !done) { + if (condition(ar[i])) { + done = true; + ar.splice(i, 1); + } + } + return ar; +} + +/** + * returns true if the supplied argument is either an Array or a Readonly> + */ +export function isMaybeReadonlyArray(x) { + // While this looks strange, it's a workaround for an issue in TypeScript: + // https://github.com/microsoft/TypeScript/issues/17002 + // + // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array, + // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`. + // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while + // still performing runtime type inspection. + return Array.isArray(x); +} + +/** + * Use this in array.filter() to remove all empty slots + * and have the correct typings afterwards. + * @link https://stackoverflow.com/a/46700791/3443137 + */ +export function arrayFilterNotEmpty(value) { + if (value === null || value === undefined) { + return false; + } + return true; +} +//# sourceMappingURL=utils-array.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-array.js.map b/dist/es/plugins/utils/utils-array.js.map new file mode 100644 index 00000000000..2e5085e3ec3 --- /dev/null +++ b/dist/es/plugins/utils/utils-array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-array.js","names":["lastOfArray","ar","length","shuffleArray","arr","sort","Math","random","toArray","input","Array","isArray","slice","batchArray","array","batchSize","ret","batch","splice","push","removeOneFromArrayIfMatches","condition","i","done","isMaybeReadonlyArray","x","arrayFilterNotEmpty","value","undefined"],"sources":["../../../../src/plugins/utils/utils-array.ts"],"sourcesContent":["import type {\n MaybeReadonly\n} from '../../types';\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.sort(() => (Math.random() - 0.5));\n}\n\nexport function toArray(input: T | T[] | Readonly | Readonly): T[] {\n return Array.isArray(input) ? (input as any[]).slice(0) : [input];\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n"],"mappings":"AAIA,OAAO,SAASA,WAAW,CAAIC,EAAO,EAAiB;EACnD,OAAOA,EAAE,CAACA,EAAE,CAACC,MAAM,GAAG,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACA,OAAO,SAASC,YAAY,CAAIC,GAAQ,EAAO;EAC3C,OAAOA,GAAG,CAACC,IAAI,CAAC;IAAA,OAAOC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAG;EAAA,CAAC,CAAC;AA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,SAAS,EAAE;IACvC,OAAO,KAAK;EAChB;EACA,OAAO,IAAI;AACf"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-base64.js b/dist/es/plugins/utils/utils-base64.js new file mode 100644 index 00000000000..0d8cf6ce4a4 --- /dev/null +++ b/dist/es/plugins/utils/utils-base64.js @@ -0,0 +1,35 @@ +/** + * NO! We cannot just use btoa() and atob() + * because they do not work correctly with binary data. + * @link https://stackoverflow.com/q/30106476/3443137 + */ +import { encode, decode } from 'js-base64'; + +/** + * atob() and btoa() do not work well with non ascii chars, + * so we have to use these helper methods instead. + * @link https://stackoverflow.com/a/30106551/3443137 + */ +// Encoding UTF8 -> base64 +export function b64EncodeUnicode(str) { + return encode(str); +} + +// Decoding base64 -> UTF8 +export function b64DecodeUnicode(str) { + return decode(str); +} + +/** + * @link https://stackoverflow.com/a/9458996/3443137 + */ +export function arrayBufferToBase64(buffer) { + var binary = ''; + var bytes = new Uint8Array(buffer); + var len = bytes.byteLength; + for (var i = 0; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} +//# sourceMappingURL=utils-base64.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-base64.js.map b/dist/es/plugins/utils/utils-base64.js.map new file mode 100644 index 00000000000..e646c6df295 --- /dev/null +++ b/dist/es/plugins/utils/utils-base64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-base64.js","names":["encode","decode","b64EncodeUnicode","str","b64DecodeUnicode","arrayBufferToBase64","buffer","binary","bytes","Uint8Array","len","byteLength","i","String","fromCharCode","btoa"],"sources":["../../../../src/plugins/utils/utils-base64.ts"],"sourcesContent":["\n/**\n * NO! We cannot just use btoa() and atob()\n * because they do not work correctly with binary data.\n * @link https://stackoverflow.com/q/30106476/3443137\n */\nimport { encode, decode } from 'js-base64';\n\n/**\n * atob() and btoa() do not work well with non ascii chars,\n * so we have to use these helper methods instead.\n * @link https://stackoverflow.com/a/30106551/3443137\n */\n// Encoding UTF8 -> base64\nexport function b64EncodeUnicode(str: string) {\n return encode(str);\n}\n\n// Decoding base64 -> UTF8\nexport function b64DecodeUnicode(str: string) {\n return decode(str);\n}\n\n/**\n * @link https://stackoverflow.com/a/9458996/3443137\n */\nexport function arrayBufferToBase64(buffer: ArrayBuffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n"],"mappings":"AACA;AACA;AACA;AACA;AACA;AACA,SAASA,MAAM,EAAEC,MAAM,QAAQ,WAAW;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,gBAAgB,CAACC,GAAW,EAAE;EAC1C,OAAOH,MAAM,CAACG,GAAG,CAAC;AACtB;;AAEA;AACA,OAAO,SAASC,gBAAgB,CAACD,GAAW,EAAE;EAC1C,OAAOF,MAAM,CAACE,GAAG,CAAC;AACtB;;AAEA;AACA;AACA;AACA,OAAO,SAASE,mBAAmB,CAACC,MAAmB,EAAE;EACrD,IAAIC,MAAM,GAAG,EAAE;EACf,IAAMC,KAAK,GAAG,IAAIC,UAAU,CAACH,MAAM,CAAC;EACpC,IAAMI,GAAG,GAAGF,KAAK,CAACG,UAAU;EAC5B,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,GAAG,EAAEE,CAAC,EAAE,EAAE;IAC1BL,MAAM,IAAIM,MAAM,CAACC,YAAY,CAACN,KAAK,CAACI,CAAC,CAAC,CAAC;EAC3C;EACA,OAAOG,IAAI,CAACR,MAAM,CAAC;AACvB"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-blob-buffer.js b/dist/es/plugins/utils/utils-blob-buffer.js new file mode 100644 index 00000000000..db6c333df2f --- /dev/null +++ b/dist/es/plugins/utils/utils-blob-buffer.js @@ -0,0 +1,117 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { arrayBufferToBase64 } from './utils-base64'; + +/** + * This is an abstraction over the Blob/Buffer data structure. + * We need this because it behaves different in different JavaScript runtimes. + * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support + * the Blob data structure which is also supported by the browsers. + */ +export var blobBufferUtil = { + /** + * depending if we are on node or browser, + * we have to use Buffer(node) or Blob(browser) + */ + createBlobBuffer: function createBlobBuffer(data, type) { + var blobBuffer = new Blob([data], { + type: type + }); + return blobBuffer; + }, + /** + * depending if we are on node or browser, + * we have to use Buffer(node) or Blob(browser) + */ + createBlobBufferFromBase64: function () { + var _createBlobBufferFromBase = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(base64String, type) { + var base64Response, blob; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return fetch("data:" + type + ";base64," + base64String); + case 2: + base64Response = _context.sent; + _context.next = 5; + return base64Response.blob(); + case 5: + blob = _context.sent; + return _context.abrupt("return", blob); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createBlobBufferFromBase64(_x, _x2) { + return _createBlobBufferFromBase.apply(this, arguments); + } + return createBlobBufferFromBase64; + }(), + isBlobBuffer: function isBlobBuffer(data) { + if (data instanceof Blob || typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) { + return true; + } else { + return false; + } + }, + toString: function toString(blobBuffer) { + /** + * in the electron-renderer we have a typed array insteaf of a blob + * so we have to transform it. + * @link https://github.com/pubkey/rxdb/issues/1371 + */ + var blobBufferType = Object.prototype.toString.call(blobBuffer); + if (blobBufferType === '[object Uint8Array]') { + blobBuffer = new Blob([blobBuffer]); + } + if (typeof blobBuffer === 'string') { + return Promise.resolve(blobBuffer); + } + return blobBuffer.text(); + }, + toBase64String: function () { + var _toBase64String = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(blobBuffer) { + var blobBufferType, arrayBuffer; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(typeof blobBuffer === 'string')) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", blobBuffer); + case 2: + /** + * in the electron-renderer we have a typed array insteaf of a blob + * so we have to transform it. + * @link https://github.com/pubkey/rxdb/issues/1371 + */ + blobBufferType = Object.prototype.toString.call(blobBuffer); + if (blobBufferType === '[object Uint8Array]') { + blobBuffer = new Blob([blobBuffer]); + } + _context2.next = 6; + return fetch(URL.createObjectURL(blobBuffer)).then(function (res) { + return res.arrayBuffer(); + }); + case 6: + arrayBuffer = _context2.sent; + return _context2.abrupt("return", arrayBufferToBase64(arrayBuffer)); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function toBase64String(_x3) { + return _toBase64String.apply(this, arguments); + } + return toBase64String; + }(), + size: function size(blobBuffer) { + return blobBuffer.size; + } +}; +//# sourceMappingURL=utils-blob-buffer.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-blob-buffer.js.map b/dist/es/plugins/utils/utils-blob-buffer.js.map new file mode 100644 index 00000000000..940ae7bd6fa --- /dev/null +++ b/dist/es/plugins/utils/utils-blob-buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-blob-buffer.js","names":["arrayBufferToBase64","blobBufferUtil","createBlobBuffer","data","type","blobBuffer","Blob","createBlobBufferFromBase64","base64String","fetch","base64Response","blob","isBlobBuffer","Buffer","isBuffer","toString","blobBufferType","Object","prototype","call","Promise","resolve","text","toBase64String","URL","createObjectURL","then","res","arrayBuffer","size"],"sources":["../../../../src/plugins/utils/utils-blob-buffer.ts"],"sourcesContent":["import type {\n BlobBuffer\n} from '../../types';\nimport { arrayBufferToBase64 } from './utils-base64';\n\n/**\n * This is an abstraction over the Blob/Buffer data structure.\n * We need this because it behaves different in different JavaScript runtimes.\n * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support\n * the Blob data structure which is also supported by the browsers.\n */\nexport const blobBufferUtil = {\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n createBlobBuffer(\n data: string,\n type: string\n ): BlobBuffer {\n const blobBuffer = new Blob([data], {\n type\n });\n return blobBuffer;\n },\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n async createBlobBufferFromBase64(\n base64String: string,\n type: string\n ): Promise {\n const base64Response = await fetch(`data:${type};base64,${base64String}`);\n const blob = await base64Response.blob();\n return blob;\n\n },\n isBlobBuffer(data: any): boolean {\n if (data instanceof Blob || (typeof Buffer !== 'undefined' && Buffer.isBuffer(data))) {\n return true;\n } else {\n return false;\n }\n },\n toString(blobBuffer: BlobBuffer | string): Promise {\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n if (typeof blobBuffer === 'string') {\n return Promise.resolve(blobBuffer);\n }\n\n return (blobBuffer as Blob).text();\n },\n async toBase64String(blobBuffer: BlobBuffer | string): Promise {\n if (typeof blobBuffer === 'string') {\n return blobBuffer;\n }\n\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n\n const arrayBuffer = await fetch(URL.createObjectURL(blobBuffer as Blob)).then(res => res.arrayBuffer());\n return arrayBufferToBase64(arrayBuffer);\n },\n size(blobBuffer: BlobBuffer): number {\n return (blobBuffer as Blob).size;\n }\n};\n"],"mappings":";;AAGA,SAASA,mBAAmB,QAAQ,gBAAgB;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,cAAc,GAAG;EAC1B;AACJ;AACA;AACA;EACIC,g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;YAAA;YAAA,kCACvBA,UAAU;UAAA;YAGrB;AACR;AACA;AACA;AACA;YACcW,cAAc,GAAGC,MAAM,CAACC,SAAS,CAACH,QAAQ,CAACI,IAAI,CAACd,UAAU,CAAC;YACjE,IAAIW,cAAc,KAAK,qBAAqB,EAAE;cAC1CX,UAAU,GAAG,IAAIC,IAAI,CAAC,CAACD,UAAU,CAAC,CAAC;YACvC;YAAC;YAAA,OAEyBI,KAAK,CAACe,GAAG,CAACC,eAAe,CAACpB,UAAU,CAAS,CAAC,CAACqB,IAAI,CAAC,UAAAC,GAAG;cAAA,OAAIA,GAAG,CAACC,WAAW,EAAE;YAAA,EAAC;UAAA;YAAjGA,WAAW;YAAA,kCACV5B,mBAAmB,CAAC4B,WAAW,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA;IAAA;MAAA;IAAA;IAAA;EAAA;EAE3CC,IAAI,gBAACxB,UAAsB,EAAU;IACjC,OAAQA,UAAU,CAAUwB,IAAI;EACpC;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-document.js b/dist/es/plugins/utils/utils-document.js new file mode 100644 index 00000000000..3d066505e26 --- /dev/null +++ b/dist/es/plugins/utils/utils-document.js @@ -0,0 +1,77 @@ +/** + * We use 1 as minimum so that the value is never falsy. + * This const is used in several places because querying + * with a value lower then the minimum could give false results. + */ +export var RX_META_LWT_MINIMUM = 1; +export function getDefaultRxDocumentMeta() { + return { + /** + * Set this to 1 to not waste performance + * while calling new Date().. + * The storage wrappers will anyway update + * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage() + */ + lwt: RX_META_LWT_MINIMUM + }; +} + +/** + * Returns a revision that is not valid. + * Use this to have correct typings + * while the storage wrapper anyway will overwrite the revision. + */ +export function getDefaultRevision() { + /** + * Use a non-valid revision format, + * to ensure that the RxStorage will throw + * when the revision is not replaced downstream. + */ + return ''; +} +export function stripMetaDataFromDocument(docData) { + return Object.assign({}, docData, { + _meta: undefined, + _deleted: undefined, + _rev: undefined + }); +} + +/** + * Faster way to check the equalness of document lists + * compared to doing a deep-equal. + * Here we only check the ids and revisions. + */ +export function areRxDocumentArraysEqual(primaryPath, ar1, ar2) { + if (ar1.length !== ar2.length) { + return false; + } + var i = 0; + var len = ar1.length; + while (i < len) { + var row1 = ar1[i]; + var row2 = ar2[i]; + i++; + if (row1._rev !== row2._rev || row1[primaryPath] !== row2[primaryPath]) { + return false; + } + } + return true; +} +export function getSortDocumentsByLastWriteTimeComparator(primaryPath) { + return function (a, b) { + if (a._meta.lwt === b._meta.lwt) { + if (b[primaryPath] < a[primaryPath]) { + return 1; + } else { + return -1; + } + } else { + return a._meta.lwt - b._meta.lwt; + } + }; +} +export function sortDocumentsByLastWriteTime(primaryPath, docs) { + return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath)); +} +//# sourceMappingURL=utils-document.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-document.js.map b/dist/es/plugins/utils/utils-document.js.map new file mode 100644 index 00000000000..50f69a78c99 --- /dev/null +++ b/dist/es/plugins/utils/utils-document.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-document.js","names":["RX_META_LWT_MINIMUM","getDefaultRxDocumentMeta","lwt","getDefaultRevision","stripMetaDataFromDocument","docData","Object","assign","_meta","undefined","_deleted","_rev","areRxDocumentArraysEqual","primaryPath","ar1","ar2","length","i","len","row1","row2","getSortDocumentsByLastWriteTimeComparator","a","b","sortDocumentsByLastWriteTime","docs","sort"],"sources":["../../../../src/plugins/utils/utils-document.ts"],"sourcesContent":["import type {\n RxDocumentData,\n RxDocumentMeta,\n StringKeys\n} from '../../types';\n/**\n * We use 1 as minimum so that the value is never falsy.\n * This const is used in several places because querying\n * with a value lower then the minimum could give false results.\n */\nexport const RX_META_LWT_MINIMUM = 1;\n\nexport function getDefaultRxDocumentMeta(): RxDocumentMeta {\n return {\n /**\n * Set this to 1 to not waste performance\n * while calling new Date()..\n * The storage wrappers will anyway update\n * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage()\n */\n lwt: RX_META_LWT_MINIMUM\n };\n}\n\n/**\n * Returns a revision that is not valid.\n * Use this to have correct typings\n * while the storage wrapper anyway will overwrite the revision.\n */\nexport function getDefaultRevision(): string {\n /**\n * Use a non-valid revision format,\n * to ensure that the RxStorage will throw\n * when the revision is not replaced downstream.\n */\n return '';\n}\n\n\nexport function stripMetaDataFromDocument(docData: RxDocumentData): RxDocType {\n return Object.assign({}, docData, {\n _meta: undefined,\n _deleted: undefined,\n _rev: undefined\n });\n}\n\n\n/**\n * Faster way to check the equalness of document lists\n * compared to doing a deep-equal.\n * Here we only check the ids and revisions.\n */\nexport function areRxDocumentArraysEqual(\n primaryPath: StringKeys>,\n ar1: RxDocumentData[],\n ar2: RxDocumentData[]\n): boolean {\n if (ar1.length !== ar2.length) {\n return false;\n }\n let i = 0;\n const len = ar1.length;\n while (i < len) {\n const row1 = ar1[i];\n const row2 = ar2[i];\n i++;\n\n if (\n row1._rev !== row2._rev ||\n row1[primaryPath] !== row2[primaryPath]\n ) {\n return false;\n }\n }\n return true;\n}\n\n\n\nexport function getSortDocumentsByLastWriteTimeComparator(primaryPath: string) {\n return (a: RxDocumentData, b: RxDocumentData) => {\n if (a._meta.lwt === b._meta.lwt) {\n if ((b as any)[primaryPath] < (a as any)[primaryPath]) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return a._meta.lwt - b._meta.lwt;\n }\n };\n}\nexport function sortDocumentsByLastWriteTime(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData[] {\n return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath));\n}\n"],"mappings":"AAKA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMA,mBAAmB,GAAG,CAAC;AAEpC,OAAO,SAASC,wBAAwB,GAAmB;EACvD,OAAO;IACH;AACR;AACA;AACA;AACA;AACA;IACQC,GAAG,EAAEF;EACT,CAAC;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASG,kBAA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K,CAACN,GAAG,GAAGqB,CAAC,CAACf,KAAK,CAACN,GAAG;IACpC;EACJ,CAAC;AACL;AACA,OAAO,SAASsB,4BAA4B,CACxCX,WAAmB,EACnBY,IAAiC,EACN;EAC3B,OAAOA,IAAI,CAACC,IAAI,CAACL,yCAAyC,CAACR,WAAW,CAAC,CAAC;AAC5E"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-error.js b/dist/es/plugins/utils/utils-error.js new file mode 100644 index 00000000000..ecf2c3aacbd --- /dev/null +++ b/dist/es/plugins/utils/utils-error.js @@ -0,0 +1,29 @@ +import { ucfirst } from './utils-string'; + +/** + * Returns an error that indicates that a plugin is missing + * We do not throw a RxError because this should not be handled + * programmatically but by using the correct import + */ +export function pluginMissing(pluginKey) { + var keyParts = pluginKey.split('-'); + var pluginName = 'RxDB'; + keyParts.forEach(function (part) { + pluginName += ucfirst(part); + }); + pluginName += 'Plugin'; + return new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { " + pluginName + " } from 'rxdb/plugins/" + pluginKey + "';\n addRxPlugin(" + pluginName + ");\n "); +} +export function errorToPlainJson(err) { + var ret = { + name: err.name, + message: err.message, + rxdb: err.rxdb, + parameters: err.parameters, + code: err.code, + // stack must be last to make it easier to read the json in a console. + stack: err.stack + }; + return ret; +} +//# sourceMappingURL=utils-error.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-error.js.map b/dist/es/plugins/utils/utils-error.js.map new file mode 100644 index 00000000000..6144e9cac91 --- /dev/null +++ b/dist/es/plugins/utils/utils-error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-error.js","names":["ucfirst","pluginMissing","pluginKey","keyParts","split","pluginName","forEach","part","Error","errorToPlainJson","err","ret","name","message","rxdb","parameters","code","stack"],"sources":["../../../../src/plugins/utils/utils-error.ts"],"sourcesContent":["import type {\n PlainJsonError,\n RxError,\n RxTypeError\n} from '../../types';\nimport { ucfirst } from './utils-string';\n\n\n\n/**\n * Returns an error that indicates that a plugin is missing\n * We do not throw a RxError because this should not be handled\n * programmatically but by using the correct import\n */\nexport function pluginMissing(\n pluginKey: string\n): Error {\n const keyParts = pluginKey.split('-');\n let pluginName = 'RxDB';\n keyParts.forEach(part => {\n pluginName += ucfirst(part);\n });\n pluginName += 'Plugin';\n return new Error(\n `You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { ${pluginName} } from 'rxdb/plugins/${pluginKey}';\n addRxPlugin(${pluginName});\n `\n );\n}\n\n\n\nexport function errorToPlainJson(err: Error | TypeError | RxError | RxTypeError): PlainJsonError {\n const ret: PlainJsonError = {\n name: err.name,\n message: err.message,\n rxdb: (err as any).rxdb,\n parameters: (err as RxError).parameters,\n code: (err as RxError).code,\n // stack must be last to make it easier to read the json in a console.\n stack: err.stack\n };\n return ret;\n}\n"],"mappings":"AAKA,SAASA,OAAO,QAAQ,gBAAgB;;AAIxC;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAa,CACzBC,SAAiB,EACZ;EACL,IAAMC,QAAQ,GAAGD,SAAS,CAACE,KAAK,CAAC,GAAG,CAAC;EACrC,IAAIC,UAAU,GAAG,MAAM;EACvBF,QAAQ,CAACG,OAAO,CAAC,UAAAC,IAAI,EAAI;IACrBF,UAAU,IAAIL,OAAO,CAACO,IAAI,CAAC;EAC/B,CAAC,CAAC;EACFF,UAAU,IAAI,QAAQ;EACtB,OAAO,IAAIG,KAAK,iLAGGH,UAAU,8BAAyBH,SAAS,oCACzCG,UAAU,kBAE/B;AACL;AAIA,OAAO,SAASI,gBAAgB,CAACC,GAA8C,EAAkB;EAC7F,IAAMC,GAAmB,GAAG;IACxBC,IAAI,EAAEF,GAAG,CAACE,IAAI;IACdC,OAAO,EAAEH,GAAG,CAACG,OAAO;IACpBC,IAAI,EAAGJ,GAAG,CAASI,IAAI;IACvBC,UAAU,EAAGL,GAAG,CAAaK,UAAU;IACvCC,IAAI,EAAGN,GAAG,CAAaM,IAAI;IAC3B;IACAC,KAAK,EAAEP,GAAG,CAACO;EACf,CAAC;EACD,OAAON,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-hash.js b/dist/es/plugins/utils/utils-hash.js new file mode 100644 index 00000000000..16f8b8a5974 --- /dev/null +++ b/dist/es/plugins/utils/utils-hash.js @@ -0,0 +1,68 @@ +/** + * This is a very fast hash method + * but it is not cryptographically secure. + * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int). + * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery + * @return a string as hash-result + */ +export function fastUnsecureHash(inputString, +// used to test the polyfill +doNotUseTextEncoder) { + var hashValue = 0, + i, + chr, + len; + + /** + * For better performance we first transform all + * chars into their ascii numbers at once. + * + * This is what makes the murmurhash implementation such fast. + * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4 + */ + var encoded; + + /** + * All modern browsers support the TextEncoder + * @link https://caniuse.com/textencoder + * But to make RxDB work in other JavaScript runtimes, + * like when using it in flutter or QuickJS, we need to + * make it work even when there is no TextEncoder. + */ + if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) { + encoded = new TextEncoder().encode(inputString); + } else { + encoded = []; + for (var j = 0; j < inputString.length; j++) { + encoded.push(inputString.charCodeAt(j)); + } + } + for (i = 0, len = inputString.length; i < len; i++) { + chr = encoded[i]; + hashValue = (hashValue << 5) - hashValue + chr; + hashValue |= 0; // Convert to 32bit integer + } + + if (hashValue < 0) { + hashValue = hashValue * -1; + } + + /** + * To make the output smaller + * but still have it to represent the same value, + * we use the biggest radix of 36 instead of just + * transforming it into a hex string. + */ + return hashValue.toString(36); +} + +/** + * Default hash method used to create revision hashes + * that do not have to be cryptographically secure. + * IMPORTANT: Changing the default hashing method + * requires a BREAKING change! + */ +export function defaultHashFunction(input) { + return fastUnsecureHash(input); +} +//# sourceMappingURL=utils-hash.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-hash.js.map b/dist/es/plugins/utils/utils-hash.js.map new file mode 100644 index 00000000000..39a6e8a2bd7 --- /dev/null +++ b/dist/es/plugins/utils/utils-hash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-hash.js","names":["fastUnsecureHash","inputString","doNotUseTextEncoder","hashValue","i","chr","len","encoded","TextEncoder","encode","j","length","push","charCodeAt","toString","defaultHashFunction","input"],"sources":["../../../../src/plugins/utils/utils-hash.ts"],"sourcesContent":["/**\n * This is a very fast hash method\n * but it is not cryptographically secure.\n * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int).\n * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery\n * @return a string as hash-result\n */\nexport function fastUnsecureHash(\n inputString: string,\n // used to test the polyfill\n doNotUseTextEncoder?: boolean\n): string {\n let hashValue = 0,\n i, chr, len;\n\n /**\n * For better performance we first transform all\n * chars into their ascii numbers at once.\n *\n * This is what makes the murmurhash implementation such fast.\n * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4\n */\n let encoded: Uint8Array | number[];\n\n /**\n * All modern browsers support the TextEncoder\n * @link https://caniuse.com/textencoder\n * But to make RxDB work in other JavaScript runtimes,\n * like when using it in flutter or QuickJS, we need to\n * make it work even when there is no TextEncoder.\n */\n if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) {\n encoded = new TextEncoder().encode(inputString);\n } else {\n encoded = [];\n for (let j = 0; j < inputString.length; j++) {\n encoded.push(inputString.charCodeAt(j));\n }\n }\n\n for (i = 0, len = inputString.length; i < len; i++) {\n chr = encoded[i];\n hashValue = ((hashValue << 5) - hashValue) + chr;\n hashValue |= 0; // Convert to 32bit integer\n }\n if (hashValue < 0) {\n hashValue = hashValue * -1;\n }\n\n /**\n * To make the output smaller\n * but still have it to represent the same value,\n * we use the biggest radix of 36 instead of just\n * transforming it into a hex string.\n */\n return hashValue.toString(36);\n}\n\n/**\n * Default hash method used to create revision hashes\n * that do not have to be cryptographically secure.\n * IMPORTANT: Changing the default hashing method\n * requires a BREAKING change!\n */\nexport function defaultHashFunction(input: string): string {\n return fastUnsecureHash(input);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,gBAAgB,CAC5BC,WAAmB;AACnB;AACAC,mBAA6B,EACvB;EACN,IAAIC,SAAS,GAAG,CAAC;IACbC,CAAC;IAAEC,GAAG;IAAEC,GAAG;;EAEf;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAIC,OAA8B;;EAElC;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAI,OAAOC,WAAW,KAAK,WAAW,IAAI,CAACN,mBAAmB,EAAE;IAC5DK,OAAO,GAAG,IAAIC,WAAW,EAAE,CAACC,MAAM,CAACR,WAAW,CAAC;EACnD,CAAC,MAAM;IACHM,OAAO,GAAG,EAAE;IACZ,KAAK,IAAIG,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGT,WAAW,CAACU,MAAM,EAAED,CAAC,EAAE,EAAE;MACzCH,OAAO,CAACK,IAAI,CAACX,WAAW,CAACY,UAAU,CAACH,CAAC,CAAC,CAAC;IAC3C;EACJ;EAEA,KAAKN,CAAC,GAAG,CAAC,EAAEE,GAAG,GAAGL,WAAW,CAACU,MAAM,EAAEP,CAAC,GAAGE,GAAG,EAAEF,CAAC,EAAE,EAAE;IAChDC,GAAG,GAAGE,OAAO,CAACH,CAAC,CAAC;IAChBD,SAAS,GAAI,CAACA,SAAS,IAAI,CAAC,IAAIA,SAAS,GAAIE,GAAG;IAChDF,SAAS,IAAI,CAAC,CAAC,CAAC;EACpB;;EACA,IAAIA,SAAS,GAAG,CAAC,EAAE;IACfA,SAAS,GAAGA,SAAS,GAAG,CAAC,CAAC;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACI,OAAOA,SAAS,CAACW,QAAQ,CAAC,EAAE,CAAC;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmB,CAACC,KAAa,EAAU;EACvD,OAAOhB,gBAAgB,CAACgB,KAAK,CAAC;AAClC"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-object.js b/dist/es/plugins/utils/utils-object.js new file mode 100644 index 00000000000..feceefaac46 --- /dev/null +++ b/dist/es/plugins/utils/utils-object.js @@ -0,0 +1,194 @@ +export function deepFreeze(o) { + Object.freeze(o); + Object.getOwnPropertyNames(o).forEach(function (prop) { + if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop])) { + deepFreeze(o[prop]); + } + }); + return o; +} + +/** + * To get specific nested path values from objects, + * RxDB normally uses the 'object-path' npm module. + * But when performance is really relevant, this is not fast enough. + * Instead we use a monad that can prepare some stuff up front + * and we can re-use the generated function. + */ + +export function objectPathMonad(objectPath) { + var split = objectPath.split('.'); + + /** + * Performance shortcut, + * if no nested path is used, + * directly return the field of the object. + */ + if (split.length === 1) { + return function (obj) { + return obj[objectPath]; + }; + } + return function (obj) { + var currentVal = obj; + var t = 0; + while (t < split.length) { + var subPath = split[t]; + currentVal = currentVal[subPath]; + if (typeof currentVal === 'undefined') { + return currentVal; + } + t++; + } + return currentVal; + }; +} +export function getFromObjectOrThrow(obj, key) { + var val = obj[key]; + if (!val) { + throw new Error('missing value from object ' + key); + } + return val; +} + +/** + * returns a flattened object + * @link https://gist.github.com/penguinboy/762197 + */ +export function flattenObject(ob) { + var toReturn = {}; + for (var i in ob) { + if (!ob.hasOwnProperty(i)) continue; + if (typeof ob[i] === 'object') { + var flatObject = flattenObject(ob[i]); + for (var x in flatObject) { + if (!flatObject.hasOwnProperty(x)) continue; + toReturn[i + '.' + x] = flatObject[x]; + } + } else { + toReturn[i] = ob[i]; + } + } + return toReturn; +} + +/** + * does a flat copy on the objects, + * is about 3 times faster then using deepClone + * @link https://jsperf.com/object-rest-spread-vs-clone/2 + */ +export function flatClone(obj) { + return Object.assign({}, obj); +} + +/** + * @link https://stackoverflow.com/a/11509718/3443137 + */ +export function firstPropertyNameOfObject(obj) { + return Object.keys(obj)[0]; +} +export function firstPropertyValueOfObject(obj) { + var key = Object.keys(obj)[0]; + return obj[key]; +} + +/** + * deep-sort an object so its attributes are in lexical order. + * Also sorts the arrays inside of the object if no-array-sort not set + */ +export function sortObject(obj) { + var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (!obj) return obj; // do not sort null, false or undefined + + // array + if (!noArraySort && Array.isArray(obj)) { + return obj.sort(function (a, b) { + if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b); + if (typeof a === 'object') return 1;else return -1; + }).map(function (i) { + return sortObject(i, noArraySort); + }); + } + + // object + // array is also of type object + if (typeof obj === 'object' && !Array.isArray(obj)) { + if (obj instanceof RegExp) { + return obj; + } + var out = {}; + Object.keys(obj).sort(function (a, b) { + return a.localeCompare(b); + }).forEach(function (key) { + out[key] = sortObject(obj[key], noArraySort); + }); + return out; + } + + // everything else + return obj; +} + +/** + * Deep clone a plain json object. + * Does not work with recursive stuff + * or non-plain-json. + * IMPORANT: Performance of this is very important, + * do not change it without running performance tests! + * + * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts + */ +function deepClone(src) { + if (!src) { + return src; + } + if (src === null || typeof src !== 'object') { + return src; + } + if (Array.isArray(src)) { + var ret = new Array(src.length); + var i = ret.length; + while (i--) { + ret[i] = deepClone(src[i]); + } + return ret; + } + var dest = {}; + // eslint-disable-next-line guard-for-in + for (var key in src) { + // TODO we should not be required to deep clone RegEx objects, + // this must be fixed in RxDB. + if (src[key] instanceof RegExp) { + dest[key] = src[key]; + } else { + dest[key] = deepClone(src[key]); + } + } + return dest; +} +export var clone = deepClone; + +/** + * overwrites the getter with the actual value + * Mostly used for caching stuff on the first run + */ +export function overwriteGetterForCaching(obj, getterName, value) { + Object.defineProperty(obj, getterName, { + get: function get() { + return value; + } + }); + return value; +} + +/** + * used to JSON.stringify() objects that contain a regex + * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs! + */ +export function stringifyFilter(key, value) { + if (value instanceof RegExp) { + return value.toString(); + } + return value; +} +//# sourceMappingURL=utils-object.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-object.js.map b/dist/es/plugins/utils/utils-object.js.map new file mode 100644 index 00000000000..4dc1889a654 --- /dev/null +++ b/dist/es/plugins/utils/utils-object.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-object.js","names":["deepFreeze","o","Object","freeze","getOwnPropertyNames","forEach","prop","hasOwnProperty","isFrozen","objectPathMonad","objectPath","split","length","obj","currentVal","t","subPath","getFromObjectOrThrow","key","val","Error","flattenObject","ob","toReturn","i","flatObject","x","flatClone","assign","firstPropertyNameOfObject","keys","firstPropertyValueOfObject","sortObject","noArraySort","Array","isArray","sort","a","b","localeCompare","map","RegExp","out","deepClone","src","ret","dest","clone","overwriteGetterForCaching","getterName","value","defineProperty","get","stringifyFilter","toString"],"sources":["../../../../src/plugins/utils/utils-object.ts"],"sourcesContent":["import type {\n DeepReadonlyObject\n} from '../../types';\n\nexport function deepFreeze(o: T): T {\n Object.freeze(o);\n Object.getOwnPropertyNames(o).forEach(function (prop) {\n if (\n (o as any).hasOwnProperty(prop)\n &&\n (o as any)[prop] !== null\n &&\n (\n typeof (o as any)[prop] === 'object'\n ||\n typeof (o as any)[prop] === 'function'\n )\n &&\n !Object.isFrozen((o as any)[prop])\n ) {\n deepFreeze((o as any)[prop]);\n }\n });\n return o;\n}\n\n\n/**\n * To get specific nested path values from objects,\n * RxDB normally uses the 'object-path' npm module.\n * But when performance is really relevant, this is not fast enough.\n * Instead we use a monad that can prepare some stuff up front\n * and we can re-use the generated function.\n */\nexport type ObjectPathMonadFunction = (obj: T) => R;\nexport function objectPathMonad(objectPath: string): ObjectPathMonadFunction {\n const split = objectPath.split('.');\n\n /**\n * Performance shortcut,\n * if no nested path is used,\n * directly return the field of the object.\n */\n if (split.length === 1) {\n return (obj: T) => (obj as any)[objectPath];\n }\n\n\n return (obj: T) => {\n let currentVal: any = obj;\n let t = 0;\n while (t < split.length) {\n const subPath = split[t];\n currentVal = currentVal[subPath];\n if (typeof currentVal === 'undefined') {\n return currentVal;\n }\n t++;\n }\n return currentVal;\n };\n}\n\n\nexport function getFromObjectOrThrow(\n obj: { [k: string]: V; },\n key: string\n): V {\n const val = obj[key];\n if (!val) {\n throw new Error('missing value from object ' + key);\n }\n return val;\n}\n\n/**\n * returns a flattened object\n * @link https://gist.github.com/penguinboy/762197\n */\nexport function flattenObject(ob: any) {\n const toReturn: any = {};\n\n for (const i in ob) {\n if (!ob.hasOwnProperty(i)) continue;\n\n if ((typeof ob[i]) === 'object') {\n const flatObject = flattenObject(ob[i]);\n for (const x in flatObject) {\n if (!flatObject.hasOwnProperty(x)) continue;\n\n toReturn[i + '.' + x] = flatObject[x];\n }\n } else {\n toReturn[i] = ob[i];\n }\n }\n return toReturn;\n}\n\n\n/**\n * does a flat copy on the objects,\n * is about 3 times faster then using deepClone\n * @link https://jsperf.com/object-rest-spread-vs-clone/2\n */\nexport function flatClone(obj: T | DeepReadonlyObject | Readonly): T {\n return Object.assign({}, obj) as any;\n}\n\n/**\n * @link https://stackoverflow.com/a/11509718/3443137\n */\nexport function firstPropertyNameOfObject(obj: any): string {\n return Object.keys(obj)[0];\n}\nexport function firstPropertyValueOfObject(obj: { [k: string]: T; }): T {\n const key = Object.keys(obj)[0];\n return obj[key];\n}\n\n\n/**\n * deep-sort an object so its attributes are in lexical order.\n * Also sorts the arrays inside of the object if no-array-sort not set\n */\nexport function sortObject(obj: any, noArraySort = false): any {\n if (!obj) return obj; // do not sort null, false or undefined\n\n // array\n if (!noArraySort && Array.isArray(obj)) {\n return obj\n .sort((a, b) => {\n if (typeof a === 'string' && typeof b === 'string')\n return a.localeCompare(b);\n\n if (typeof a === 'object') return 1;\n else return -1;\n })\n .map(i => sortObject(i, noArraySort));\n }\n\n // object\n // array is also of type object\n if (typeof obj === 'object' && !Array.isArray(obj)) {\n if (obj instanceof RegExp) {\n return obj;\n }\n\n const out: any = {};\n Object.keys(obj)\n .sort((a, b) => a.localeCompare(b))\n .forEach(key => {\n out[key] = sortObject(obj[key], noArraySort);\n });\n return out;\n }\n\n // everything else\n return obj;\n}\n\n\n\n/**\n * Deep clone a plain json object.\n * Does not work with recursive stuff\n * or non-plain-json.\n * IMPORANT: Performance of this is very important,\n * do not change it without running performance tests!\n *\n * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts\n */\nfunction deepClone(src: T | DeepReadonlyObject): T {\n if (!src) {\n return src;\n }\n if (src === null || typeof (src) !== 'object') {\n return src;\n }\n if (Array.isArray(src)) {\n const ret = new Array(src.length);\n let i = ret.length;\n while (i--) {\n ret[i] = deepClone(src[i]);\n }\n return ret as any;\n }\n const dest: any = {};\n // eslint-disable-next-line guard-for-in\n for (const key in src) {\n // TODO we should not be required to deep clone RegEx objects,\n // this must be fixed in RxDB.\n if (src[key] instanceof RegExp) {\n dest[key] = src[key];\n } else {\n dest[key] = deepClone(src[key]);\n }\n }\n return dest;\n}\nexport const clone = deepClone;\n\n\n\n/**\n * overwrites the getter with the actual value\n * Mostly used for caching stuff on the first run\n */\nexport function overwriteGetterForCaching(\n obj: any,\n getterName: string,\n value: ValueType\n): ValueType {\n Object.defineProperty(obj, getterName, {\n get: function () {\n return value;\n }\n });\n return value;\n}\n\n\n\n/**\n * used to JSON.stringify() objects that contain a regex\n * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs!\n */\nexport function stringifyFilter(key: string, value: any) {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n}\n\n\n"],"mappings":"AAIA,OAAO,SAASA,UAAU,CAAIC,CAAI,EAAK;EACnCC,MAAM,CAACC,MAAM,CAACF,CAAC,CAAC;EAChBC,MAAM,CAACE,mBAAmB,CAACH,CAAC,CAAC,CAACI,OAAO,CAAC,UAAUC,IAAI,EAAE;IAClD,IACKL,CAAC,CAASM,cAAc,CAACD,IAAI,CAAC,IAE9BL,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KAAK;AAChB"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-other.js b/dist/es/plugins/utils/utils-other.js new file mode 100644 index 00000000000..c29f1019ca2 --- /dev/null +++ b/dist/es/plugins/utils/utils-other.js @@ -0,0 +1,44 @@ +export function runXTimes(xTimes, fn) { + new Array(xTimes).fill(0).forEach(function (_v, idx) { + return fn(idx); + }); +} +export function ensureNotFalsy(obj) { + if (!obj) { + throw new Error('ensureNotFalsy() is falsy'); + } + return obj; +} +export function ensureInteger(obj) { + if (!Number.isInteger(obj)) { + throw new Error('ensureInteger() is falsy'); + } + return obj; +} +export function getFromMapOrThrow(map, key) { + var val = map.get(key); + if (typeof val === 'undefined') { + throw new Error('missing value from map ' + key); + } + return val; +} +export function getFromMapOrFill(map, key, fillerFunction) { + var value = map.get(key); + if (!value) { + value = fillerFunction(); + map.set(key, value); + } + return value; +} + +/** + * Using shareReplay() without settings will not unsubscribe + * if there are no more subscribers. + * So we use these defaults. + * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95 + */ +export var RXJS_SHARE_REPLAY_DEFAULTS = { + bufferSize: 1, + refCount: true +}; +//# sourceMappingURL=utils-other.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-other.js.map b/dist/es/plugins/utils/utils-other.js.map new file mode 100644 index 00000000000..a42307e235d --- /dev/null +++ b/dist/es/plugins/utils/utils-other.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-other.js","names":["runXTimes","xTimes","fn","Array","fill","forEach","_v","idx","ensureNotFalsy","obj","Error","ensureInteger","Number","isInteger","getFromMapOrThrow","map","key","val","get","getFromMapOrFill","fillerFunction","value","set","RXJS_SHARE_REPLAY_DEFAULTS","bufferSize","refCount"],"sources":["../../../../src/plugins/utils/utils-other.ts"],"sourcesContent":["export function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null): T {\n if (!obj) {\n throw new Error('ensureNotFalsy() is falsy');\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n\nexport function getFromMapOrThrow(map: Map | WeakMap, key: K): V {\n const val = map.get(key);\n if (typeof val === 'undefined') {\n throw new Error('missing value from map ' + key);\n }\n return val;\n}\n\nexport function getFromMapOrFill(\n map: Map | WeakMap,\n key: K,\n fillerFunction: () => V\n): V {\n let value = map.get(key);\n if (!value) {\n value = fillerFunction();\n map.set(key, value);\n }\n return value;\n}\n\n\n\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n"],"mappings":"AAAA,OAAO,SAASA,SAAS,CAACC,MAAc,EAAEC,EAAyB,EAAE;EACjE,IAAIC,KAAK,CAACF,MAAM,CAAC,CAACG,IAAI,CAAC,CAAC,CAAC,CAACC,OAAO,CAAC,UAACC,EAAE,EAAEC,GAAG;IAAA,OAAKL,EAAE,CAACK,GAAG,CAAC;EAAA,EAAC;AAC3D;AAEA,OAAO,SAASC,cAAc,CAAIC,GAAiC,EAAK;EACpE,IAAI,CAACA,GAAG,EAAE;IACN,MAAM,IAAIC,KAAK,CAAC,2BAA2B,CAAC;EAChD;EACA,OAAOD,GAAG;AACd;AAEA,OAAO,SAASE,aAAa,CAACF,GAAY,EAAU;EAChD,IAAI,CAACG,MAAM,CAACC,SAAS,CAACJ,GAAG,CAAC,EAAE;IACxB,MAAM,IAAIC,KAAK,CAAC,0BAA0B,CAAC;EAC/C;EACA,OAAOD,GAAG;AACd;AAGA,OAAO,SAASK,iBAAiB,CAAOC,GAAgC,EAAEC,GAAM,EAAK;EACjF,IAAMC,GAAG,GAAGF,GAAG,CAACG,GAAG,CAACF,GAAG,CAAC;EACxB,IAAI,OAAOC,GAAG,KAAK,WAAW,EAAE;IAC5B,MAAM,IAAIP,KAAK,CAAC,yBAAyB,GAAGM,GAAG,CAAC;EACpD;EACA,OAAOC,GAAG;AACd;AAEA,OAAO,SAASE,gBAAgB,CAC5BJ,GAAgC,EAChCC,GAAM,EACNI,cAAuB,EACtB;EACD,IAAIC,KAAK,GAAGN,GAAG,CAACG,GAAG,CAACF,GAAG,CAAC;EACxB,IAAI,CAACK,KAAK,EAAE;IACRA,KAAK,GAAGD,cAAc,EAAE;IACxBL,GAAG,CAACO,GAAG,CAACN,GAAG,EAAEK,KAAK,CAAC;EACvB;EACA,OAAOA,KAAK;AAChB;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAME,0BAA0B,GAAG;EACtCC,UAAU,EAAE,CAAC;EACbC,QAAQ,EAAE;AACd,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-promise.js b/dist/es/plugins/utils/utils-promise.js new file mode 100644 index 00000000000..166aed6c771 --- /dev/null +++ b/dist/es/plugins/utils/utils-promise.js @@ -0,0 +1,59 @@ +/** + * returns a promise that resolves on the next tick + */ +export function nextTick() { + return new Promise(function (res) { + return setTimeout(res, 0); + }); +} +export function promiseWait() { + var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + return new Promise(function (res) { + return setTimeout(res, ms); + }); +} +export function toPromise(maybePromise) { + if (maybePromise && typeof maybePromise.then === 'function') { + // is promise + return maybePromise; + } else { + return Promise.resolve(maybePromise); + } +} +export var PROMISE_RESOLVE_TRUE = Promise.resolve(true); +export var PROMISE_RESOLVE_FALSE = Promise.resolve(false); +export var PROMISE_RESOLVE_NULL = Promise.resolve(null); +export var PROMISE_RESOLVE_VOID = Promise.resolve(); +export function requestIdlePromise() { + var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + if (typeof window === 'object' && window['requestIdleCallback']) { + return new Promise(function (res) { + return window['requestIdleCallback'](res, { + timeout: timeout + }); + }); + } else { + return promiseWait(0); + } +} + +/** + * run the callback if requestIdleCallback available + * do nothing if not + * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback + */ +export function requestIdleCallbackIfAvailable(fun) { + if (typeof window === 'object' && window['requestIdleCallback']) window['requestIdleCallback'](fun); +} + +/** + * like Promise.all() but runs in series instead of parallel + * @link https://github.com/egoist/promise.series/blob/master/index.js + * @param tasks array with functions that return a promise + */ +export function promiseSeries(tasks, initial) { + return tasks.reduce(function (current, next) { + return current.then(next); + }, Promise.resolve(initial)); +} +//# sourceMappingURL=utils-promise.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-promise.js.map b/dist/es/plugins/utils/utils-promise.js.map new file mode 100644 index 00000000000..06829a18822 --- /dev/null +++ b/dist/es/plugins/utils/utils-promise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-promise.js","names":["nextTick","Promise","res","setTimeout","promiseWait","ms","toPromise","maybePromise","then","resolve","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_NULL","PROMISE_RESOLVE_VOID","requestIdlePromise","timeout","window","requestIdleCallbackIfAvailable","fun","promiseSeries","tasks","initial","reduce","current","next"],"sources":["../../../../src/plugins/utils/utils-promise.ts"],"sourcesContent":["/**\n * returns a promise that resolves on the next tick\n */\nexport function nextTick(): Promise {\n return new Promise(res => setTimeout(res, 0));\n}\n\nexport function promiseWait(ms: number = 0): Promise {\n return new Promise(res => setTimeout(res, ms));\n}\n\nexport function toPromise(maybePromise: Promise | T): Promise {\n if (maybePromise && typeof (maybePromise as any).then === 'function') {\n // is promise\n return maybePromise as any;\n } else {\n return Promise.resolve(maybePromise);\n }\n}\n\n\nexport const PROMISE_RESOLVE_TRUE: Promise = Promise.resolve(true);\nexport const PROMISE_RESOLVE_FALSE: Promise = Promise.resolve(false);\nexport const PROMISE_RESOLVE_NULL: Promise = Promise.resolve(null);\nexport const PROMISE_RESOLVE_VOID: Promise = Promise.resolve();\n\n\nexport function requestIdlePromise(timeout: number | null = null) {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) {\n return new Promise(\n res => (window as any)['requestIdleCallback'](res, {\n timeout\n })\n );\n } else {\n return promiseWait(0);\n }\n}\n\n\n/**\n * run the callback if requestIdleCallback available\n * do nothing if not\n * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback\n */\nexport function requestIdleCallbackIfAvailable(fun: Function): void {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) (window as any)['requestIdleCallback'](fun);\n}\n\n\n/**\n * like Promise.all() but runs in series instead of parallel\n * @link https://github.com/egoist/promise.series/blob/master/index.js\n * @param tasks array with functions that return a promise\n */\nexport function promiseSeries(\n tasks: Function[],\n initial?: any\n): Promise {\n return tasks\n .reduce(\n (current, next) => (current as any).then(next),\n Promise.resolve(initial)\n );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,SAASA,QAAQ,GAAkB;EACtC,OAAO,IAAIC,OAAO,CAAC,UAAAC,GAAG;IAAA,OAAIC,UAAU,CAACD,GAAG,EAAE,CAAC,CAAC;EAAA,EAAC;AACjD;AAEA,OAAO,SAASE,WAAW,GAAgC;EAAA,IAA/BC,EAAU,uEAAG,CAAC;EACtC,OAAO,IAAIJ,OAAO,CAAC,UAAAC,GAAG;IAAA,OAAIC,UAAU,CAACD,GAAG,EAAEG,EAAE,CAAC;EAAA,EAAC;AAClD;AAEA,OAAO,SAASC,SAAS,CAAIC,YAA4B,EAAc;EACnE,IAAIA,YAAY,IAAI,OAAQA,YAAY,CAASC,IAAI,KAAK,UAAU,EAAE;IAClE;IACA,OAAOD,YAAY;EACvB,CAAC,MAAM;IACH,OAAON,OAAO,CAACQ,OAAO,CAACF,YAAY,CAAC;EACxC;AACJ;AAGA,OAAO,IAAMG,oBAAmC,GAAGT,OAAO,CAACQ,OAAO,CAAC,IAAI,CAAC;AACxE,OAAO,IAAME,qBAAqC,GAAGV,OAAO,CAACQ,OAAO,CAAC,KAAK,CAAC;AAC3E,OAAO,IAAMG,oBAAmC,GAAGX,OAAO,CAACQ,OAAO,CAAC,IAAI,CAAC;AACxE,OAAO,IAAMI,oBAAmC,GAAGZ,OAAO,CAACQ,OAAO,EAAE;AAGpE,OAAO,SAASK,kBAAkB,GAAgC;EAAA,IAA/BC,OAAsB,uEAAG,IAAI;EAC5D,IACI,OAAOC,MAAM,KAAK,QAAQ,IACzBA,MAAM,CAAS,qBAAqB,CAAC,EACxC;IACE,OAAO,IAAIf,OAAO,CACd,UAAAC,GAAG;MAAA,OAAKc,MAAM,CAAS,qBAAqB,CAAC,CAACd,GAAG,EAAE;QAC/Ca,OAAO,EAAPA;MACJ,CAAC,CAAC;IAAA,EACL;EACL,CAAC,MAAM;IACH,OAAOX,WAAW,CAAC,CAAC,CAAC;EACzB;AACJ;;AAGA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASa,8BAA8B,CAACC,GAAa,EAAQ;EAChE,IACI,OAAOF,MAAM,KAAK,QAAQ,IACzBA,MAAM,CAAS,qBAAqB,CAAC,EACvCA,MAAM,CAAS,qBAAqB,CAAC,CAACE,GAAG,CAAC;AACjD;;AAGA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAa,CACzBC,KAAiB,EACjBC,OAAa,EACC;EACd,OAAOD,KAAK,CACPE,MAAM,CACH,UAACC,OAAO,EAAEC,IAAI;IAAA,OAAMD,OAAO,CAASf,IAAI,CAACgB,IAAI,CAAC;EAAA,GAC9CvB,OAAO,CAACQ,OAAO,CAACY,OAAO,CAAC,CAC3B;AACT"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-revision.js b/dist/es/plugins/utils/utils-revision.js new file mode 100644 index 00000000000..ea8e8df2f64 --- /dev/null +++ b/dist/es/plugins/utils/utils-revision.js @@ -0,0 +1,21 @@ +export function parseRevision(revision) { + var split = revision.split('-'); + return { + height: parseInt(split[0], 10), + hash: split[1] + }; +} +export function getHeightOfRevision(revision) { + return parseRevision(revision).height; +} + +/** + * Creates the next write revision for a given document. + */ +export function createRevision(databaseInstanceToken, previousDocData) { + var previousRevision = previousDocData ? previousDocData._rev : null; + var previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0; + var newRevisionHeight = previousRevisionHeigth + 1; + return newRevisionHeight + '-' + databaseInstanceToken; +} +//# sourceMappingURL=utils-revision.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-revision.js.map b/dist/es/plugins/utils/utils-revision.js.map new file mode 100644 index 00000000000..6db596284e4 --- /dev/null +++ b/dist/es/plugins/utils/utils-revision.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-revision.js","names":["parseRevision","revision","split","height","parseInt","hash","getHeightOfRevision","createRevision","databaseInstanceToken","previousDocData","previousRevision","_rev","previousRevisionHeigth","newRevisionHeight"],"sources":["../../../../src/plugins/utils/utils-revision.ts"],"sourcesContent":["import type {\n RxDocumentData\n} from '../../types';\n\nexport function parseRevision(revision: string): { height: number; hash: string; } {\n const split = revision.split('-');\n return {\n height: parseInt(split[0], 10),\n hash: split[1]\n };\n}\n\nexport function getHeightOfRevision(revision: string): number {\n return parseRevision(revision).height;\n}\n\n/**\n * Creates the next write revision for a given document.\n */\nexport function createRevision(\n databaseInstanceToken: string,\n previousDocData?: RxDocumentData\n): string {\n const previousRevision = previousDocData ? previousDocData._rev : null;\n const previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0;\n const newRevisionHeight = previousRevisionHeigth + 1;\n return newRevisionHeight + '-' + databaseInstanceToken;\n}\n\n"],"mappings":"AAIA,OAAO,SAASA,aAAa,CAACC,QAAgB,EAAqC;EAC/E,IAAMC,KAAK,GAAGD,QAAQ,CAACC,KAAK,CAAC,GAAG,CAAC;EACjC,OAAO;IACHC,MAAM,EAAEC,QAAQ,CAACF,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAC9BG,IAAI,EAAEH,KAAK,CAAC,CAAC;EACjB,CAAC;AACL;AAEA,OAAO,SAASI,mBAAmB,CAACL,QAAgB,EAAU;EAC1D,OAAOD,aAAa,CAACC,QAAQ,CAAC,CAACE,MAAM;AACzC;;AAEA;AACA;AACA;AACA,OAAO,SAASI,cAAc,CAC1BC,qBAA6B,EAC7BC,eAA2C,EACrC;EACN,IAAMC,gBAAgB,GAAGD,eAAe,GAAGA,eAAe,CAACE,IAAI,GAAG,IAAI;EACtE,IAAMC,sBAAsB,GAAGF,gBAAgB,GAAGV,aAAa,CAACU,gBAAgB,CAAC,CAACP,MAAM,GAAG,CAAC;EAC5F,IAAMU,iBAAiB,GAAGD,sBAAsB,GAAG,CAAC;EACpD,OAAOC,iBAAiB,GAAG,GAAG,GAAGL,qBAAqB;AAC1D"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-string.js b/dist/es/plugins/utils/utils-string.js new file mode 100644 index 00000000000..88c717d90a0 --- /dev/null +++ b/dist/es/plugins/utils/utils-string.js @@ -0,0 +1,55 @@ +/** + * get a random string which can be used with couchdb + * @link http://stackoverflow.com/a/1349426/3443137 + */ +export function randomCouchString() { + var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; + var text = ''; + var possible = 'abcdefghijklmnopqrstuvwxyz'; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} + +/** + * A random string that is never inside of any storage + */ +export var RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX'; + +/** + * uppercase first char + */ +export function ucfirst(str) { + str += ''; + var f = str.charAt(0).toUpperCase(); + return f + str.substr(1); +} + +/** + * removes trailing and ending dots from the string + */ +export function trimDots(str) { + // start + while (str.charAt(0) === '.') str = str.substr(1); + + // end + while (str.slice(-1) === '.') str = str.slice(0, -1); + return str; +} + +/** + * returns true if the given name is likely a folder path + */ +export function isFolderPath(name) { + // do not check, if foldername is given + if (name.includes('/') || + // unix + name.includes('\\') // windows + ) { + return true; + } else { + return false; + } +} +//# sourceMappingURL=utils-string.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-string.js.map b/dist/es/plugins/utils/utils-string.js.map new file mode 100644 index 00000000000..171c8438586 --- /dev/null +++ b/dist/es/plugins/utils/utils-string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-string.js","names":["randomCouchString","length","text","possible","i","charAt","Math","floor","random","RANDOM_STRING","ucfirst","str","f","toUpperCase","substr","trimDots","slice","isFolderPath","name","includes"],"sources":["../../../../src/plugins/utils/utils-string.ts"],"sourcesContent":["/**\n * get a random string which can be used with couchdb\n * @link http://stackoverflow.com/a/1349426/3443137\n */\nexport function randomCouchString(length: number = 10): string {\n let text = '';\n const possible = 'abcdefghijklmnopqrstuvwxyz';\n\n for (let i = 0; i < length; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n\n return text;\n}\n\n\n/**\n * A random string that is never inside of any storage\n */\nexport const RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX';\n\n/**\n * uppercase first char\n */\nexport function ucfirst(str: string): string {\n str += '';\n const f = str.charAt(0)\n .toUpperCase();\n return f + str.substr(1);\n}\n\n/**\n * removes trailing and ending dots from the string\n */\nexport function trimDots(str: string): string {\n // start\n while (str.charAt(0) === '.')\n str = str.substr(1);\n\n // end\n while (str.slice(-1) === '.')\n str = str.slice(0, -1);\n\n return str;\n}\n\n/**\n * returns true if the given name is likely a folder path\n */\nexport function isFolderPath(name: string) {\n // do not check, if foldername is given\n if (\n name.includes('/') || // unix\n name.includes('\\\\') // windows\n ) {\n return true;\n } else {\n return false;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,OAAO,SAASA,iBAAiB,GAA8B;EAAA,IAA7BC,MAAc,uEAAG,EAAE;EACjD,IAAIC,IAAI,GAAG,EAAE;EACb,IAAMC,QAAQ,GAAG,4BAA4B;EAE7C,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,MAAM,EAAEG,CAAC,EAAE,EAAE;IAC7BF,IAAI,IAAIC,QAAQ,CAACE,MAAM,CAACC,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,MAAM,EAAE,GAAGL,QAAQ,CAACF,MAAM,CAAC,CAAC;EACxE;EAEA,OAAOC,IAAI;AACf;;AAGA;AACA;AACA;AACA,OAAO,IAAMO,aAAa,GAAG,kCAAkC;;AAE/D;AACA;AACA;AACA,OAAO,SAASC,OAAO,CAACC,GAAW,EAAU;EACzCA,GAAG,IAAI,EAAE;EACT,IAAMC,CAAC,GAAGD,GAAG,CAACN,MAAM,CAAC,CAAC,CAAC,CAClBQ,WAAW,EAAE;EAClB,OAAOD,CAAC,GAAGD,GAAG,CAACG,MAAM,CAAC,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACA,OAAO,SAASC,QAAQ,CAACJ,GAAW,EAAU;EAC1C;EACA,OAAOA,GAAG,CAACN,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EACxBM,GAAG,GAAGA,GAAG,CAACG,MAAM,CAAC,CAAC,CAAC;;EAEvB;EACA,OAAOH,GAAG,CAACK,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EACxBL,GAAG,GAAGA,GAAG,CAACK,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EAE1B,OAAOL,GAAG;AACd;;AAEA;AACA;AACA;AACA,OAAO,SAASM,YAAY,CAACC,IAAY,EAAE;EACvC;EACA,IACIA,IAAI,CAACC,QAAQ,CAAC,GAAG,CAAC;EAAI;EACtBD,IAAI,CAACC,QAAQ,CAAC,IAAI,CAAC,CAAC;EAAA,EACtB;IACE,OAAO,IAAI;EACf,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-time.js b/dist/es/plugins/utils/utils-time.js new file mode 100644 index 00000000000..f04cd6d3648 --- /dev/null +++ b/dist/es/plugins/utils/utils-time.js @@ -0,0 +1,35 @@ +/** + * Returns the current unix time in milliseconds (with two decmials!) + * Because the accuracy of getTime() in javascript is bad, + * and we cannot rely on performance.now() on all platforms, + * this method implements a way to never return the same value twice. + * This ensures that when now() is called often, we do not loose the information + * about which call came first and which came after. + * + * We had to move from having no decimals, to having two decimal + * because it turned out that some storages are such fast that + * calling this method too often would return 'the future'. + */ +var _lastNow = 0; +/** + * Returns the current time in milliseconds, + * also ensures to not return the same value twice. + */ +export function now() { + var ret = new Date().getTime(); + ret = ret + 0.01; + if (ret <= _lastNow) { + ret = _lastNow + 0.01; + } + + /** + * Strip the returned number to max two decimals. + * In theory we would not need this but + * in practice JavaScript has no such good number precision + * so rounding errors could add another decimal place. + */ + var twoDecimals = parseFloat(ret.toFixed(2)); + _lastNow = twoDecimals; + return twoDecimals; +} +//# sourceMappingURL=utils-time.js.map \ No newline at end of file diff --git a/dist/es/plugins/utils/utils-time.js.map b/dist/es/plugins/utils/utils-time.js.map new file mode 100644 index 00000000000..7dd9df7ee94 --- /dev/null +++ b/dist/es/plugins/utils/utils-time.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-time.js","names":["_lastNow","now","ret","Date","getTime","twoDecimals","parseFloat","toFixed"],"sources":["../../../../src/plugins/utils/utils-time.ts"],"sourcesContent":["\n/**\n * Returns the current unix time in milliseconds (with two decmials!)\n * Because the accuracy of getTime() in javascript is bad,\n * and we cannot rely on performance.now() on all platforms,\n * this method implements a way to never return the same value twice.\n * This ensures that when now() is called often, we do not loose the information\n * about which call came first and which came after.\n *\n * We had to move from having no decimals, to having two decimal\n * because it turned out that some storages are such fast that\n * calling this method too often would return 'the future'.\n */\nlet _lastNow: number = 0;\n/**\n * Returns the current time in milliseconds,\n * also ensures to not return the same value twice.\n */\nexport function now(): number {\n let ret = new Date().getTime();\n ret = ret + 0.01;\n if (ret <= _lastNow) {\n ret = _lastNow + 0.01;\n }\n\n /**\n * Strip the returned number to max two decimals.\n * In theory we would not need this but\n * in practice JavaScript has no such good number precision\n * so rounding errors could add another decimal place.\n */\n const twoDecimals = parseFloat(ret.toFixed(2));\n\n _lastNow = twoDecimals;\n return twoDecimals;\n}\n"],"mappings":"AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIA,QAAgB,GAAG,CAAC;AACxB;AACA;AACA;AACA;AACA,OAAO,SAASC,GAAG,GAAW;EAC1B,IAAIC,GAAG,GAAG,IAAIC,IAAI,EAAE,CAACC,OAAO,EAAE;EAC9BF,GAAG,GAAGA,GAAG,GAAG,IAAI;EAChB,IAAIA,GAAG,IAAIF,QAAQ,EAAE;IACjBE,GAAG,GAAGF,QAAQ,GAAG,IAAI;EACzB;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMK,WAAW,GAAGC,UAAU,CAACJ,GAAG,CAACK,OAAO,CAAC,CAAC,CAAC,CAAC;EAE9CP,QAAQ,GAAGK,WAAW;EACtB,OAAOA,WAAW;AACtB"} \ No newline at end of file diff --git a/dist/es/plugins/validate-ajv/index.js b/dist/es/plugins/validate-ajv/index.js index 27823f242c5..0179e1d3f2e 100644 --- a/dist/es/plugins/validate-ajv/index.js +++ b/dist/es/plugins/validate-ajv/index.js @@ -4,7 +4,6 @@ * @link https://github.com/epoberezkin/ajv */ import Ajv from 'ajv'; -import { newRxError } from '../../rx-error'; import { wrappedValidateStorageFactory } from '../../plugin-helpers'; var ajv = new Ajv({ strict: false @@ -13,12 +12,10 @@ export function getValidator(schema) { var validator = ajv.compile(schema); return function (docData) { var isValid = validator(docData); - if (!isValid) { - throw newRxError('VD2', { - errors: validator.errors, - document: docData, - schema: schema - }); + if (isValid) { + return []; + } else { + return validator.errors; } }; } diff --git a/dist/es/plugins/validate-ajv/index.js.map b/dist/es/plugins/validate-ajv/index.js.map index b457c03df17..306943bb4d4 100644 --- a/dist/es/plugins/validate-ajv/index.js.map +++ b/dist/es/plugins/validate-ajv/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["Ajv","newRxError","wrappedValidateStorageFactory","ajv","strict","getValidator","schema","validator","compile","docData","isValid","errors","document","wrappedValidateAjvStorage"],"sources":["../../../../src/plugins/validate-ajv/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using ajv as jsonschema-validator\n * @link https://github.com/epoberezkin/ajv\n */\nimport Ajv from 'ajv';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nconst ajv = new Ajv({\n strict: false\n});\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = ajv.compile(schema);\n return (docData: RxDocumentData) => {\n const isValid = validator(docData);\n if (!isValid) {\n throw newRxError('VD2', {\n errors: validator.errors as any,\n document: docData,\n schema\n });\n }\n };\n}\n\nexport const wrappedValidateAjvStorage = wrappedValidateStorageFactory(\n getValidator,\n 'ajv'\n);\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,GAAG,MAAM,KAAK;AACrB,SACIC,UAAU,QACP,gBAAgB;AAKvB,SAASC,6BAA6B,QAAQ,sBAAsB;AAGpE,IAAMC,GAAG,GAAG,IAAIH,GAAG,CAAC;EAChBI,MAAM,EAAE;AACZ,CAAC,CAAC;AAGF,OAAO,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAGJ,GAAG,CAACK,OAAO,CAACF,MAAM,CAAC;EACrC,OAAO,UAACG,OAA4B,EAAK;IACrC,IAAMC,OAAO,GAAGH,SAAS,CAACE,OAAO,CAAC;IAClC,IAAI,CAACC,OAAO,EAAE;MACV,MAAMT,UAAU,CAAC,KAAK,EAAE;QACpBU,MAAM,EAAEJ,SAAS,CAACI,MAAa;QAC/BC,QAAQ,EAAEH,OAAO;QACjBH,MAAM,EAANA;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;AACL;AAEA,OAAO,IAAMO,yBAAyB,GAAGX,6BAA6B,CAClEG,YAAY,EACZ,KAAK,CACR"} \ No newline at end of file +{"version":3,"file":"index.js","names":["Ajv","wrappedValidateStorageFactory","ajv","strict","getValidator","schema","validator","compile","docData","isValid","errors","wrappedValidateAjvStorage"],"sources":["../../../../src/plugins/validate-ajv/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using ajv as jsonschema-validator\n * @link https://github.com/epoberezkin/ajv\n */\nimport Ajv from 'ajv';\nimport type {\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nconst ajv = new Ajv({\n strict: false\n});\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = ajv.compile(schema);\n return (docData: RxDocumentData) => {\n const isValid = validator(docData);\n if (isValid) {\n return [];\n } else {\n return validator.errors as any;\n }\n };\n}\n\nexport const wrappedValidateAjvStorage = wrappedValidateStorageFactory(\n getValidator,\n 'ajv'\n);\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,GAAG,MAAM,KAAK;AAKrB,SAASC,6BAA6B,QAAQ,sBAAsB;AAGpE,IAAMC,GAAG,GAAG,IAAIF,GAAG,CAAC;EAChBG,MAAM,EAAE;AACZ,CAAC,CAAC;AAGF,OAAO,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAGJ,GAAG,CAACK,OAAO,CAACF,MAAM,CAAC;EACrC,OAAO,UAACG,OAA4B,EAAK;IACrC,IAAMC,OAAO,GAAGH,SAAS,CAACE,OAAO,CAAC;IAClC,IAAIC,OAAO,EAAE;MACT,OAAO,EAAE;IACb,CAAC,MAAM;MACH,OAAOH,SAAS,CAACI,MAAM;IAC3B;EACJ,CAAC;AACL;AAEA,OAAO,IAAMC,yBAAyB,GAAGV,6BAA6B,CAClEG,YAAY,EACZ,KAAK,CACR"} \ No newline at end of file diff --git a/dist/es/plugins/validate-is-my-json-valid/index.js b/dist/es/plugins/validate-is-my-json-valid/index.js index 652f908c3e7..7b71b2c0bb8 100644 --- a/dist/es/plugins/validate-is-my-json-valid/index.js +++ b/dist/es/plugins/validate-is-my-json-valid/index.js @@ -4,18 +4,15 @@ * @link https://github.com/mafintosh/is-my-json-valid */ import isMyJsonValid from 'is-my-json-valid'; -import { newRxError } from '../../rx-error'; import { wrappedValidateStorageFactory } from '../../plugin-helpers'; export function getValidator(schema) { var validator = isMyJsonValid(schema); return function (docData) { var isValid = validator(docData); - if (!isValid) { - throw newRxError('VD2', { - errors: validator.errors, - document: docData, - schema: schema - }); + if (isValid) { + return []; + } else { + return validator.errors; } }; } diff --git a/dist/es/plugins/validate-is-my-json-valid/index.js.map b/dist/es/plugins/validate-is-my-json-valid/index.js.map index d6259736d86..f81a060f533 100644 --- a/dist/es/plugins/validate-is-my-json-valid/index.js.map +++ b/dist/es/plugins/validate-is-my-json-valid/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["isMyJsonValid","newRxError","wrappedValidateStorageFactory","getValidator","schema","validator","docData","isValid","errors","document","wrappedValidateIsMyJsonValidStorage"],"sources":["../../../../src/plugins/validate-is-my-json-valid/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using is-my-json-valid as jsonschema-validator\n * @link https://github.com/mafintosh/is-my-json-valid\n */\nimport isMyJsonValid from 'is-my-json-valid';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = isMyJsonValid(schema as any);\n return (docData: any) => {\n const isValid = validator(docData);\n if (!isValid) {\n throw newRxError('VD2', {\n errors: validator.errors,\n document: docData,\n schema\n });\n }\n };\n}\n\nexport const wrappedValidateIsMyJsonValidStorage = wrappedValidateStorageFactory(\n getValidator,\n 'is-my-json-valid'\n);\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,aAAa,MAAM,kBAAkB;AAC5C,SACIC,UAAU,QACP,gBAAgB;AAIvB,SAASC,6BAA6B,QAAQ,sBAAsB;AAGpE,OAAO,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAGL,aAAa,CAACI,MAAM,CAAQ;EAC9C,OAAO,UAACE,OAAY,EAAK;IACrB,IAAMC,OAAO,GAAGF,SAAS,CAACC,OAAO,CAAC;IAClC,IAAI,CAACC,OAAO,EAAE;MACV,MAAMN,UAAU,CAAC,KAAK,EAAE;QACpBO,MAAM,EAAEH,SAAS,CAACG,MAAM;QACxBC,QAAQ,EAAEH,OAAO;QACjBF,MAAM,EAANA;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;AACL;AAEA,OAAO,IAAMM,mCAAmC,GAAGR,6BAA6B,CAC5EC,YAAY,EACZ,kBAAkB,CACrB"} \ No newline at end of file +{"version":3,"file":"index.js","names":["isMyJsonValid","wrappedValidateStorageFactory","getValidator","schema","validator","docData","isValid","errors","wrappedValidateIsMyJsonValidStorage"],"sources":["../../../../src/plugins/validate-is-my-json-valid/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using is-my-json-valid as jsonschema-validator\n * @link https://github.com/mafintosh/is-my-json-valid\n */\nimport isMyJsonValid from 'is-my-json-valid';\nimport type {\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = isMyJsonValid(schema as any);\n return (docData: any) => {\n const isValid = validator(docData);\n if (isValid) {\n return [];\n } else {\n return validator.errors as any;\n }\n };\n}\n\nexport const wrappedValidateIsMyJsonValidStorage = wrappedValidateStorageFactory(\n getValidator,\n 'is-my-json-valid'\n);\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,aAAa,MAAM,kBAAkB;AAI5C,SAASC,6BAA6B,QAAQ,sBAAsB;AAGpE,OAAO,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAGJ,aAAa,CAACG,MAAM,CAAQ;EAC9C,OAAO,UAACE,OAAY,EAAK;IACrB,IAAMC,OAAO,GAAGF,SAAS,CAACC,OAAO,CAAC;IAClC,IAAIC,OAAO,EAAE;MACT,OAAO,EAAE;IACb,CAAC,MAAM;MACH,OAAOF,SAAS,CAACG,MAAM;IAC3B;EACJ,CAAC;AACL;AAEA,OAAO,IAAMC,mCAAmC,GAAGP,6BAA6B,CAC5EC,YAAY,EACZ,kBAAkB,CACrB"} \ No newline at end of file diff --git a/dist/es/plugins/validate-z-schema/index.js b/dist/es/plugins/validate-z-schema/index.js index efdc5713a70..ad28c39b6b6 100644 --- a/dist/es/plugins/validate-z-schema/index.js +++ b/dist/es/plugins/validate-z-schema/index.js @@ -4,7 +4,6 @@ * @link https://github.com/zaggino/z-schema */ import ZSchema from 'z-schema'; -import { newRxError } from '../../rx-error'; import { wrappedValidateStorageFactory } from '../../plugin-helpers'; export function getValidator(schema) { var validatorInstance = new ZSchema(); @@ -29,11 +28,9 @@ export function getValidator(schema) { message: message }; }); - throw newRxError('VD2', { - errors: formattedZSchemaErrors, - document: docData, - schema: schema - }); + return formattedZSchemaErrors; + } else { + return []; } }; } diff --git a/dist/es/plugins/validate-z-schema/index.js.map b/dist/es/plugins/validate-z-schema/index.js.map index e8ef8b8262f..6b5c5b5bb7f 100644 --- a/dist/es/plugins/validate-z-schema/index.js.map +++ b/dist/es/plugins/validate-z-schema/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ZSchema","newRxError","wrappedValidateStorageFactory","getValidator","schema","validatorInstance","validator","obj","validate","docData","useValidator","errors","getLastErrors","formattedZSchemaErrors","map","title","description","message","document","wrappedValidateZSchemaStorage"],"sources":["../../../../src/plugins/validate-z-schema/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using z-schema as jsonschema-validator\n * @link https://github.com/zaggino/z-schema\n */\nimport ZSchema from 'z-schema';\nimport {\n newRxError\n} from '../../rx-error';\nimport type { RxJsonSchema } from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validatorInstance = new (ZSchema as any)();\n const validator = (obj: any) => {\n validatorInstance.validate(obj, schema);\n return validatorInstance;\n };\n return (docData: any) => {\n const useValidator = validator(docData);\n if (useValidator === true) {\n return;\n }\n const errors: ZSchema.SchemaErrorDetail[] = (useValidator as any).getLastErrors();\n if (errors) {\n const formattedZSchemaErrors = (errors as any).map(({\n title,\n description,\n message\n }: any) => ({\n title,\n description,\n message\n }));\n throw newRxError('VD2', {\n errors: formattedZSchemaErrors,\n document: docData,\n schema\n });\n }\n };\n}\n\nexport const wrappedValidateZSchemaStorage = wrappedValidateStorageFactory(\n getValidator,\n 'z-schema'\n);\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,OAAO,MAAM,UAAU;AAC9B,SACIC,UAAU,QACP,gBAAgB;AAEvB,SAASC,6BAA6B,QAAQ,sBAAsB;AAGpE,OAAO,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,iBAAiB,GAAG,IAAKL,OAAO,EAAU;EAChD,IAAMM,SAAS,GAAG,SAAZA,SAAS,CAAIC,GAAQ,EAAK;IAC5BF,iBAAiB,CAACG,QAAQ,CAACD,GAAG,EAAEH,MAAM,CAAC;IACvC,OAAOC,iBAAiB;EAC5B,CAAC;EACD,OAAO,UAACI,OAAY,EAAK;IACrB,IAAMC,YAAY,GAAGJ,SAAS,CAACG,OAAO,CAAC;IACvC,IAAIC,YAAY,KAAK,IAAI,EAAE;MACvB;IACJ;IACA,IAAMC,MAAmC,GAAID,YAAY,CAASE,aAAa,EAAE;IACjF,IAAID,MAAM,EAAE;MACR,IAAME,sBAAsB,GAAIF,MAAM,CAASG,GAAG,CAAC;QAAA,IAC/CC,KAAK,QAALA,KAAK;UACLC,WAAW,QAAXA,WAAW;UACXC,OAAO,QAAPA,OAAO;QAAA,OACC;UACRF,KAAK,EAALA,KAAK;UACLC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA;QACJ,CAAC;MAAA,CAAC,CAAC;MACH,MAAMhB,UAAU,CAAC,KAAK,EAAE;QACpBU,MAAM,EAAEE,sBAAsB;QAC9BK,QAAQ,EAAET,OAAO;QACjBL,MAAM,EAANA;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;AACL;AAEA,OAAO,IAAMe,6BAA6B,GAAGjB,6BAA6B,CACtEC,YAAY,EACZ,UAAU,CACb"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ZSchema","wrappedValidateStorageFactory","getValidator","schema","validatorInstance","validator","obj","validate","docData","useValidator","errors","getLastErrors","formattedZSchemaErrors","map","title","description","message","wrappedValidateZSchemaStorage"],"sources":["../../../../src/plugins/validate-z-schema/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using z-schema as jsonschema-validator\n * @link https://github.com/zaggino/z-schema\n */\nimport ZSchema from 'z-schema';\nimport type { RxJsonSchema } from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validatorInstance = new (ZSchema as any)();\n const validator = (obj: any) => {\n validatorInstance.validate(obj, schema);\n return validatorInstance;\n };\n return (docData: any) => {\n const useValidator = validator(docData);\n if (useValidator === true) {\n return;\n }\n const errors: ZSchema.SchemaErrorDetail[] = (useValidator as any).getLastErrors();\n if (errors) {\n const formattedZSchemaErrors = (errors as any).map(({\n title,\n description,\n message\n }: any) => ({\n title,\n description,\n message\n }));\n return formattedZSchemaErrors;\n } else {\n return [];\n }\n };\n}\n\nexport const wrappedValidateZSchemaStorage = wrappedValidateStorageFactory(\n getValidator,\n 'z-schema'\n);\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,OAAOA,OAAO,MAAM,UAAU;AAE9B,SAASC,6BAA6B,QAAQ,sBAAsB;AAGpE,OAAO,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,iBAAiB,GAAG,IAAKJ,OAAO,EAAU;EAChD,IAAMK,SAAS,GAAG,SAAZA,SAAS,CAAIC,GAAQ,EAAK;IAC5BF,iBAAiB,CAACG,QAAQ,CAACD,GAAG,EAAEH,MAAM,CAAC;IACvC,OAAOC,iBAAiB;EAC5B,CAAC;EACD,OAAO,UAACI,OAAY,EAAK;IACrB,IAAMC,YAAY,GAAGJ,SAAS,CAACG,OAAO,CAAC;IACvC,IAAIC,YAAY,KAAK,IAAI,EAAE;MACvB;IACJ;IACA,IAAMC,MAAmC,GAAID,YAAY,CAASE,aAAa,EAAE;IACjF,IAAID,MAAM,EAAE;MACR,IAAME,sBAAsB,GAAIF,MAAM,CAASG,GAAG,CAAC;QAAA,IAC/CC,KAAK,QAALA,KAAK;UACLC,WAAW,QAAXA,WAAW;UACXC,OAAO,QAAPA,OAAO;QAAA,OACC;UACRF,KAAK,EAALA,KAAK;UACLC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA;QACJ,CAAC;MAAA,CAAC,CAAC;MACH,OAAOJ,sBAAsB;IACjC,CAAC,MAAM;MACH,OAAO,EAAE;IACb;EACJ,CAAC;AACL;AAEA,OAAO,IAAMK,6BAA6B,GAAGhB,6BAA6B,CACtEC,YAAY,EACZ,UAAU,CACb"} \ No newline at end of file diff --git a/dist/es/plugins/worker/in-worker.js.map b/dist/es/plugins/worker/in-worker.js.map deleted file mode 100644 index 0d19f624a16..00000000000 --- a/dist/es/plugins/worker/in-worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"in-worker.js","names":["expose","getFromMapOrThrow","wrappedWorkerRxStorage","args","nextId","instanceById","Map","exposeMe","createStorageInstance","params","instanceId","storage","instance","set","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","cleanup","minDeletedTime","close","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution"],"sources":["../../../../src/plugins/worker/in-worker.ts"],"sourcesContent":["/**\n * This file contains everything\n * that is supposed to run inside of the worker.\n */\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types';\nimport { expose } from 'threads/worker';\nimport { getFromMapOrThrow } from '../../util';\nimport { Observable } from 'rxjs';\n\n\nexport type InWorkerStorage = {\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise;\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise>;\n findDocumentsById(\n instanceId: number,\n ids: string[], deleted: boolean\n ): Promise>;\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise>;\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise;\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise;\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }>;\n changeStream(\n instanceById: number\n ): Observable>, CheckpointType>>;\n cleanup(instanceId: number, minDeletedTime: number): Promise;\n close(instanceId: number): Promise;\n remove(instanceId: number): Promise;\n\n conflictResultionTasks(\n instanceById: number\n ): Observable>;\n resolveConflictResultionTask(\n instanceById: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise;\n};\n\nexport function wrappedWorkerRxStorage(\n args: {\n storage: RxStorage;\n }\n) {\n let nextId = 0;\n const instanceById: Map = new Map();\n\n const exposeMe: InWorkerStorage = {\n /**\n * RxStorageInstance\n */\n async createStorageInstance(params) {\n const instanceId = nextId++;\n const instance = await args.storage.createStorageInstance(params);\n instanceById.set(instanceId, instance);\n return instanceId;\n },\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.bulkWrite(documentWrites, context);\n },\n findDocumentsById(\n instanceId: number,\n ids: string[],\n deleted: boolean\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.findDocumentsById(ids, deleted);\n },\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.query(preparedQuery);\n },\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.count(preparedQuery);\n },\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getAttachmentData(\n documentId,\n attachmentId\n );\n },\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint: any\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getChangedDocumentsSince(\n limit,\n checkpoint\n );\n },\n changeStream(\n instanceId: number\n ): Observable>, CheckpointType>> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.changeStream();\n },\n cleanup(\n instanceId: number,\n minDeletedTime: number\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.cleanup(minDeletedTime);\n },\n close(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.close();\n },\n remove(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.remove();\n },\n\n conflictResultionTasks(\n instanceId: number\n ): Observable> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.conflictResultionTasks();\n },\n resolveConflictResultionTask(\n instanceId: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.resolveConflictResultionTask(taskSolution);\n }\n };\n expose(exposeMe);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAeA,SAASA,MAAM,QAAQ,gBAAgB;AACvC,SAASC,iBAAiB,QAAQ,YAAY;AAsD9C,OAAO,SAASC,sBAAsB,CAClCC,IAEC,EACH;EACE,IAAIC,MAAM,GAAG,CAAC;EACd,IAAMC,YAA8B,GAAG,IAAIC,GAAG,EAAE;EAEhD,IAAMC,QAA8C,GAAG;IACnD;AACR;AACA;IACcC,qBAAqB,iCAACC,MAAM;MAAA,IAAE;QAChC,IAAMC,WAAU,GAAGN,MAAM,EAAE;QAAC,uBACLD,IAAI,CAACQ,OAAO,CAACH,qBAAqB,CAACC,MAAM,CAAC,iBAA3DG,QAAQ;UACdP,YAAY,CAACQ,GAAG,CAACH,WAAU,EAAEE,QAAQ,CAAC;UACtC,OAAOF,WAAU;QAAC;MACtB,CAAC;QAAA;MAAA;IAAA;IACDI,SAAS,qBACLJ,UAAkB,EAClBK,cAA4C,EAC5CC,OAAe,EACjB;MACE,IAAMJ,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACE,SAAS,CAACC,cAAc,EAAEC,OAAO,CAAC;IACtD,CAAC;IACDC,iBAAiB,6BACbP,UAAkB,EAClBQ,GAAa,EACbC,OAAgB,EACyB;MACzC,IAAMP,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACK,iBAAiB,CAACC,GAAG,EAAEC,OAAO,CAAC;IACnD,CAAC;IACDC,KAAK,iBACDV,UAAkB,EAClBW,aAAkB,EACyB;MAC3C,IAAMT,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACQ,KAAK,CAACC,aAAa,CAAC;IACxC,CA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C5B,CAAC;IAEDC,sBAAsB,kCAClBxB,UAAkB,EAC4B;MAC9C,IAAME,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACsB,sBAAsB,EAAE;IAC5C,CAAC;IACDC,4BAA4B,wCACxBzB,UAAkB,EAClB0B,YAAwD,EAC3C;MACb,IAAMxB,QAAQ,GAAGX,iBAAiB,CAACI,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACuB,4BAA4B,CAACC,YAAY,CAAC;IAC9D;EACJ,CAAC;EACDpC,MAAM,CAACO,QAAQ,CAAC;AACpB"} \ No newline at end of file diff --git a/dist/es/plugins/worker/index.js.map b/dist/es/plugins/worker/index.js.map deleted file mode 100644 index 95f293a95bf..00000000000 --- a/dist/es/plugins/worker/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/worker/index.ts"],"sourcesContent":["export * from './in-worker';\nexport * from './non-worker';\n"],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,cAAc"} \ No newline at end of file diff --git a/dist/es/plugins/worker/non-worker.js.map b/dist/es/plugins/worker/non-worker.js.map deleted file mode 100644 index 74524fc4e82..00000000000 --- a/dist/es/plugins/worker/non-worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"non-worker.js","names":["Subject","spawn","Worker","Thread","ensureNotFalsy","getFromMapOrThrow","removeWorkerRef","instance","workerState","WORKER_BY_INSTANCE","storage","refs","size","workerPromise","then","worker","terminate","Map","RxStorageWorker","settings","statics","name","createStorageInstance","params","get","workerInput","Set","set","instanceId","RxStorageInstanceWorker","databaseName","collectionName","schema","rxStorage","options","add","internals","changes$","conflicts$","subs","closed","push","changeStream","subscribe","ev","next","conflictResultionTasks","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","asObservable","cleanup","minDeletedTime","close","Promise","reject","Error","forEach","sub","unsubscribe","remove","resolveConflictResultionTask","taskSolution","getRxStorageWorker"],"sources":["../../../../src/plugins/worker/non-worker.ts"],"sourcesContent":["import {\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n spawn,\n Worker,\n Thread\n} from 'threads';\nimport type {\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageInstance,\n BulkWriteRow,\n RxDocumentData,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageQueryResult,\n EventBulk,\n RxStorageStatics,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageCountResult\n} from '../../types';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from '../../util';\nimport { InWorkerStorage } from './in-worker';\n\ndeclare type WorkerStorageInternals = {\n rxStorage: RxStorageWorker;\n instanceId: number;\n worker: InWorkerStorage;\n};\ndeclare type RxStorageWorkerSettings = {\n statics: RxStorageStatics;\n workerInput: any;\n};\n\n\n/**\n * We have no way to detect if a worker is no longer needed.\n * So we create the worker process on the first RxStorageInstance\n * and have to close it again of no more RxStorageInstances are non-closed.\n */\nconst WORKER_BY_INSTANCE: Map>;\n refs: Set>;\n}> = new Map();\n\nexport class RxStorageWorker implements RxStorage {\n public name = 'worker';\n\n constructor(\n public readonly settings: RxStorageWorkerSettings,\n public readonly statics: RxStorageStatics\n ) { }\n\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n let workerState = WORKER_BY_INSTANCE.get(this);\n if (!workerState) {\n workerState = {\n workerPromise: spawn>(new Worker(this.settings.workerInput)) as any,\n refs: new Set()\n };\n WORKER_BY_INSTANCE.set(this, workerState);\n }\n\n return workerState.workerPromise.then(worker => {\n return worker.createStorageInstance(params)\n .then(instanceId => {\n const instance = new RxStorageInstanceWorker(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n rxStorage: this,\n instanceId,\n worker\n },\n params.options\n );\n ensureNotFalsy(workerState).refs.add(instance);\n return instance;\n });\n });\n }\n}\n\n\nexport class RxStorageInstanceWorker implements RxStorageInstance {\n /**\n * threads.js uses observable-fns instead of rxjs\n * so we have to transform it.\n */\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n\n constructor(\n public readonly storage: RxStorageWorker,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: WorkerStorageInternals,\n public readonly options: Readonly\n ) {\n this.subs.push(\n this.internals.worker.changeStream(\n this.internals.instanceId\n ).subscribe(ev => this.changes$.next(ev as any))\n );\n this.subs.push(\n this.internals.worker.conflictResultionTasks(\n this.internals.instanceId\n ).subscribe(ev => this.conflicts$.next(ev as any))\n );\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.internals.worker.bulkWrite(\n this.internals.instanceId,\n documentWrites,\n context\n );\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.internals.worker.findDocumentsById(\n this.internals.instanceId,\n ids,\n deleted\n );\n }\n query(preparedQuery: any): Promise> {\n return this.internals.worker.query(\n this.internals.instanceId,\n preparedQuery\n );\n }\n count(preparedQuery: any): Promise {\n return this.internals.worker.count(\n this.internals.instanceId,\n preparedQuery\n );\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.internals.worker.getAttachmentData(\n this.internals.instanceId,\n documentId,\n attachmentId\n );\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ) {\n return this.internals.worker.getChangedDocumentsSince(\n this.internals.instanceId,\n limit,\n checkpoint\n );\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number) {\n return this.internals.worker.cleanup(\n this.internals.instanceId,\n minDeletedTime\n );\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n await this.internals.worker.close(\n this.internals.instanceId\n );\n await removeWorkerRef(this);\n }\n async remove(): Promise {\n await this.internals.worker.remove(\n this.internals.instanceId\n );\n this.closed = true;\n await removeWorkerRef(this);\n }\n\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.internals.worker.resolveConflictResultionTask(\n this.internals.instanceId,\n taskSolution\n );\n }\n\n}\n\nexport function getRxStorageWorker(\n settings: RxStorageWorkerSettings\n): RxStorageWorker {\n const storage = new RxStorageWorker(settings, settings.statics);\n return storage;\n}\n\n/**\n * TODO we have a bug.\n * When the exact same RxStorage opens and closes\n * many RxStorage instances, then it might happen\n * that some calls to createStorageInstance() time out,\n * because the worker thread is in the closing state.\n */\nexport async function removeWorkerRef(\n instance: RxStorageInstanceWorker\n) {\n const workerState = getFromMapOrThrow(WORKER_BY_INSTANCE, instance.storage);\n workerState.refs.delete(instance);\n if (workerState.refs.size === 0) {\n WORKER_BY_INSTANCE.delete(instance.storage);\n await workerState.workerPromise\n .then(worker => Thread.terminate(worker as any));\n }\n}\n"],"mappings":"AAAA,SAEIA,OAAO,QAEJ,MAAM;AACb,SACIC,KAAK,EACLC,MAAM,EACNC,MAAM,QACH,SAAS;AAkBhB,SACIC,cAAc,EACdC,iBAAiB,QACd,YAAY;AA+LnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAsBC,eAAe,YAAfA,eAAe,CACjCC,QAAsC;EAAA,IACxC;IACE,IAAMC,WAAW,GAAGH,iBAAiB,CAACI,kBAAkB,EAAEF,QAAQ,CAACG,OAAO,CAAC;IAC3EF,WAAW,CAACG,IAAI,UAAO,CAACJ,QAAQ,CAAC;IAAC;MAAA,IAC9BC,WAAW,CAACG,IAAI,CAACC,IAAI,KAAK,CAAC;QAC3BH,kBAAkB,UAAO,CAACF,QAAQ,CAACG,OAAO,CAAC;QAAC,uBACtCF,W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AQ,CAACC,OAAO,CAAC;EAC/D,OAAOV,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/dexie-memory.worker.js.map b/dist/es/plugins/worker/workers/dexie-memory.worker.js.map deleted file mode 100644 index 17049031ee2..00000000000 --- a/dist/es/plugins/worker/workers/dexie-memory.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-memory.worker.js","names":["getRxStorageDexie","wrappedWorkerRxStorage","indexedDB","IDBKeyRange","storage"],"sources":["../../../../../src/plugins/worker/workers/dexie-memory.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../dexie';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nimport {\n indexedDB,\n IDBKeyRange\n} from 'fake-indexeddb';\n\nconst storage = getRxStorageDexie({\n indexedDB,\n IDBKeyRange\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,aAAa;AAC/C,SAASC,sBAAsB,QAAQ,cAAc;AAErD,SACIC,SAAS,EACTC,WAAW,QACR,gBAAgB;AAEvB,IAAMC,OAAO,GAAGJ,iBAAiB,CAAC;EAC9BE,SAAS,EAATA,SAAS;EACTC,WAAW,EAAXA;AACJ,CAAC,CAAC;AACFF,sBAAsB,CAAC;EACnBG,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/dexie.worker.js.map b/dist/es/plugins/worker/workers/dexie.worker.js.map deleted file mode 100644 index 3cf6e618a20..00000000000 --- a/dist/es/plugins/worker/workers/dexie.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie.worker.js","names":["getRxStorageDexie","wrappedWorkerRxStorage","storage"],"sources":["../../../../../src/plugins/worker/workers/dexie.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../dexie';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nconst storage = getRxStorageDexie();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,aAAa;AAC/C,SAASC,sBAAsB,QAAQ,cAAc;AAErD,IAAMC,OAAO,GAAGF,iBAAiB,EAAE;AACnCC,sBAAsB,CAAC;EACnBC,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-fs.worker.js.map b/dist/es/plugins/worker/workers/lokijs-fs.worker.js.map deleted file mode 100644 index 31701f29f40..00000000000 --- a/dist/es/plugins/worker/workers/lokijs-fs.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-fs.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","lfsa","require","adapter","storage"],"sources":["../../../../../src/plugins/worker/workers/lokijs-fs.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nconst lfsa = require('lokijs/src/loki-fs-structured-adapter.js');\nconst adapter = new lfsa();\nconst storage = getRxStorageLoki({\n adapter\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,sBAAsB,QAAQ,cAAc;AAErD,IAAMC,IAAI,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAChE,IAAMC,OAAO,GAAG,IAAIF,IAAI,EAAE;AAC1B,IAAMG,OAAO,GAAGL,gBAAgB,CAAC;EAC7BI,OAAO,EAAPA;AACJ,CAAC,CAAC;AACFH,sBAAsB,CAAC;EACnBI,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js.map b/dist/es/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js.map deleted file mode 100644 index 036c395162e..00000000000 --- a/dist/es/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-incremental-indexeddb.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","LokiIncrementalIndexedDBAdapter","require","storage","adapter"],"sources":["../../../../../src/plugins/worker/workers/lokijs-incremental-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\nconst LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIncrementalIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,sBAAsB,QAAQ,cAAc;AACrD,IAAMC,+BAA+B,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAE3F,IAAMC,OAAO,GAAGJ,gBAAgB,CAAC;EAC7BK,OAAO,EAAE,IAAIH,+BAA+B;AAChD,CAAC,CAAC;AACFD,sBAAsB,CAAC;EACnBG,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-indexeddb.worker.js.map b/dist/es/plugins/worker/workers/lokijs-indexeddb.worker.js.map deleted file mode 100644 index 2e769d450e1..00000000000 --- a/dist/es/plugins/worker/workers/lokijs-indexeddb.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-indexeddb.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","LokiIndexedDBAdapter","require","storage","adapter"],"sources":["../../../../../src/plugins/worker/workers/lokijs-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\nconst LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,sBAAsB,QAAQ,cAAc;AACrD,IAAMC,oBAAoB,GAAGC,OAAO,CAAC,iCAAiC,CAAC;AAEvE,IAAMC,OAAO,GAAGJ,gBAAgB,CAAC;EAC7BK,OAAO,EAAE,IAAIH,oBAAoB;AACrC,CAAC,CAAC;AACFD,sBAAsB,CAAC;EACnBG,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/lokijs-memory.worker.js.map b/dist/es/plugins/worker/workers/lokijs-memory.worker.js.map deleted file mode 100644 index b5d5408bcf0..00000000000 --- a/dist/es/plugins/worker/workers/lokijs-memory.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-memory.worker.js","names":["getRxStorageLoki","wrappedWorkerRxStorage","storage"],"sources":["../../../../../src/plugins/worker/workers/lokijs-memory.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nconst storage = getRxStorageLoki();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,sBAAsB,QAAQ,cAAc;AAErD,IAAMC,OAAO,GAAGF,gBAAgB,EAAE;AAClCC,sBAAsB,CAAC;EACnBC,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/pouchdb-idb.worker.js b/dist/es/plugins/worker/workers/pouchdb-idb.worker.js deleted file mode 100644 index d16d89f493c..00000000000 --- a/dist/es/plugins/worker/workers/pouchdb-idb.worker.js +++ /dev/null @@ -1,10 +0,0 @@ -import { getRxStoragePouch, addPouchPlugin } from '../../pouchdb'; -import { wrappedWorkerRxStorage } from '../../worker'; -addPouchPlugin(require('pouchdb-adapter-idb')); -var storage = getRxStoragePouch({ - adapter: 'idb' -}); -wrappedWorkerRxStorage({ - storage: storage -}); -//# sourceMappingURL=pouchdb-idb.worker.js.map \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/pouchdb-idb.worker.js.map b/dist/es/plugins/worker/workers/pouchdb-idb.worker.js.map deleted file mode 100644 index 23b032f9140..00000000000 --- a/dist/es/plugins/worker/workers/pouchdb-idb.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-idb.worker.js","names":["getRxStoragePouch","addPouchPlugin","wrappedWorkerRxStorage","require","storage","adapter"],"sources":["../../../../../src/plugins/worker/workers/pouchdb-idb.worker.ts"],"sourcesContent":["import { getRxStoragePouch, addPouchPlugin } from '../../pouchdb';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\naddPouchPlugin(require('pouchdb-adapter-idb'));\nconst storage = getRxStoragePouch({\n adapter: 'idb'\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,cAAc,QAAQ,eAAe;AACjE,SAASC,sBAAsB,QAAQ,cAAc;AAErDD,cAAc,CAACE,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAC9C,IAAMC,OAAO,GAAGJ,iBAAiB,CAAC;EAC9BK,OAAO,EAAE;AACb,CAAC,CAAC;AACFH,sBAAsB,CAAC;EACnBE,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/pouchdb-memory.worker.js b/dist/es/plugins/worker/workers/pouchdb-memory.worker.js deleted file mode 100644 index 6819c5cf6e5..00000000000 --- a/dist/es/plugins/worker/workers/pouchdb-memory.worker.js +++ /dev/null @@ -1,10 +0,0 @@ -import { getRxStoragePouch, addPouchPlugin } from '../../pouchdb'; -import { wrappedWorkerRxStorage } from '../../worker'; -addPouchPlugin(require('pouchdb-adapter-memory')); -var storage = getRxStoragePouch({ - adapter: 'memory' -}); -wrappedWorkerRxStorage({ - storage: storage -}); -//# sourceMappingURL=pouchdb-memory.worker.js.map \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/pouchdb-memory.worker.js.map b/dist/es/plugins/worker/workers/pouchdb-memory.worker.js.map deleted file mode 100644 index 6cf54ed314d..00000000000 --- a/dist/es/plugins/worker/workers/pouchdb-memory.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-memory.worker.js","names":["getRxStoragePouch","addPouchPlugin","wrappedWorkerRxStorage","require","storage","adapter"],"sources":["../../../../../src/plugins/worker/workers/pouchdb-memory.worker.ts"],"sourcesContent":["import { getRxStoragePouch, addPouchPlugin } from '../../pouchdb';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\naddPouchPlugin(require('pouchdb-adapter-memory'));\nconst storage = getRxStoragePouch({\n adapter: 'memory'\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,cAAc,QAAQ,eAAe;AACjE,SAASC,sBAAsB,QAAQ,cAAc;AAErDD,cAAc,CAACE,OAAO,CAAC,wBAAwB,CAAC,CAAC;AACjD,IAAMC,OAAO,GAAGJ,iBAAiB,CAAC;EAC9BK,OAAO,EAAE;AACb,CAAC,CAAC;AACFH,sBAAsB,CAAC;EACnBE,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/es/plugins/worker/workers/webpack.config.js.map b/dist/es/plugins/worker/workers/webpack.config.js.map deleted file mode 100644 index ceffb41e119..00000000000 --- a/dist/es/plugins/worker/workers/webpack.config.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"webpack.config.js","names":["path","require","TerserPlugin","projectRootPath","resolve","__dirname","babelConfig","module","exports","entry","output","filename","clean","mode","cache","type","cacheDirectory","devtool","rules","test","exclude","use","loader","options","extensions","fallback","fs","optimization","moduleIds","minimize","minimizer","terserOptions","format","comments","extractComments"],"sources":["../../../../../src/plugins/worker/workers/webpack.config.js"],"sourcesContent":["const path = require('path');\nconst TerserPlugin = require('terser-webpack-plugin');\n\nconst projectRootPath = path.resolve(\n __dirname,\n '../../../../'\n);\n\nconst babelConfig = require('../../../../babel.config');\nmodule.exports = {\n entry: {\n 'lokijs-incremental-indexeddb': './src/plugins/worker/workers/lokijs-incremental-indexeddb.worker.ts',\n 'lokijs-indexeddb': './src/plugins/worker/workers/lokijs-indexeddb.worker.ts',\n 'lokijs-memory': './src/plugins/worker/workers/lokijs-memory.worker.ts',\n 'lokijs-fs': './src/plugins/worker/workers/lokijs-fs.worker.ts',\n 'pouchdb-idb': './src/plugins/worker/workers/pouchdb-idb.worker.ts',\n 'pouchdb-memory': './src/plugins/worker/workers/pouchdb-memory.worker.ts',\n 'dexie': './src/plugins/worker/workers/dexie.worker.ts',\n 'dexie-memory': './src/plugins/worker/workers/dexie-memory.worker.ts'\n },\n output: {\n filename: '[name].worker.js',\n clean: true,\n path: path.resolve(\n projectRootPath,\n 'dist/workers'\n ),\n },\n mode: 'production',\n cache: {\n type: 'filesystem',\n cacheDirectory: path.resolve(\n projectRootPath,\n 'test_tmp',\n 'webpack-cache-worker'\n ),\n },\n devtool: 'source-map',\n module: {\n rules: [\n /**\n * We transpile the typscript via babel instead of ts-loader.\n * This ensures we have the exact same babel config\n * as the root RxDB project.\n */\n {\n test: /\\.tsx?$/,\n exclude: /(node_modules)/,\n use: {\n loader: 'babel-loader',\n options: babelConfig\n },\n }\n ],\n },\n resolve: {\n extensions: ['.tsx', '.ts', '.js'],\n /**\n * Fix LokiJS bundle error\n * @link https://rxdb.info/rx-storage-lokijs.html\n */\n fallback: {\n fs: false\n }\n },\n optimization: {\n moduleIds: 'deterministic',\n minimize: true,\n minimizer: [new TerserPlugin({\n terserOptions: {\n format: {\n comments: false,\n },\n },\n /**\n * Disable creating the license files.\n * @link https://github.com/webpack/webpack/issues/12506#issuecomment-789314176\n */\n extractComments: false,\n })],\n }\n};\n"],"mappings":"AAAA,IAAMA,IAAI,GAAGC,OAAO,CAAC,MAAM,CAAC;AAC5B,IAAMC,YAAY,GAAGD,OAAO,CAAC,uBAAuB,CAAC;AAErD,IAAME,eAAe,GAAGH,IAAI,CAACI,OAAO,CAChCC,SAAS,EACT,c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;AACA;MACYC,eAAe,EAAE;IACrB,CAAC,CAAC;EACN;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/es/query-cache.js b/dist/es/query-cache.js index ca55bfbc7ed..96fa7bc06c4 100644 --- a/dist/es/query-cache.js +++ b/dist/es/query-cache.js @@ -3,7 +3,7 @@ * if you use the same mango-query more then once, it will reuse the first RxQuery */ -import { nextTick, now, requestIdlePromise } from './util'; +import { nextTick, now, requestIdlePromise } from './plugins/utils'; export var QueryCache = /*#__PURE__*/function () { function QueryCache() { this._map = new Map(); diff --git a/dist/es/query-cache.js.map b/dist/es/query-cache.js.map index 6ef7824b3b1..3e1cf72bdb0 100644 --- a/dist/es/query-cache.js.map +++ b/dist/es/query-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"query-cache.js","names":["nextTick","now","requestIdlePromise","QueryCache","_map","Map","getByQuery","rxQuery","stringRep","toString","has","set","get","createQueryCache","uncacheRxQuery","queryCache","uncached","countRxQuerySubscribers","refCount$","observers","length","DEFAULT_TRY_TO_KEEP_MAX","DEFAULT_UNEXECUTED_LIFETME","defaultCacheReplacementPolicyMonad","tryToKeepMax","unExecutedLifetime","_collection","size","minUnExecutedLifetime","maybeUncash","queriesInCache","Array","from","values","_lastEnsureEqual","_creationTime","push","mustUncache","sortedByLastUsage","sort","a","b","toRemove","slice","forEach","defaultCacheReplacementPolicy","COLLECTIONS_WITH_RUNNING_CLEANUP","WeakSet","triggerCacheReplacement","rxCollection","add","then","destroyed","cacheReplacementPolicy","_queryCache"],"sources":["../../src/query-cache.ts"],"sourcesContent":["/**\n * the query-cache makes sure that on every query-state, exactly one instance can exist\n * if you use the same mango-query more then once, it will reuse the first RxQuery\n */\nimport type {\n RxQuery,\n RxCacheReplacementPolicy,\n RxCollection\n} from './types';\nimport {\n nextTick,\n now,\n requestIdlePromise\n} from './util';\n\nexport class QueryCache {\n public _map: Map = new Map();\n\n /**\n * check if an equal query is in the cache,\n * if true, return the cached one,\n * if false, save the given one and return it\n */\n getByQuery(rxQuery: RxQuery): RxQuery {\n const stringRep = rxQuery.toString();\n if (!this._map.has(stringRep)) {\n this._map.set(stringRep, rxQuery);\n }\n return this._map.get(stringRep) as RxQuery;\n }\n}\n\nexport function createQueryCache() {\n return new QueryCache();\n}\n\n\nexport function uncacheRxQuery(queryCache: QueryCache, rxQuery: RxQuery) {\n rxQuery.uncached = true;\n const stringRep = rxQuery.toString();\n queryCache._map.delete(stringRep);\n\n}\n\n\nexport function countRxQuerySubscribers(rxQuery: RxQuery): number {\n return rxQuery.refCount$.observers.length;\n}\n\n\nexport const DEFAULT_TRY_TO_KEEP_MAX = 100;\nexport const DEFAULT_UNEXECUTED_LIFETME = 30 * 1000;\n\n/**\n * The default cache replacement policy\n * See docs-src/query-cache.md to learn how it should work.\n * Notice that this runs often and should block the cpu as less as possible\n * This is a monad which makes it easier to unit test\n */\nexport const defaultCacheReplacementPolicyMonad: (\n tryToKeepMax: number,\n unExecutedLifetime: number\n) => RxCacheReplacementPolicy = (\n tryToKeepMax,\n unExecutedLifetime\n) => (\n _collection: RxCollection,\n queryCache: QueryCache\n) => {\n if (queryCache._map.size < tryToKeepMax) {\n return;\n }\n\n const minUnExecutedLifetime = now() - unExecutedLifetime;\n const maybeUncash: RxQuery[] = [];\n\n const queriesInCache = Array.from(queryCache._map.values());\n for (const rxQuery of queriesInCache) {\n // filter out queries with subscribers\n if (countRxQuerySubscribers(rxQuery) > 0) {\n continue;\n }\n // directly uncache queries that never executed and are older then unExecutedLifetime\n if (rxQuery._lastEnsureEqual === 0 && rxQuery._creationTime < minUnExecutedLifetime) {\n uncacheRxQuery(queryCache, rxQuery);\n continue;\n }\n maybeUncash.push(rxQuery);\n }\n\n const mustUncache = maybeUncash.length - tryToKeepMax;\n if (mustUncache <= 0) {\n return;\n }\n\n const sortedByLastUsage = maybeUncash.sort((a, b) => a._lastEnsureEqual - b._lastEnsureEqual);\n const toRemove = sortedByLastUsage.slice(0, mustUncache);\n toRemove.forEach(rxQuery => uncacheRxQuery(queryCache, rxQuery));\n};\n\n\nexport const defaultCacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicyMonad(\n DEFAULT_TRY_TO_KEEP_MAX,\n DEFAULT_UNEXECUTED_LIFETME\n);\n\nexport const COLLECTIONS_WITH_RUNNING_CLEANUP: WeakSet = new WeakSet();\n\n/**\n * Triggers the cache replacement policy after waitTime has passed.\n * We do not run this directly because at exactly the time a query is created,\n * we need all CPU to minimize latency.\n * Also this should not be triggered multiple times when waitTime is still waiting.\n */\nexport function triggerCacheReplacement(\n rxCollection: RxCollection\n) {\n if (COLLECTIONS_WITH_RUNNING_CLEANUP.has(rxCollection)) {\n // already started\n return;\n }\n\n COLLECTIONS_WITH_RUNNING_CLEANUP.add(rxCollection);\n\n /**\n * Do not run directly to not reduce result latency of a new query\n */\n nextTick() // wait at least one tick\n .then(() => requestIdlePromise(200)) // and then wait for the CPU to be idle\n .then(() => {\n if (!rxCollection.destroyed) {\n rxCollection.cacheReplacementPolicy(rxCollection, rxCollection._queryCache);\n }\n COLLECTIONS_WITH_RUNNING_CLEANUP.delete(rxCollection);\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAMA,SACIA,QAAQ,EACRC,GAAG,EACHC,kBAAkB,QACf,QAAQ;AAEf,WAAaC,UAAU;EAAA;IAAA,KACZC,IAAI,GAAyB,IAAIC,GAAG,EAAE;EAAA;EAAA;EAE7C;AACJ;AACA;AACA;AACA;EAJI,OAKAC,UAAU,GAAV,oBAAWC,OAAgB,EAAW;IAClC,IAAMC,SAAS,GAAGD,OAAO,CAACE,QAAQ,EAAE;IACpC,IAAI,CAAC,IAAI,CAACL,IAAI,CAACM,GAAG,CAACF,SAAS,CAAC,EAAE;MAC3B,IAAI,CAACJ,IAAI,CAACO,GAAG,CAACH,SAAS,EAAED,OAAO,CAAC;IACrC;IACA,OAAO,IAAI,CAACH,IAAI,CAACQ,GAAG,CAACJ,SAAS,CAAC;EACnC,CAAC;EAAA;AAAA;AAGL,OAA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8B,WAAW,GAAGR,WAAW,CAACT,MAAM,GAAGI,YAAY;IACrD,IAAIa,WAAW,IAAI,CAAC,EAAE;MAClB;IACJ;IAEA,IAAMC,iBAAiB,GAAGT,WAAW,CAACU,IAAI,CAAC,UAACC,CAAC,EAAEC,CAAC;MAAA,OAAKD,CAAC,CAACN,gBAAgB,GAAGO,CAAC,CAACP,gBAAgB;IAAA,EAAC;IAC7F,IAAMQ,QAAQ,GAAGJ,iBAAiB,CAACK,KAAK,CAAC,CAAC,EAAEN,WAAW,CAAC;IACxDK,QAAQ,CAACE,OAAO,CAAC,UAAArC,OAAO;MAAA,OAAIO,cAAc,CAACC,UAAU,EAAER,OAAO,CAAC;IAAA,EAAC;EACpE,CAAC;AAAA;AAGD,OAAO,IAAMsC,6BAAuD,GAAGtB,kCAAkC,CACrGF,uBAAuB,EACvBC,0BAA0B,CAC7B;AAED,OAAO,IAAMwB,gCAAuD,GAAG,IAAIC,OAAO,EAAE;;AAEpF;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuB,CACnCC,YAA0B,EAC5B;EACE,IAAIH,gCAAgC,CAACpC,GAAG,CAACuC,YAAY,CAAC,EAAE;IACpD;IACA;EACJ;EAEAH,gCAAgC,CAACI,GAAG,CAACD,YAAY,CAAC;;EAElD;AACJ;AACA;EACIjD,QAAQ,EAAE,CAAC;EAAA,CACNmD,IAAI,CAAC;IAAA,OAAMjD,kBAAkB,CAAC,GAAG,CAAC;EAAA,EAAC,CAAC;EAAA,CACpCiD,IAAI,CAAC,YAAM;IACR,IAAI,CAACF,YAAY,CAACG,SAAS,EAAE;MACzBH,YAAY,CAACI,sBAAsB,CAACJ,YAAY,EAAEA,YAAY,CAACK,WAAW,CAAC;IAC/E;IACAR,gCAAgC,UAAO,CAACG,YAAY,CAAC;EACzD,CAAC,CAAC;AACV"} \ No newline at end of file +{"version":3,"file":"query-cache.js","names":["nextTick","now","requestIdlePromise","QueryCache","_map","Map","getByQuery","rxQuery","stringRep","toString","has","set","get","createQueryCache","uncacheRxQuery","queryCache","uncached","countRxQuerySubscribers","refCount$","observers","length","DEFAULT_TRY_TO_KEEP_MAX","DEFAULT_UNEXECUTED_LIFETME","defaultCacheReplacementPolicyMonad","tryToKeepMax","unExecutedLifetime","_collection","size","minUnExecutedLifetime","maybeUncash","queriesInCache","Array","from","values","_lastEnsureEqual","_creationTime","push","mustUncache","sortedByLastUsage","sort","a","b","toRemove","slice","forEach","defaultCacheReplacementPolicy","COLLECTIONS_WITH_RUNNING_CLEANUP","WeakSet","triggerCacheReplacement","rxCollection","add","then","destroyed","cacheReplacementPolicy","_queryCache"],"sources":["../../src/query-cache.ts"],"sourcesContent":["/**\n * the query-cache makes sure that on every query-state, exactly one instance can exist\n * if you use the same mango-query more then once, it will reuse the first RxQuery\n */\nimport type {\n RxQuery,\n RxCacheReplacementPolicy,\n RxCollection\n} from './types';\nimport {\n nextTick,\n now,\n requestIdlePromise\n} from './plugins/utils';\n\nexport class QueryCache {\n public _map: Map = new Map();\n\n /**\n * check if an equal query is in the cache,\n * if true, return the cached one,\n * if false, save the given one and return it\n */\n getByQuery(rxQuery: RxQuery): RxQuery {\n const stringRep = rxQuery.toString();\n if (!this._map.has(stringRep)) {\n this._map.set(stringRep, rxQuery);\n }\n return this._map.get(stringRep) as RxQuery;\n }\n}\n\nexport function createQueryCache() {\n return new QueryCache();\n}\n\n\nexport function uncacheRxQuery(queryCache: QueryCache, rxQuery: RxQuery) {\n rxQuery.uncached = true;\n const stringRep = rxQuery.toString();\n queryCache._map.delete(stringRep);\n\n}\n\n\nexport function countRxQuerySubscribers(rxQuery: RxQuery): number {\n return rxQuery.refCount$.observers.length;\n}\n\n\nexport const DEFAULT_TRY_TO_KEEP_MAX = 100;\nexport const DEFAULT_UNEXECUTED_LIFETME = 30 * 1000;\n\n/**\n * The default cache replacement policy\n * See docs-src/query-cache.md to learn how it should work.\n * Notice that this runs often and should block the cpu as less as possible\n * This is a monad which makes it easier to unit test\n */\nexport const defaultCacheReplacementPolicyMonad: (\n tryToKeepMax: number,\n unExecutedLifetime: number\n) => RxCacheReplacementPolicy = (\n tryToKeepMax,\n unExecutedLifetime\n) => (\n _collection: RxCollection,\n queryCache: QueryCache\n) => {\n if (queryCache._map.size < tryToKeepMax) {\n return;\n }\n\n const minUnExecutedLifetime = now() - unExecutedLifetime;\n const maybeUncash: RxQuery[] = [];\n\n const queriesInCache = Array.from(queryCache._map.values());\n for (const rxQuery of queriesInCache) {\n // filter out queries with subscribers\n if (countRxQuerySubscribers(rxQuery) > 0) {\n continue;\n }\n // directly uncache queries that never executed and are older then unExecutedLifetime\n if (rxQuery._lastEnsureEqual === 0 && rxQuery._creationTime < minUnExecutedLifetime) {\n uncacheRxQuery(queryCache, rxQuery);\n continue;\n }\n maybeUncash.push(rxQuery);\n }\n\n const mustUncache = maybeUncash.length - tryToKeepMax;\n if (mustUncache <= 0) {\n return;\n }\n\n const sortedByLastUsage = maybeUncash.sort((a, b) => a._lastEnsureEqual - b._lastEnsureEqual);\n const toRemove = sortedByLastUsage.slice(0, mustUncache);\n toRemove.forEach(rxQuery => uncacheRxQuery(queryCache, rxQuery));\n};\n\n\nexport const defaultCacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicyMonad(\n DEFAULT_TRY_TO_KEEP_MAX,\n DEFAULT_UNEXECUTED_LIFETME\n);\n\nexport const COLLECTIONS_WITH_RUNNING_CLEANUP: WeakSet = new WeakSet();\n\n/**\n * Triggers the cache replacement policy after waitTime has passed.\n * We do not run this directly because at exactly the time a query is created,\n * we need all CPU to minimize latency.\n * Also this should not be triggered multiple times when waitTime is still waiting.\n */\nexport function triggerCacheReplacement(\n rxCollection: RxCollection\n) {\n if (COLLECTIONS_WITH_RUNNING_CLEANUP.has(rxCollection)) {\n // already started\n return;\n }\n\n COLLECTIONS_WITH_RUNNING_CLEANUP.add(rxCollection);\n\n /**\n * Do not run directly to not reduce result latency of a new query\n */\n nextTick() // wait at least one tick\n .then(() => requestIdlePromise(200)) // and then wait for the CPU to be idle\n .then(() => {\n if (!rxCollection.destroyed) {\n rxCollection.cacheReplacementPolicy(rxCollection, rxCollection._queryCache);\n }\n COLLECTIONS_WITH_RUNNING_CLEANUP.delete(rxCollection);\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;;AAMA,SACIA,QAAQ,EACRC,GAAG,EACHC,kBAAkB,QACf,iBAAiB;AAExB,WAAaC,UAAU;EAAA;IAAA,KACZC,IAAI,GAAyB,IAAIC,GAAG,EAAE;EAAA;EAAA;EAE7C;AACJ;AACA;AACA;AACA;EAJI,OAKAC,UAAU,GAAV,oBAAWC,OAAgB,EAAW;IAClC,IAAMC,SAAS,GAAGD,OAAO,CAACE,QAAQ,EAAE;IACpC,IAAI,CAAC,IAAI,CAACL,IAAI,CAACM,GAAG,CAACF,SAAS,CAAC,EAAE;MAC3B,IAAI,CAACJ,IAAI,CAACO,GAAG,CAACH,SAAS,EAAED,OAAO,CAAC;IACrC;IACA,OAAO,IAAI,CAACH,IAAI,CAACQ,GAAG,CAACJ,SAAS,CAAC;EACnC,CAAC;EAAA;AAAA;AAGL,OAAO,SAASK,gBAAgB,GAAG;EAC/B,OAAO,IAAIV,UAAU,EAAE;AAC3B;AAGA,OAAO,SAASW,cAAc,CAACC,UAAsB,EAAER,OAAgB,EAAE;EACrEA,OAAO,CAACS,QAAQ,GAAG,IAAI;EACvB,IAAMR,SAAS,GAAGD,OAAO,CAACE,QAAQ,EAAE;EACpCM,UAAU,CAACX,IAAI,UAAO,CAACI,SAAS,CAAC;AAErC;AAGA,OAAO,SAASS,uBAAuB,CAACV,OAAgB,EAAU;EAC9D,OAAOA,OAAO,CAACW,SAAS,CAACC,SAAS,CAACC,MAAM;AAC7C;AAGA,OAAO,IAAMC,uBAAuB,GAAG,GAAG;AAC1C,OAAO,IAAMC,0BAA0B,GAAG,EAAE,GAAG,IAAI;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,kCAGgB,GAAG,SAHnBA,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;AAED,OAAO,IAAMwB,gCAAuD,GAAG,IAAIC,OAAO,EAAE;;AAEpF;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuB,CACnCC,YAA0B,EAC5B;EACE,IAAIH,gCAAgC,CAACpC,GAAG,CAACuC,YAAY,CAAC,EAAE;IACpD;IACA;EACJ;EAEAH,gCAAgC,CAACI,GAAG,CAACD,YAAY,CAAC;;EAElD;AACJ;AACA;EACIjD,QAAQ,EAAE,CAAC;EAAA,CACNmD,IAAI,CAAC;IAAA,OAAMjD,kBAAkB,CAAC,GAAG,CAAC;EAAA,EAAC,CAAC;EAAA,CACpCiD,IAAI,CAAC,YAAM;IACR,IAAI,CAACF,YAAY,CAACG,SAAS,EAAE;MACzBH,YAAY,CAACI,sBAAsB,CAACJ,YAAY,EAAEA,YAAY,CAACK,WAAW,CAAC;IAC/E;IACAR,gCAAgC,UAAO,CAACG,YAAY,CAAC;EACzD,CAAC,CAAC;AACV"} \ No newline at end of file diff --git a/dist/es/query-planner.js.map b/dist/es/query-planner.js.map index edd689ee94f..36c7afbd07f 100644 --- a/dist/es/query-planner.js.map +++ b/dist/es/query-planner.js.map @@ -1 +1 @@ -{"version":3,"file":"query-planner.js","names":["getPrimaryFieldOfPrimaryKey","INDEX_MAX","String","fromCharCode","INDEX_MIN","Infinity","getQueryPlan","schema","query","primaryPath","primaryKey","selector","indexes","slice","index","push","optimalSortIndex","sort","map","sortField","Object","keys","optimalSortIndexCompareString","join","hasDescSorting","find","values","currentBestQuality","currentBestQueryPlan","forEach","inclusiveEnd","inclusiveStart","opts","indexField","matcher","operators","matcherOpts","length","startKey","endKey","operator","LOGICAL_OPERATORS","has","operatorValue","partialOpts","getMatcherQueryOpts","assign","queryPlan","startKeys","opt","endKeys","sortFieldsSameAsIndexFields","selectorSatisfiedByIndex","isSelectorSatisfiedByIndex","quality","rateQueryPlan","Set","LOWER_BOUND_LOGICAL_OPERATORS","UPPER_BOUND_LOGICAL_OPERATORS","selectorEntries","entries","hasNonMatchingOperator","fieldName","operation","includes","hasNonLogicOperator","op","_value","prevLowerBoundaryField","hasMoreThenOneLowerBoundaryField","hasLowerLogicOp","key","prevUpperBoundaryField","hasMoreThenOneUpperBoundaryField","hasUpperLogicOp","Error","pointsPerMatchingKey","idxOfFirstMinStartKey","findIndex","keyValue","idxOfFirstMaxEndKey","pointsIfNoReSortMustBeDone"],"sources":["../../src/query-planner.ts"],"sourcesContent":["import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxJsonSchema,\n RxQueryPlan,\n RxQueryPlanerOpts\n} from './types';\n\n\nexport const INDEX_MAX = String.fromCharCode(65535);\nexport const INDEX_MIN = -Infinity;\n\n/**\n * Returns the query plan which contains\n * information about how to run the query\n * and which indexes to use.\n *\n * This is used in some storage like Memory, dexie.js and IndexedDB.\n */\nexport function getQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): RxQueryPlan {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const selector = query.selector;\n\n let indexes: string[][] = schema.indexes ? schema.indexes.slice(0) as any : [];\n if (query.index) {\n indexes = [query.index];\n } else {\n indexes.push([primaryPath]);\n }\n\n const optimalSortIndex = query.sort.map(sortField => Object.keys(sortField)[0]);\n const optimalSortIndexCompareString = optimalSortIndex.join(',');\n /**\n * Most storages do not support descending indexes\n * so having a 'desc' in the sorting, means we always have to re-sort the results.\n */\n const hasDescSorting = !!query.sort.find(sortField => Object.values(sortField)[0] === 'desc');\n\n let currentBestQuality = -1;\n let currentBestQueryPlan: RxQueryPlan | undefined;\n\n indexes.forEach((index) => {\n let inclusiveEnd = true;\n let inclusiveStart = true;\n const opts: RxQueryPlanerOpts[] = index.map(indexField => {\n const matcher = selector[indexField];\n const operators = matcher ? Object.keys(matcher) : [];\n\n let matcherOpts: RxQueryPlanerOpts = {} as any;\n\n if (\n !matcher ||\n !operators.length\n ) {\n matcherOpts = {\n startKey: inclusiveStart ? INDEX_MIN : INDEX_MAX,\n endKey: inclusiveEnd ? INDEX_MAX : INDEX_MIN,\n inclusiveStart: true,\n inclusiveEnd: true\n };\n } else {\n operators.forEach(operator => {\n if (LOGICAL_OPERATORS.has(operator)) {\n const operatorValue = matcher[operator];\n const partialOpts = getMatcherQueryOpts(operator, operatorValue);\n matcherOpts = Object.assign(matcherOpts, partialOpts);\n }\n });\n }\n\n // fill missing attributes\n if (typeof matcherOpts.startKey === 'undefined') {\n matcherOpts.startKey = INDEX_MIN;\n }\n if (typeof matcherOpts.endKey === 'undefined') {\n matcherOpts.endKey = INDEX_MAX;\n }\n if (typeof matcherOpts.inclusiveStart === 'undefined') {\n matcherOpts.inclusiveStart = true;\n }\n if (typeof matcherOpts.inclusiveEnd === 'undefined') {\n matcherOpts.inclusiveEnd = true;\n }\n\n\n if (inclusiveStart && !matcherOpts.inclusiveStart) {\n inclusiveStart = false;\n }\n if (inclusiveEnd && !matcherOpts.inclusiveEnd) {\n inclusiveEnd = false;\n }\n\n return matcherOpts;\n });\n\n const queryPlan: RxQueryPlan = {\n index,\n startKeys: opts.map(opt => opt.startKey),\n endKeys: opts.map(opt => opt.endKey),\n inclusiveEnd,\n inclusiveStart,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === index.join(','),\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex(index, query.selector)\n };\n const quality = rateQueryPlan(\n schema,\n query,\n queryPlan\n );\n if (\n (\n quality > 0 &&\n quality > currentBestQuality\n ) ||\n query.index\n ) {\n currentBestQuality = quality;\n currentBestQueryPlan = queryPlan;\n }\n });\n\n /**\n * No index found, use the default index\n */\n if (!currentBestQueryPlan) {\n currentBestQueryPlan = {\n index: [primaryPath],\n startKeys: [INDEX_MIN],\n endKeys: [INDEX_MAX],\n inclusiveEnd: true,\n inclusiveStart: true,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === primaryPath,\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex([primaryPath], query.selector)\n };\n }\n\n return currentBestQueryPlan;\n}\n\nexport const LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte', '$lt', '$lte']);\nexport const LOWER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte']);\nexport const UPPER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$lt', '$lte']);\n\nexport function isSelectorSatisfiedByIndex(\n index: string[],\n selector: MangoQuerySelector\n): boolean {\n const selectorEntries = Object.entries(selector);\n const hasNonMatchingOperator = selectorEntries\n .find(([fieldName, operation]) => {\n if (!index.includes(fieldName)) {\n return true;\n }\n const hasNonLogicOperator = Object.entries(operation)\n .find(([op, _value]) => !LOGICAL_OPERATORS.has(op));\n return hasNonLogicOperator;\n });\n if (hasNonMatchingOperator) {\n return false;\n }\n\n\n let prevLowerBoundaryField: any;\n const hasMoreThenOneLowerBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasLowerLogicOp = Object.keys(operation).find(key => LOWER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevLowerBoundaryField && hasLowerLogicOp) {\n return true;\n } else if (hasLowerLogicOp !== '$eq') {\n prevLowerBoundaryField = hasLowerLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneLowerBoundaryField) {\n return false;\n }\n\n let prevUpperBoundaryField: any;\n const hasMoreThenOneUpperBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasUpperLogicOp = Object.keys(operation).find(key => UPPER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevUpperBoundaryField && hasUpperLogicOp) {\n return true;\n } else if (hasUpperLogicOp !== '$eq') {\n prevUpperBoundaryField = hasUpperLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneUpperBoundaryField) {\n return false;\n }\n\n return true;\n}\n\nexport function getMatcherQueryOpts(\n operator: string,\n operatorValue: any\n): Partial {\n switch (operator) {\n case '$eq':\n return {\n startKey: operatorValue,\n endKey: operatorValue\n };\n case '$lte':\n return {\n endKey: operatorValue\n };\n case '$gte':\n return {\n startKey: operatorValue\n };\n case '$lt':\n return {\n endKey: operatorValue,\n inclusiveEnd: false\n };\n case '$gt':\n return {\n startKey: operatorValue,\n inclusiveStart: false\n };\n default:\n throw new Error('SNH');\n }\n}\n\n\n/**\n * Returns a number that determines the quality of the query plan.\n * Higher number means better query plan.\n */\nexport function rateQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery,\n queryPlan: RxQueryPlan\n): number {\n let quality: number = 0;\n\n const pointsPerMatchingKey = 10;\n const idxOfFirstMinStartKey = queryPlan.startKeys.findIndex(keyValue => keyValue === INDEX_MIN);\n if (idxOfFirstMinStartKey > 0) {\n quality = quality + (idxOfFirstMinStartKey * pointsPerMatchingKey);\n }\n\n const idxOfFirstMaxEndKey = queryPlan.endKeys.findIndex(keyValue => keyValue === INDEX_MAX);\n if (idxOfFirstMaxEndKey > 0) {\n quality = quality + (idxOfFirstMaxEndKey * pointsPerMatchingKey);\n }\n\n const pointsIfNoReSortMustBeDone = 5;\n if (queryPlan.sortFieldsSameAsIndexFields) {\n quality = quality + pointsIfNoReSortMustBeDone;\n }\n\n return quality;\n}\n"],"mappings":"AAAA,SAASA,2BAA2B,QAAQ,oBAAoB;AAWhE,OAAO,IAAMC,SAAS,GAAGC,MAAM,CAACC,YAAY,CAAC,KAAK,CAAC;AACnD,OAAO,IAAMC,SAAS,GAAG,CAACC,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,YAAY,CACxBC,MAA+C,EAC/CC,KAAkC,EACvB;EACX,IAAMC,WAAW,GAAGT,2BAA2B,CAACO,MAAM,CAACG,UAAU,CAAC;EAClE,IAAMC,QAAQ,GAAGH,KAAK,CAACG,QAAQ;EAE/B,IAAIC,OAAmB,GAAGL,MAAM,CAACK,OAAO,GAAGL,MAAM,CAACK,OAAO,CAACC,KAAK,C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ACA;AACA,OAAO,SAASpB,aAAa,CACzBhD,MAA+C,EAC/CC,KAAkC,EAClCuC,SAAsB,EAChB;EACN,IAAIO,OAAe,GAAG,CAAC;EAEvB,IAAMsB,oBAAoB,GAAG,EAAE;EAC/B,IAAMC,qBAAqB,GAAG9B,SAAS,CAACC,SAAS,CAAC8B,SAAS,CAAC,UAAAC,QAAQ;IAAA,OAAIA,QAAQ,KAAK3E,SAAS;EAAA,EAAC;EAC/F,IAAIyE,qBAAqB,GAAG,CAAC,EAAE;IAC3BvB,OAAO,GAAGA,OAAO,GAAIuB,qBAAqB,GAAGD,oBAAqB;EACtE;EAEA,IAAMI,mBAAmB,GAAGjC,SAAS,CAACG,OAAO,CAAC4B,SAAS,CAAC,UAAAC,QAAQ;IAAA,OAAIA,QAAQ,KAAK9E,SAAS;EAAA,EAAC;EAC3F,IAAI+E,mBAAmB,GAAG,CAAC,EAAE;IACzB1B,OAAO,GAAGA,OAAO,GAAI0B,mBAAmB,GAAGJ,oBAAqB;EACpE;EAEA,IAAMK,0BAA0B,GAAG,CAAC;EACpC,IAAIlC,SAAS,CAACI,2BAA2B,EAAE;IACvCG,OAAO,GAAGA,OAAO,GAAG2B,0BAA0B;EAClD;EAEA,OAAO3B,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"query-planner.js","names":["getPrimaryFieldOfPrimaryKey","INDEX_MAX","String","fromCharCode","INDEX_MIN","Infinity","getQueryPlan","schema","query","primaryPath","primaryKey","selector","indexes","slice","index","push","optimalSortIndex","sort","map","sortField","Object","keys","optimalSortIndexCompareString","join","hasDescSorting","find","values","currentBestQuality","currentBestQueryPlan","forEach","inclusiveEnd","inclusiveStart","opts","indexField","matcher","operators","matcherOpts","length","startKey","endKey","operator","LOGICAL_OPERATORS","has","operatorValue","partialOpts","getMatcherQueryOpts","assign","queryPlan","startKeys","opt","endKeys","sortFieldsSameAsIndexFields","selectorSatisfiedByIndex","isSelectorSatisfiedByIndex","quality","rateQueryPlan","Set","LOWER_BOUND_LOGICAL_OPERATORS","UPPER_BOUND_LOGICAL_OPERATORS","selectorEntries","entries","hasNonMatchingOperator","fieldName","operation","includes","hasNonLogicOperator","op","_value","prevLowerBoundaryField","hasMoreThenOneLowerBoundaryField","hasLowerLogicOp","key","prevUpperBoundaryField","hasMoreThenOneUpperBoundaryField","hasUpperLogicOp","Error","pointsPerMatchingKey","idxOfFirstMinStartKey","findIndex","keyValue","idxOfFirstMaxEndKey","pointsIfNoReSortMustBeDone"],"sources":["../../src/query-planner.ts"],"sourcesContent":["import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxJsonSchema,\n RxQueryPlan,\n RxQueryPlanerOpts\n} from './types';\n\n\nexport const INDEX_MAX = String.fromCharCode(65535);\nexport const INDEX_MIN = -Infinity;\n\n/**\n * Returns the query plan which contains\n * information about how to run the query\n * and which indexes to use.\n *\n * This is used in some storage like Memory, dexie.js and IndexedDB.\n */\nexport function getQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): RxQueryPlan {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const selector = query.selector;\n\n let indexes: string[][] = schema.indexes ? schema.indexes.slice(0) as any : [];\n if (query.index) {\n indexes = [query.index];\n } else {\n indexes.push([primaryPath]);\n }\n\n const optimalSortIndex = query.sort.map(sortField => Object.keys(sortField)[0]);\n const optimalSortIndexCompareString = optimalSortIndex.join(',');\n /**\n * Most storages do not support descending indexes\n * so having a 'desc' in the sorting, means we always have to re-sort the results.\n */\n const hasDescSorting = !!query.sort.find(sortField => Object.values(sortField)[0] === 'desc');\n\n let currentBestQuality = -1;\n let currentBestQueryPlan: RxQueryPlan | undefined;\n\n indexes.forEach((index) => {\n let inclusiveEnd = true;\n let inclusiveStart = true;\n const opts: RxQueryPlanerOpts[] = index.map(indexField => {\n const matcher = (selector as any)[indexField];\n const operators = matcher ? Object.keys(matcher) : [];\n\n let matcherOpts: RxQueryPlanerOpts = {} as any;\n\n if (\n !matcher ||\n !operators.length\n ) {\n matcherOpts = {\n startKey: inclusiveStart ? INDEX_MIN : INDEX_MAX,\n endKey: inclusiveEnd ? INDEX_MAX : INDEX_MIN,\n inclusiveStart: true,\n inclusiveEnd: true\n };\n } else {\n operators.forEach(operator => {\n if (LOGICAL_OPERATORS.has(operator)) {\n const operatorValue = matcher[operator];\n const partialOpts = getMatcherQueryOpts(operator, operatorValue);\n matcherOpts = Object.assign(matcherOpts, partialOpts);\n }\n });\n }\n\n // fill missing attributes\n if (typeof matcherOpts.startKey === 'undefined') {\n matcherOpts.startKey = INDEX_MIN;\n }\n if (typeof matcherOpts.endKey === 'undefined') {\n matcherOpts.endKey = INDEX_MAX;\n }\n if (typeof matcherOpts.inclusiveStart === 'undefined') {\n matcherOpts.inclusiveStart = true;\n }\n if (typeof matcherOpts.inclusiveEnd === 'undefined') {\n matcherOpts.inclusiveEnd = true;\n }\n\n\n if (inclusiveStart && !matcherOpts.inclusiveStart) {\n inclusiveStart = false;\n }\n if (inclusiveEnd && !matcherOpts.inclusiveEnd) {\n inclusiveEnd = false;\n }\n\n return matcherOpts;\n });\n\n const queryPlan: RxQueryPlan = {\n index,\n startKeys: opts.map(opt => opt.startKey),\n endKeys: opts.map(opt => opt.endKey),\n inclusiveEnd,\n inclusiveStart,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === index.join(','),\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex(index, query.selector)\n };\n const quality = rateQueryPlan(\n schema,\n query,\n queryPlan\n );\n if (\n (\n quality > 0 &&\n quality > currentBestQuality\n ) ||\n query.index\n ) {\n currentBestQuality = quality;\n currentBestQueryPlan = queryPlan;\n }\n });\n\n /**\n * No index found, use the default index\n */\n if (!currentBestQueryPlan) {\n currentBestQueryPlan = {\n index: [primaryPath],\n startKeys: [INDEX_MIN],\n endKeys: [INDEX_MAX],\n inclusiveEnd: true,\n inclusiveStart: true,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === primaryPath,\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex([primaryPath], query.selector)\n };\n }\n\n return currentBestQueryPlan;\n}\n\nexport const LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte', '$lt', '$lte']);\nexport const LOWER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte']);\nexport const UPPER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$lt', '$lte']);\n\nexport function isSelectorSatisfiedByIndex(\n index: string[],\n selector: MangoQuerySelector\n): boolean {\n const selectorEntries = Object.entries(selector);\n const hasNonMatchingOperator = selectorEntries\n .find(([fieldName, operation]) => {\n if (!index.includes(fieldName)) {\n return true;\n }\n const hasNonLogicOperator = Object.entries(operation as any)\n .find(([op, _value]) => !LOGICAL_OPERATORS.has(op));\n return hasNonLogicOperator;\n });\n if (hasNonMatchingOperator) {\n return false;\n }\n\n\n let prevLowerBoundaryField: any;\n const hasMoreThenOneLowerBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasLowerLogicOp = Object.keys(operation).find(key => LOWER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevLowerBoundaryField && hasLowerLogicOp) {\n return true;\n } else if (hasLowerLogicOp !== '$eq') {\n prevLowerBoundaryField = hasLowerLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneLowerBoundaryField) {\n return false;\n }\n\n let prevUpperBoundaryField: any;\n const hasMoreThenOneUpperBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasUpperLogicOp = Object.keys(operation).find(key => UPPER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevUpperBoundaryField && hasUpperLogicOp) {\n return true;\n } else if (hasUpperLogicOp !== '$eq') {\n prevUpperBoundaryField = hasUpperLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneUpperBoundaryField) {\n return false;\n }\n\n return true;\n}\n\nexport function getMatcherQueryOpts(\n operator: string,\n operatorValue: any\n): Partial {\n switch (operator) {\n case '$eq':\n return {\n startKey: operatorValue,\n endKey: operatorValue\n };\n case '$lte':\n return {\n endKey: operatorValue\n };\n case '$gte':\n return {\n startKey: operatorValue\n };\n case '$lt':\n return {\n endKey: operatorValue,\n inclusiveEnd: false\n };\n case '$gt':\n return {\n startKey: operatorValue,\n inclusiveStart: false\n };\n default:\n throw new Error('SNH');\n }\n}\n\n\n/**\n * Returns a number that determines the quality of the query plan.\n * Higher number means better query plan.\n */\nexport function rateQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery,\n queryPlan: RxQueryPlan\n): number {\n let quality: number = 0;\n\n const pointsPerMatchingKey = 10;\n const idxOfFirstMinStartKey = queryPlan.startKeys.findIndex(keyValue => keyValue === INDEX_MIN);\n if (idxOfFirstMinStartKey > 0) {\n quality = quality + (idxOfFirstMinStartKey * pointsPerMatchingKey);\n }\n\n const idxOfFirstMaxEndKey = queryPlan.endKeys.findIndex(keyValue => keyValue === INDEX_MAX);\n if (idxOfFirstMaxEndKey > 0) {\n quality = quality + (idxOfFirstMaxEndKey * pointsPerMatchingKey);\n }\n\n const pointsIfNoReSortMustBeDone = 5;\n if (queryPlan.sortFieldsSameAsIndexFields) {\n quality = quality + pointsIfNoReSortMustBeDone;\n }\n\n return quality;\n}\n"],"mappings":"AAAA,SAASA,2BAA2B,QAAQ,oBAAoB;AAWhE,OAAO,IAAMC,SAAS,GAAGC,MAAM,CAACC,YAAY,CAAC,KAAK,CAAC;AACnD,OAAO,IAAMC,SAAS,GAAG,CAACC,QAAQ;;AAElC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,YAAY,CACxBC,MAA+C,EAC/CC,KAAkC,EACvB;EACX,IAAMC,WAAW,GAAGT,2BAA2B,CAACO,MAAM,CAACG,UAAU,CAAC;EAClE,IAAMC,QAAQ,GAAGH,KAAK,CAACG,QAAQ;EAE/B,IAAIC,OAAmB,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AM,IAAI4C,KAAK,CAAC,KAAK,CAAC;EAAC;AAEnC;;AAGA;AACA;AACA;AACA;AACA,OAAO,SAASpB,aAAa,CACzBhD,MAA+C,EAC/CC,KAAkC,EAClCuC,SAAsB,EAChB;EACN,IAAIO,OAAe,GAAG,CAAC;EAEvB,IAAMsB,oBAAoB,GAAG,EAAE;EAC/B,IAAMC,qBAAqB,GAAG9B,SAAS,CAACC,SAAS,CAAC8B,SAAS,CAAC,UAAAC,QAAQ;IAAA,OAAIA,QAAQ,KAAK3E,SAAS;EAAA,EAAC;EAC/F,IAAIyE,qBAAqB,GAAG,CAAC,EAAE;IAC3BvB,OAAO,GAAGA,OAAO,GAAIuB,qBAAqB,GAAGD,oBAAqB;EACtE;EAEA,IAAMI,mBAAmB,GAAGjC,SAAS,CAACG,OAAO,CAAC4B,SAAS,CAAC,UAAAC,QAAQ;IAAA,OAAIA,QAAQ,KAAK9E,SAAS;EAAA,EAAC;EAC3F,IAAI+E,mBAAmB,GAAG,CAAC,EAAE;IACzB1B,OAAO,GAAGA,OAAO,GAAI0B,mBAAmB,GAAGJ,oBAAqB;EACpE;EAEA,IAAMK,0BAA0B,GAAG,CAAC;EACpC,IAAIlC,SAAS,CAACI,2BAA2B,EAAE;IACvCG,OAAO,GAAGA,OAAO,GAAG2B,0BAA0B;EAClD;EAEA,OAAO3B,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/es/replication-protocol/checkpoint.js b/dist/es/replication-protocol/checkpoint.js index 9f5112763f7..f1eb22f1fe5 100644 --- a/dist/es/replication-protocol/checkpoint.js +++ b/dist/es/replication-protocol/checkpoint.js @@ -1,195 +1,94 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { getComposedPrimaryKeyOfDocumentData } from '../rx-schema-helper'; import { stackCheckpoints } from '../rx-storage-helper'; -import { createRevision, ensureNotFalsy, fastUnsecureHash, getDefaultRevision, getDefaultRxDocumentMeta, getFromObjectOrThrow, now } from '../util'; +import { createRevision, ensureNotFalsy, fastUnsecureHash, getDefaultRevision, getDefaultRxDocumentMeta, getFromObjectOrThrow, now } from '../plugins/utils'; import { RX_REPLICATION_META_INSTANCE_SCHEMA } from './meta-instance'; +export function getLastCheckpointDoc(_x, _x2) { + return _getLastCheckpointDoc.apply(this, arguments); +} + /** * Sets the checkpoint, * automatically resolves conflicts that appear. */ -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); +function _getLastCheckpointDoc() { + _getLastCheckpointDoc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(state, direction) { + var checkpointDocId, checkpointResult, checkpointDoc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + checkpointDocId = getComposedPrimaryKeyOfDocumentData(RX_REPLICATION_META_INSTANCE_SCHEMA, { + isCheckpoint: '1', + itemId: direction, + replicationIdentifier: state.checkpointKey + }); + _context.next = 3; + return state.input.metaInstance.findDocumentsById([checkpointDocId], false); + case 3: + checkpointResult = _context.sent; + checkpointDoc = checkpointResult[checkpointDocId]; + state.lastCheckpointDoc[direction] = checkpointDoc; + if (!checkpointDoc) { + _context.next = 10; + break; + } + return _context.abrupt("return", checkpointDoc.data); + case 10: + return _context.abrupt("return", undefined); + case 11: + case "end": + return _context.stop(); } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; + }, _callee); + })); + return _getLastCheckpointDoc.apply(this, arguments); } -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } +export function setCheckpoint(_x3, _x4, _x5) { + return _setCheckpoint.apply(this, arguments); } -export var setCheckpoint = function setCheckpoint(state, direction, checkpoint) { - try { - var _exit = false; - var previousCheckpointDoc = state.lastCheckpointDoc[direction]; - return Promise.resolve(function () { - if (checkpoint && - /** - * If the replication is already canceled, - * we do not write a checkpoint - * because that could mean we write a checkpoint - * for data that has been fetched from the master - * but not been written to the child. - */ - !state.events.canceled.getValue() && ( - /** - * Only write checkpoint if it is different from before - * to have less writes to the storage. - */ +function _setCheckpoint() { + _setCheckpoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(state, direction, checkpoint) { + var previousCheckpointDoc, newDoc, result, error; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + previousCheckpointDoc = state.lastCheckpointDoc[direction]; + if (!(checkpoint && + /** + * If the replication is already canceled, + * we do not write a checkpoint + * because that could mean we write a checkpoint + * for data that has been fetched from the master + * but not been written to the child. + */ + !state.events.canceled.getValue() && ( + /** + * Only write checkpoint if it is different from before + * to have less writes to the storage. + */ - !previousCheckpointDoc || JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint))) { - var newDoc = { - id: '', - isCheckpoint: '1', - itemId: direction, - replicationIdentifier: state.checkpointKey, - _deleted: false, - _attachments: {}, - data: checkpoint, - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision() - }; - newDoc.id = getComposedPrimaryKeyOfDocumentData(RX_REPLICATION_META_INSTANCE_SCHEMA, newDoc); - return _for(function () { - return !_exit; - }, void 0, function () { + !previousCheckpointDoc || JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)))) { + _context2.next = 25; + break; + } + newDoc = { + id: '', + isCheckpoint: '1', + itemId: direction, + replicationIdentifier: state.checkpointKey, + _deleted: false, + _attachments: {}, + data: checkpoint, + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision() + }; + newDoc.id = getComposedPrimaryKeyOfDocumentData(RX_REPLICATION_META_INSTANCE_SCHEMA, newDoc); + case 4: + if (!true) { + _context2.next = 25; + break; + } /** * Instead of just storign the new checkpoint, * we have to stack up the checkpoint with the previous one. @@ -201,51 +100,41 @@ export var setCheckpoint = function setCheckpoint(state, direction, checkpoint) newDoc.data = stackCheckpoints([previousCheckpointDoc.data, newDoc.data]); } newDoc._meta.lwt = now(); - newDoc._rev = createRevision(state.input.hashFunction, newDoc, previousCheckpointDoc); - return Promise.resolve(state.input.metaInstance.bulkWrite([{ + newDoc._rev = createRevision(state.input.identifier, previousCheckpointDoc); + _context2.next = 10; + return state.input.metaInstance.bulkWrite([{ previous: previousCheckpointDoc, document: newDoc - }], 'replication-set-checkpoint')).then(function (result) { - if (result.success[newDoc.id]) { - state.lastCheckpointDoc[direction] = getFromObjectOrThrow(result.success, newDoc.id); - _exit = true; - } else { - var error = getFromObjectOrThrow(result.error, newDoc.id); - if (error.status !== 409) { - throw error; - } else { - previousCheckpointDoc = ensureNotFalsy(error.documentInDb); - newDoc._rev = createRevision(state.input.hashFunction, newDoc, previousCheckpointDoc); - } - } - }); - }); - } - }()); - } catch (e) { - return Promise.reject(e); - } -}; -export var getLastCheckpointDoc = function getLastCheckpointDoc(state, direction) { - try { - var checkpointDocId = getComposedPrimaryKeyOfDocumentData(RX_REPLICATION_META_INSTANCE_SCHEMA, { - isCheckpoint: '1', - itemId: direction, - replicationIdentifier: state.checkpointKey - }); - return Promise.resolve(state.input.metaInstance.findDocumentsById([checkpointDocId], false)).then(function (checkpointResult) { - var checkpointDoc = checkpointResult[checkpointDocId]; - state.lastCheckpointDoc[direction] = checkpointDoc; - if (checkpointDoc) { - return checkpointDoc.data; - } else { - return undefined; + }], 'replication-set-checkpoint'); + case 10: + result = _context2.sent; + if (!result.success[newDoc.id]) { + _context2.next = 16; + break; + } + state.lastCheckpointDoc[direction] = getFromObjectOrThrow(result.success, newDoc.id); + return _context2.abrupt("return"); + case 16: + error = getFromObjectOrThrow(result.error, newDoc.id); + if (!(error.status !== 409)) { + _context2.next = 21; + break; + } + throw error; + case 21: + previousCheckpointDoc = ensureNotFalsy(error.documentInDb); + newDoc._rev = createRevision(state.input.identifier, previousCheckpointDoc); + case 23: + _context2.next = 4; + break; + case 25: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; + }, _callee2); + })); + return _setCheckpoint.apply(this, arguments); +} export function getCheckpointKey(input) { var hash = fastUnsecureHash([input.identifier, input.forkInstance.databaseName, input.forkInstance.collectionName].join('||')); return 'rx-storage-replication-' + hash; diff --git a/dist/es/replication-protocol/checkpoint.js.map b/dist/es/replication-protocol/checkpoint.js.map index 07894da8bca..247f43c5e6f 100644 --- a/dist/es/replication-protocol/checkpoint.js.map +++ b/dist/es/replication-protocol/checkpoint.js.map @@ -1 +1 @@ -{"version":3,"file":"checkpoint.js","names":["getComposedPrimaryKeyOfDocumentData","stackCheckpoints","createRevision","ensureNotFalsy","fastUnsecureHash","getDefaultRevision","getDefaultRxDocumentMeta","getFromObjectOrThrow","now","RX_REPLICATION_META_INSTANCE_SCHEMA","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","setCheckpoint","direction","checkpoint","previousCheckpointDoc","lastCheckpointDoc","events","canceled","getValue","JSON","stringify","data","newDoc","id","isCheckpoint","itemId","replicationIdentifier","checkpointKey","_deleted","_attachments","_meta","_rev","lwt","input","hashFunction","metaInstance","bulkWrite","previous","document","success","error","status","documentInDb","getLastCheckpointDoc","checkpointDocId","findDocumentsById","checkpointResult","checkpointDoc","undefined","getCheckpointKey","hash","identifier","forkInstance","databaseName","collectionName","join"],"sources":["../../../src/replication-protocol/checkpoint.ts"],"sourcesContent":["import { getComposedPrimaryKeyOfDocumentData } from '../rx-schema-helper';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxDocumentData,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta\n} from '../types';\nimport {\n createRevision,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromObjectOrThrow,\n now\n} from '../util';\nimport { RX_REPLICATION_META_INSTANCE_SCHEMA } from './meta-instance';\n\nexport async function getLastCheckpointDoc(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection\n): Promise {\n const checkpointDocId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey\n }\n );\n const checkpointResult = await state.input.metaInstance.findDocumentsById(\n [\n checkpointDocId\n ],\n false\n );\n\n const checkpointDoc = checkpointResult[checkpointDocId];\n state.lastCheckpointDoc[direction] = checkpointDoc;\n if (checkpointDoc) {\n return checkpointDoc.data;\n } else {\n return undefined;\n }\n}\n\n\n/**\n * Sets the checkpoint,\n * automatically resolves conflicts that appear.\n */\nexport async function setCheckpoint(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection,\n checkpoint: CheckpointType\n) {\n let previousCheckpointDoc = state.lastCheckpointDoc[direction];\n if (\n checkpoint &&\n /**\n * If the replication is already canceled,\n * we do not write a checkpoint\n * because that could mean we write a checkpoint\n * for data that has been fetched from the master\n * but not been written to the child.\n */\n !state.events.canceled.getValue() &&\n /**\n * Only write checkpoint if it is different from before\n * to have less writes to the storage.\n */\n (\n !previousCheckpointDoc ||\n JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)\n )\n ) {\n const newDoc: RxDocumentData = {\n id: '',\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey,\n _deleted: false,\n _attachments: {},\n data: checkpoint,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision()\n };\n newDoc.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newDoc\n );\n while (true) {\n /**\n * Instead of just storign the new checkpoint,\n * we have to stack up the checkpoint with the previous one.\n * This is required for plugins like the sharding RxStorage\n * where the changeStream events only contain a Partial of the\n * checkpoint.\n */\n if (previousCheckpointDoc) {\n newDoc.data = stackCheckpoints([\n previousCheckpointDoc.data,\n newDoc.data\n ]);\n }\n newDoc._meta.lwt = now();\n newDoc._rev = createRevision(\n state.input.hashFunction,\n newDoc,\n previousCheckpointDoc\n );\n const result = await state.input.metaInstance.bulkWrite([{\n previous: previousCheckpointDoc,\n document: newDoc\n }], 'replication-set-checkpoint');\n\n if (result.success[newDoc.id]) {\n state.lastCheckpointDoc[direction] = getFromObjectOrThrow(\n result.success,\n newDoc.id\n );\n return;\n } else {\n const error = getFromObjectOrThrow(\n result.error,\n newDoc.id\n );\n if (error.status !== 409) {\n throw error;\n } else {\n previousCheckpointDoc = ensureNotFalsy(error.documentInDb);\n newDoc._rev = createRevision(\n state.input.hashFunction,\n newDoc,\n previousCheckpointDoc\n );\n }\n }\n }\n }\n}\n\nexport function getCheckpointKey(\n input: RxStorageInstanceReplicationInput\n): string {\n const hash = fastUnsecureHash([\n input.identifier,\n input.forkInstance.databaseName,\n input.forkInstance.collectionName\n ].join('||'));\n return 'rx-storage-replication-' + hash;\n}\n"],"mappings":"AAAA,SAASA,mCAAmC,QAAQ,qBAAqB;AACzE,SAASC,gBAAgB,QAAQ,sBAAsB;AAQvD,SACIC,cAAc,EACdC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,wBAAwB,EACxBC,oBAAoB,EACpBC,GAAG,QACA,SAAS;AAChB,SAASC,mCAAmC,QAAQ,iBAAiB;AA+BrE;AACA;AACA;AACA;AAbO,iBAAiBC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3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;MAAC;IAAA;EAEzB,CAAC;IAAA;EAAA;AAAA;AAkGD,OAAO,SAASC,gBAAgB,CAC5BhB,KAAmD,EAC7C;EACN,IAAMiB,IAAI,GAAGxE,gBAAgB,CAAC,CAC1BuD,KAAK,CAACkB,UAAU,EAChBlB,KAAK,CAACmB,YAAY,CAACC,YAAY,EAC/BpB,KAAK,CAACmB,YAAY,CAACE,cAAc,CACpC,CAACC,IAAI,CAAC,IAAI,CAAC,CAAC;EACb,OAAO,yBAAyB,GAAGL,IAAI;AAC3C"} \ No newline at end of file +{"version":3,"file":"checkpoint.js","names":["getComposedPrimaryKeyOfDocumentData","stackCheckpoints","createRevision","ensureNotFalsy","fastUnsecureHash","getDefaultRevision","getDefaultRxDocumentMeta","getFromObjectOrThrow","now","RX_REPLICATION_META_INSTANCE_SCHEMA","getLastCheckpointDoc","state","direction","checkpointDocId","isCheckpoint","itemId","replicationIdentifier","checkpointKey","input","metaInstance","findDocumentsById","checkpointResult","checkpointDoc","lastCheckpointDoc","data","undefined","setCheckpoint","checkpoint","previousCheckpointDoc","events","canceled","getValue","JSON","stringify","newDoc","id","_deleted","_attachments","_meta","_rev","lwt","identifier","bulkWrite","previous","document","result","success","error","status","documentInDb","getCheckpointKey","hash","forkInstance","databaseName","collectionName","join"],"sources":["../../../src/replication-protocol/checkpoint.ts"],"sourcesContent":["import { getComposedPrimaryKeyOfDocumentData } from '../rx-schema-helper';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxDocumentData,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta\n} from '../types';\nimport {\n createRevision,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromObjectOrThrow,\n now\n} from '../plugins/utils';\nimport { RX_REPLICATION_META_INSTANCE_SCHEMA } from './meta-instance';\n\nexport async function getLastCheckpointDoc(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection\n): Promise {\n const checkpointDocId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey\n }\n );\n const checkpointResult = await state.input.metaInstance.findDocumentsById(\n [\n checkpointDocId\n ],\n false\n );\n\n const checkpointDoc = checkpointResult[checkpointDocId];\n state.lastCheckpointDoc[direction] = checkpointDoc;\n if (checkpointDoc) {\n return checkpointDoc.data;\n } else {\n return undefined;\n }\n}\n\n\n/**\n * Sets the checkpoint,\n * automatically resolves conflicts that appear.\n */\nexport async function setCheckpoint(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection,\n checkpoint: CheckpointType\n) {\n let previousCheckpointDoc = state.lastCheckpointDoc[direction];\n if (\n checkpoint &&\n /**\n * If the replication is already canceled,\n * we do not write a checkpoint\n * because that could mean we write a checkpoint\n * for data that has been fetched from the master\n * but not been written to the child.\n */\n !state.events.canceled.getValue() &&\n /**\n * Only write checkpoint if it is different from before\n * to have less writes to the storage.\n */\n (\n !previousCheckpointDoc ||\n JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)\n )\n ) {\n const newDoc: RxDocumentData = {\n id: '',\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey,\n _deleted: false,\n _attachments: {},\n data: checkpoint,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision()\n };\n newDoc.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newDoc\n );\n while (true) {\n /**\n * Instead of just storign the new checkpoint,\n * we have to stack up the checkpoint with the previous one.\n * This is required for plugins like the sharding RxStorage\n * where the changeStream events only contain a Partial of the\n * checkpoint.\n */\n if (previousCheckpointDoc) {\n newDoc.data = stackCheckpoints([\n previousCheckpointDoc.data,\n newDoc.data\n ]);\n }\n newDoc._meta.lwt = now();\n newDoc._rev = createRevision(\n state.input.identifier,\n previousCheckpointDoc\n );\n const result = await state.input.metaInstance.bulkWrite([{\n previous: previousCheckpointDoc,\n document: newDoc\n }], 'replication-set-checkpoint');\n\n if (result.success[newDoc.id]) {\n state.lastCheckpointDoc[direction] = getFromObjectOrThrow(\n result.success,\n newDoc.id\n );\n return;\n } else {\n const error = getFromObjectOrThrow(\n result.error,\n newDoc.id\n );\n if (error.status !== 409) {\n throw error;\n } else {\n previousCheckpointDoc = ensureNotFalsy(error.documentInDb);\n newDoc._rev = createRevision(\n state.input.identifier,\n previousCheckpointDoc\n );\n }\n }\n }\n }\n}\n\nexport function getCheckpointKey(\n input: RxStorageInstanceReplicationInput\n): string {\n const hash = fastUnsecureHash([\n input.identifier,\n input.forkInstance.databaseName,\n input.forkInstance.collectionName\n ].join('||'));\n return 'rx-storage-replication-' + hash;\n}\n"],"mappings":";;AAAA,SAASA,mCAAmC,QAAQ,qBAAqB;AACzE,SAASC,gBAAgB,QAAQ,sBAAsB;AAQvD,SACIC,cAAc,EACdC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,wBAAwB,EACxBC,oBAAoB,EACpBC,GAAG,QACA,kBAAkB;AACzB,SAASC,mCAAmC,QAAQ,iBAAiB;AAErE,gBAAsBC,oBAAoB;EAAA;AAAA;;AA6B1C;AACA;AACA;AACA;AAHA;EAAA,iFA7BO,iBACHC,KAAmD,EACnDC,SAAwC;IAAA;IAAA;MAAA;QAAA;UAElCC,eAAe,GAAGb,mCAAmC,CACvDS,mCAAmC,EACnC;YACIK,YAAY,EAAE,GAAG;YACjBC,MAAM,EAAEH,SAAS;YACjBI,qBAAqB,EAAEL,KAAK,CAACM;UACjC,CAAC,CACJ;UAAA;UAAA,OAC8BN,KAAK,CAACO,KAAK,CAACC,YAAY,CAACC,iBAAiB,CACrE,CACIP,eAAe,CAClB,EACD,KAAK,CACR;QAAA;UALKQ,gBAAgB;UAOhBC,aAAa,GAAGD,gBAAgB,CAACR,eAAe,CAAC;UACvDF,KAAK,CAACY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AAC,IAAI,CAAC,CAAC;EACb,OAAO,yBAAyB,GAAGJ,IAAI;AAC3C"} \ No newline at end of file diff --git a/dist/es/replication-protocol/conflicts.js b/dist/es/replication-protocol/conflicts.js index f348034c4f3..fae0f30470d 100644 --- a/dist/es/replication-protocol/conflicts.js +++ b/dist/es/replication-protocol/conflicts.js @@ -1,49 +1,7 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import deepEqual from 'fast-deep-equal'; -import { getDefaultRevision, createRevision, now, flatClone } from '../util'; -/** - * Resolves a conflict error or determines that the given document states are equal. - * Returns the resolved document that must be written to the fork. - * Then the new document state can be pushed upstream. - * If document is not in conflict, returns undefined. - * If error is non-409, it throws an error. - * Conflicts are only solved in the upstream, never in the downstream. - */ -export var resolveConflictError = function resolveConflictError(state, input, forkState) { - try { - var conflictHandler = state.input.conflictHandler; - return Promise.resolve(conflictHandler(input, 'replication-resolve-conflict')).then(function (conflictHandlerOutput) { - if (conflictHandlerOutput.isEqual) { - /** - * Documents are equal, - * so this is not a conflict -> do nothing. - */ - return undefined; - } else { - /** - * We have a resolved conflict, - * use the resolved document data. - */ - var resolvedDoc = Object.assign({}, conflictHandlerOutput.documentData, { - /** - * Because the resolved conflict is written to the fork, - * we have to keep/update the forks _meta data, not the masters. - */ - _meta: flatClone(forkState._meta), - _rev: getDefaultRevision(), - _attachments: flatClone(forkState._attachments) - }); - resolvedDoc._meta.lwt = now(); - resolvedDoc._rev = createRevision(state.input.hashFunction, resolvedDoc, forkState); - return { - resolvedDoc: resolvedDoc, - output: conflictHandlerOutput - }; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; +import { getDefaultRevision, createRevision, now, flatClone } from '../plugins/utils'; export var defaultConflictHandler = function defaultConflictHandler(i, _context) { /** * If the documents are deep equal, @@ -67,4 +25,60 @@ export var defaultConflictHandler = function defaultConflictHandler(i, _context) documentData: i.realMasterState }); }; + +/** + * Resolves a conflict error or determines that the given document states are equal. + * Returns the resolved document that must be written to the fork. + * Then the new document state can be pushed upstream. + * If document is not in conflict, returns undefined. + * If error is non-409, it throws an error. + * Conflicts are only solved in the upstream, never in the downstream. + */ +export function resolveConflictError(_x, _x2, _x3) { + return _resolveConflictError.apply(this, arguments); +} +function _resolveConflictError() { + _resolveConflictError = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(state, input, forkState) { + var conflictHandler, conflictHandlerOutput, resolvedDoc; + return _regeneratorRuntime.wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + conflictHandler = state.input.conflictHandler; + _context2.next = 3; + return conflictHandler(input, 'replication-resolve-conflict'); + case 3: + conflictHandlerOutput = _context2.sent; + if (!conflictHandlerOutput.isEqual) { + _context2.next = 8; + break; + } + return _context2.abrupt("return", undefined); + case 8: + /** + * We have a resolved conflict, + * use the resolved document data. + */ + resolvedDoc = Object.assign({}, conflictHandlerOutput.documentData, { + /** + * Because the resolved conflict is written to the fork, + * we have to keep/update the forks _meta data, not the masters. + */ + _meta: flatClone(forkState._meta), + _rev: getDefaultRevision(), + _attachments: flatClone(forkState._attachments) + }); + resolvedDoc._meta.lwt = now(); + resolvedDoc._rev = createRevision(state.input.identifier, forkState); + return _context2.abrupt("return", { + resolvedDoc: resolvedDoc, + output: conflictHandlerOutput + }); + case 12: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return _resolveConflictError.apply(this, arguments); +} //# sourceMappingURL=conflicts.js.map \ No newline at end of file diff --git a/dist/es/replication-protocol/conflicts.js.map b/dist/es/replication-protocol/conflicts.js.map index da8bfa690ab..35cc7eb2e74 100644 --- a/dist/es/replication-protocol/conflicts.js.map +++ b/dist/es/replication-protocol/conflicts.js.map @@ -1 +1 @@ -{"version":3,"file":"conflicts.js","names":["deepEqual","getDefaultRevision","createRevision","now","flatClone","resolveConflictError","state","input","forkState","conflictHandler","conflictHandlerOutput","isEqual","undefined","resolvedDoc","Object","assign","documentData","_meta","_rev","_attachments","lwt","hashFunction","output","defaultConflictHandler","i","_context","newDocumentState","realMasterState","Promise","resolve"],"sources":["../../../src/replication-protocol/conflicts.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport type {\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxDocumentData,\n RxStorageInstanceReplicationState\n} from '../types';\nimport {\n getDefaultRevision,\n createRevision,\n now,\n flatClone\n} from '../util';\n\nexport const defaultConflictHandler: RxConflictHandler = function (\n i: RxConflictHandlerInput,\n _context: string\n): Promise> {\n /**\n * If the documents are deep equal,\n * we have no conflict.\n * On your custom conflict handler you might only\n * check some properties, like the updatedAt time,\n * for better performance, because deepEqual is expensive.\n */\n if (deepEqual(\n i.newDocumentState,\n i.realMasterState\n )) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n /**\n * The default conflict handler will always\n * drop the fork state and use the master state instead.\n */\n return Promise.resolve({\n isEqual: false,\n documentData: i.realMasterState\n });\n};\n\n\n/**\n * Resolves a conflict error or determines that the given document states are equal.\n * Returns the resolved document that must be written to the fork.\n * Then the new document state can be pushed upstream.\n * If document is not in conflict, returns undefined.\n * If error is non-409, it throws an error.\n * Conflicts are only solved in the upstream, never in the downstream.\n */\nexport async function resolveConflictError(\n state: RxStorageInstanceReplicationState,\n input: RxConflictHandlerInput,\n forkState: RxDocumentData\n): Promise<{\n resolvedDoc: RxDocumentData;\n output: RxConflictHandlerOutput;\n } | undefined> {\n const conflictHandler: RxConflictHandler = state.input.conflictHandler;\n const conflictHandlerOutput = await conflictHandler(input, 'replication-resolve-conflict');\n\n if (conflictHandlerOutput.isEqual) {\n /**\n * Documents are equal,\n * so this is not a conflict -> do nothing.\n */\n return undefined;\n } else {\n /**\n * We have a resolved conflict,\n * use the resolved document data.\n */\n const resolvedDoc: RxDocumentData = Object.assign(\n {},\n conflictHandlerOutput.documentData,\n {\n /**\n * Because the resolved conflict is written to the fork,\n * we have to keep/update the forks _meta data, not the masters.\n */\n _meta: flatClone(forkState._meta),\n _rev: getDefaultRevision(),\n _attachments: flatClone(forkState._attachments)\n }\n );\n resolvedDoc._meta.lwt = now();\n resolvedDoc._rev = createRevision(\n state.input.hashFunction,\n resolvedDoc,\n forkState\n );\n return {\n resolvedDoc,\n output: conflictHandlerOutput\n };\n }\n}\n"],"mappings":"AAAA,OAAOA,SAAS,MAAM,iBAAiB;AAQvC,SACIC,kBAAkB,EAClBC,cAAc,EACdC,GAAG,EACHC,SAAS,QACN,SAAS;AAiChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAsBC,oBAAoB,YAApBA,oBAAoB,CACtCC,KAAmD,EACnDC,KAAwC,EACxCC,SAAoC;EAAA,IAIrB;IACf,IAAMC,eAA6C,GAAGH,KAAK,CAACC,KAAK,CAACE,eAAe;IAAC,uBAC9CA,eAAe,CAACF,KAAK,EAAE,8BAA8B,CAAC,iBAApFG,qBAAqB;MAAA,IAEvBA,qBAAqB,CAACC,OAAO;QAC7B;AACR;AACA;AACA;QACQ,OAAOC,SAAS;MAAC;QAEjB;AACR;AACA;AACA;QACQ,IAAMC,WAAsC,GAAGC,MAAM,CAACC,MAAM,CACxD,CAAC,CAAC,EACFL,qBAAqB,CAACM,YAAY,EAClC;UACI;AAChB;AACA;AACA;UACgBC,KAAK,EAAEb,SAAS,CAACI,SAAS,CAACS,KAAK,CAAC;UACjCC,IAAI,EAAEjB,kBAAkB,EAAE;UAC1BkB,YAAY,EAAEf,SAAS,CAACI,SAAS,CAACW,YAAY;QAClD,CAAC,CACJ;QACDN,WAAW,CAACI,KAAK,CAACG,GAAG,GAAGjB,GAAG,EAAE;QAC7BU,WAAW,CAACK,IAAI,GAAGhB,cAAc,CAC7BI,KAAK,CAACC,KAAK,CAACc,YAAY,EACxBR,WAAW,EACXL,SAAS,CACZ;QACD,OAAO;UACHK,WAAW,EAAXA,WAAW;UACXS,MAAM,EAAEZ;QACZ,CAAC;MAAC;IAAA;EAEV,CAAC;IAAA;EAAA;AAAA;AArFD,OAAO,IAAMa,sBAA8C,GAAG,SAAjDA,sBAA8C,CACvDC,CAA8B,EAC9BC,QAAgB,EACqB;EACrC;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAIzB,SAAS,CACTwB,CAAC,CAACE,gBAAgB,EAClBF,CAAC,CAACG,eAAe,CACpB,EAAE;IACC,OAAOC,OAAO,CAACC,OAAO,CAAC;MACnBlB,OAAO,EAAE;IACb,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;EACI,OAAOiB,OAAO,CAACC,OAAO,CAAC;IACnBlB,OAAO,EAAE,KAAK;IACdK,YAAY,EAAEQ,CAAC,CAACG;EACpB,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file +{"version":3,"file":"conflicts.js","names":["deepEqual","getDefaultRevision","createRevision","now","flatClone","defaultConflictHandler","i","_context","newDocumentState","realMasterState","Promise","resolve","isEqual","documentData","resolveConflictError","state","input","forkState","conflictHandler","conflictHandlerOutput","undefined","resolvedDoc","Object","assign","_meta","_rev","_attachments","lwt","identifier","output"],"sources":["../../../src/replication-protocol/conflicts.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport type {\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxDocumentData,\n RxStorageInstanceReplicationState\n} from '../types';\nimport {\n getDefaultRevision,\n createRevision,\n now,\n flatClone\n} from '../plugins/utils';\n\nexport const defaultConflictHandler: RxConflictHandler = function (\n i: RxConflictHandlerInput,\n _context: string\n): Promise> {\n /**\n * If the documents are deep equal,\n * we have no conflict.\n * On your custom conflict handler you might only\n * check some properties, like the updatedAt time,\n * for better performance, because deepEqual is expensive.\n */\n if (deepEqual(\n i.newDocumentState,\n i.realMasterState\n )) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n /**\n * The default conflict handler will always\n * drop the fork state and use the master state instead.\n */\n return Promise.resolve({\n isEqual: false,\n documentData: i.realMasterState\n });\n};\n\n\n/**\n * Resolves a conflict error or determines that the given document states are equal.\n * Returns the resolved document that must be written to the fork.\n * Then the new document state can be pushed upstream.\n * If document is not in conflict, returns undefined.\n * If error is non-409, it throws an error.\n * Conflicts are only solved in the upstream, never in the downstream.\n */\nexport async function resolveConflictError(\n state: RxStorageInstanceReplicationState,\n input: RxConflictHandlerInput,\n forkState: RxDocumentData\n): Promise<{\n resolvedDoc: RxDocumentData;\n output: RxConflictHandlerOutput;\n} | undefined> {\n const conflictHandler: RxConflictHandler = state.input.conflictHandler;\n const conflictHandlerOutput = await conflictHandler(input, 'replication-resolve-conflict');\n\n if (conflictHandlerOutput.isEqual) {\n /**\n * Documents are equal,\n * so this is not a conflict -> do nothing.\n */\n return undefined;\n } else {\n /**\n * We have a resolved conflict,\n * use the resolved document data.\n */\n const resolvedDoc: RxDocumentData = Object.assign(\n {},\n conflictHandlerOutput.documentData,\n {\n /**\n * Because the resolved conflict is written to the fork,\n * we have to keep/update the forks _meta data, not the masters.\n */\n _meta: flatClone(forkState._meta),\n _rev: getDefaultRevision(),\n _attachments: flatClone(forkState._attachments)\n }\n );\n resolvedDoc._meta.lwt = now();\n resolvedDoc._rev = createRevision(\n state.input.identifier,\n forkState\n );\n return {\n resolvedDoc,\n output: conflictHandlerOutput\n };\n }\n}\n"],"mappings":";;AAAA,OAAOA,SAAS,MAAM,iBAAiB;AAQvC,SACIC,kBAAkB,EAClBC,cAAc,EACdC,GAAG,EACHC,SAAS,QACN,kBAAkB;AAEzB,OAAO,IAAMC,sBAA8C,GAAG,SAAjDA,sBAA8C,CACvDC,CAA8B,EAC9BC,QAAgB,EACqB;EACrC;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAIP,SAAS,CACTM,CAAC,CAACE,gBAAgB,EAClBF,CAAC,CAACG,eAAe,CACpB,EAAE;IACC,OAAOC,OAAO,CAACC,OAAO,CAAC;MACnBC,OAAO,EAAE;IACb,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;EACI,OAAOF,OAAO,CAACC,OAAO,CAAC;IACnBC,OAAO,EAAE,KAAK;IACdC,YAAY,EAAEP,CAAC,CAACG;EACpB,CAAC,CAAC;AACN,CAAC;;AAGD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAsBK,oBAAoB;EAAA;AAAA;AA6CzC;EAAA,iFA7CM,iBACHC,KAAmD,EACnDC,KAAwC,EACxCC,SAAoC;IAAA;IAAA;MAAA;QAAA;UAK9BC,eAA6C,GAAGH,KAAK,CAACC,KAAK,CAACE,eAAe;UAAA;UAAA,OAC7CA,eAAe,CAACF,KAAK,EAAE,8BAA8B,CAAC;QAAA;UAApFG,qBAAqB;UAAA,KAEvBA,qBAAqB,CAACP,OAAO;YAAA;YAAA;UAAA;UAAA,kCAKtBQ,SAAS;QAAA;UAEhB;AACR;AACA;AACA;UACcC,WAAsC,GAAGC,MAAM,CAACC,MAAM,CACxD,CAAC,CAAC,EACFJ,qBAAqB,CAACN,YAAY,EAClC;YACI;AAChB;AACA;AACA;YACgBW,KAAK,EAAEpB,SAAS,CAACa,SAAS,CAACO,KAAK,CAAC;YACjCC,IAAI,EAAExB,kBAAkB,EAAE;YAC1ByB,YAAY,EAAEtB,SAAS,CAACa,SAAS,CAACS,YAAY;UAClD,CAAC,CACJ;UACDL,WAAW,CAACG,KAAK,CAACG,GAAG,GAAGxB,GAAG,EAAE;UAC7BkB,WAAW,CAACI,IAAI,GAAGvB,cAAc,CAC7Ba,KAAK,CAACC,KAAK,CAACY,UAAU,EACtBX,SAAS,CACZ;UAAC,kCACK;YACHI,WAAW,EAAXA,WAAW;YACXQ,MAAM,EAAEV;UACZ,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAER;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/replication-protocol/downstream.js b/dist/es/replication-protocol/downstream.js index 4ca8a75625a..194577404af 100644 --- a/dist/es/replication-protocol/downstream.js +++ b/dist/es/replication-protocol/downstream.js @@ -1,6 +1,9 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { firstValueFrom, filter } from 'rxjs'; +import { newRxError } from '../rx-error'; import { stackCheckpoints } from '../rx-storage-helper'; -import { createRevision, ensureNotFalsy, flatClone, getDefaultRevision, getDefaultRxDocumentMeta, now, parseRevision, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_VOID } from '../util'; +import { ensureNotFalsy, flatClone, getDefaultRevision, getDefaultRxDocumentMeta, parseRevision, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_VOID } from '../plugins/utils'; import { getLastCheckpointDoc, setCheckpoint } from './checkpoint'; import { writeDocToDocState } from './helper'; import { getAssumedMasterState, getMetaWriteRow } from './meta-instance'; @@ -13,199 +16,7 @@ import { getAssumedMasterState, getMetaWriteRow } from './meta-instance'; * We need this to be able to do initial syncs * and still can have fast event based sync when the client is not offline. */ -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} export function startReplicationDownstream(state) { - var downstreamResyncOnce = function downstreamResyncOnce() { - try { - state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1; - if (state.events.canceled.getValue()) { - return Promise.resolve(); - } - state.checkpointQueue = state.checkpointQueue.then(function () { - return getLastCheckpointDoc(state, 'down'); - }); - return Promise.resolve(state.checkpointQueue).then(function (lastCheckpoint) { - var _interrupt = false; - function _temp2() { - return Promise.resolve(Promise.all(promises)).then(function () {}); - } - var promises = []; - var _temp = _for(function () { - return !_interrupt && !state.events.canceled.getValue(); - }, void 0, function () { - lastTimeMasterChangesRequested = timer++; - return Promise.resolve(replicationHandler.masterChangesSince(lastCheckpoint, state.input.pullBatchSize)).then(function (downResult) { - if (downResult.documents.length === 0) { - _interrupt = true; - return; - } - lastCheckpoint = stackCheckpoints([lastCheckpoint, downResult.checkpoint]); - promises.push(persistFromMaster(downResult.documents, lastCheckpoint)); - - /** - * By definition we stop pull when the pulled documents - * do not fill up the pullBatchSize because we - * can assume that the remote has no more documents. - */ - if (downResult.documents.length < state.input.pullBatchSize) { - _interrupt = true; - } - }); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); - } - }; var replicationHandler = state.input.replicationHandler; // used to detect which tasks etc can in it at which order. @@ -274,6 +85,73 @@ export function startReplicationDownstream(state) { * and then await all writes at the end. */ var lastTimeMasterChangesRequested = -1; + function downstreamResyncOnce() { + return _downstreamResyncOnce.apply(this, arguments); + } + function _downstreamResyncOnce() { + _downstreamResyncOnce = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + var lastCheckpoint, promises, downResult; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1; + if (!state.events.canceled.getValue()) { + _context2.next = 3; + break; + } + return _context2.abrupt("return"); + case 3: + state.checkpointQueue = state.checkpointQueue.then(function () { + return getLastCheckpointDoc(state, 'down'); + }); + _context2.next = 6; + return state.checkpointQueue; + case 6: + lastCheckpoint = _context2.sent; + promises = []; + case 8: + if (state.events.canceled.getValue()) { + _context2.next = 21; + break; + } + lastTimeMasterChangesRequested = timer++; + _context2.next = 12; + return replicationHandler.masterChangesSince(lastCheckpoint, state.input.pullBatchSize); + case 12: + downResult = _context2.sent; + if (!(downResult.documents.length === 0)) { + _context2.next = 15; + break; + } + return _context2.abrupt("break", 21); + case 15: + lastCheckpoint = stackCheckpoints([lastCheckpoint, downResult.checkpoint]); + promises.push(persistFromMaster(downResult.documents, lastCheckpoint)); + + /** + * By definition we stop pull when the pulled documents + * do not fill up the pullBatchSize because we + * can assume that the remote has no more documents. + */ + if (!(downResult.documents.length < state.input.pullBatchSize)) { + _context2.next = 19; + break; + } + return _context2.abrupt("break", 21); + case 19: + _context2.next = 8; + break; + case 21: + _context2.next = 23; + return Promise.all(promises); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _downstreamResyncOnce.apply(this, arguments); + } function downstreamProcessChanges(tasks) { state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1; var docsOfAllTasks = []; @@ -331,47 +209,55 @@ export function startReplicationDownstream(state) { return Promise.all([state.input.forkInstance.findDocumentsById(docIds, true), getAssumedMasterState(state, docIds)]).then(function (_ref) { var currentForkState = _ref[0], assumedMasterState = _ref[1]; - return Promise.all(docIds.map(function (docId) { - try { - var forkStateFullDoc = currentForkState[docId]; - var forkStateDocData = forkStateFullDoc ? writeDocToDocState(forkStateFullDoc) : undefined; - var masterState = downDocsById[docId]; - var assumedMaster = assumedMasterState[docId]; - if (assumedMaster && assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev) { - /** - * The current fork state represents a resolved conflict - * that first must be send to the master in the upstream. - * All conflicts are resolved by the upstream. - */ - return Promise.resolve(PROMISE_RESOLVE_VOID); - } - var isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ? PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ - realMasterState: assumedMaster.docData, - newDocumentState: forkStateDocData - }, 'downstream-check-if-equal-0').then(function (r) { - return r.isEqual; - }); - return Promise.resolve(isAssumedMasterEqualToForkStatePromise).then(function (isAssumedMasterEqualToForkState) { - if (!isAssumedMasterEqualToForkState && assumedMaster && assumedMaster.docData._rev && forkStateFullDoc._meta[state.input.identifier] && parseRevision(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]) { - isAssumedMasterEqualToForkState = true; - } - if (forkStateFullDoc && assumedMaster && isAssumedMasterEqualToForkState === false || forkStateFullDoc && !assumedMaster) { - /** - * We have a non-upstream-replicated - * local write to the fork. - * This means we ignore the downstream of this document - * because anyway the upstream will first resolve the conflict. - */ - return PROMISE_RESOLVE_VOID; - } - var areStatesExactlyEqualPromise = !forkStateDocData ? PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ - realMasterState: masterState, - newDocumentState: forkStateDocData - }, 'downstream-check-if-equal-1').then(function (r) { - return r.isEqual; - }); - return Promise.resolve(areStatesExactlyEqualPromise).then(function (areStatesExactlyEqual) { - if (forkStateDocData && areStatesExactlyEqual) { + return Promise.all(docIds.map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(docId) { + var forkStateFullDoc, forkStateDocData, masterState, assumedMaster, isAssumedMasterEqualToForkStatePromise, isAssumedMasterEqualToForkState, areStatesExactlyEqualPromise, areStatesExactlyEqual, newForkState, nextRevisionHeight, forkWriteRow; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + forkStateFullDoc = currentForkState[docId]; + forkStateDocData = forkStateFullDoc ? writeDocToDocState(forkStateFullDoc) : undefined; + masterState = downDocsById[docId]; + assumedMaster = assumedMasterState[docId]; + if (!(assumedMaster && assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev)) { + _context.next = 6; + break; + } + return _context.abrupt("return", PROMISE_RESOLVE_VOID); + case 6: + isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ? PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ + realMasterState: assumedMaster.docData, + newDocumentState: forkStateDocData + }, 'downstream-check-if-equal-0').then(function (r) { + return r.isEqual; + }); + _context.next = 9; + return isAssumedMasterEqualToForkStatePromise; + case 9: + isAssumedMasterEqualToForkState = _context.sent; + if (!isAssumedMasterEqualToForkState && assumedMaster && assumedMaster.docData._rev && forkStateFullDoc._meta[state.input.identifier] && parseRevision(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]) { + isAssumedMasterEqualToForkState = true; + } + if (!(forkStateFullDoc && assumedMaster && isAssumedMasterEqualToForkState === false || forkStateFullDoc && !assumedMaster)) { + _context.next = 13; + break; + } + return _context.abrupt("return", PROMISE_RESOLVE_VOID); + case 13: + areStatesExactlyEqualPromise = !forkStateDocData ? PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ + realMasterState: masterState, + newDocumentState: forkStateDocData + }, 'downstream-check-if-equal-1').then(function (r) { + return r.isEqual; + }); + _context.next = 16; + return areStatesExactlyEqualPromise; + case 16: + areStatesExactlyEqual = _context.sent; + if (!(forkStateDocData && areStatesExactlyEqual)) { + _context.next = 20; + break; + } /** * Document states are exactly equal. * This can happen when the replication is shut down @@ -383,57 +269,50 @@ export function startReplicationDownstream(state) { if (!assumedMaster || isAssumedMasterEqualToForkState === false) { useMetaWriteRows.push(getMetaWriteRow(state, forkStateDocData, assumedMaster ? assumedMaster.metaDocument : undefined)); } - return PROMISE_RESOLVE_VOID; - } - - /** - * All other master states need to be written to the forkInstance - * and metaInstance. - */ - var newForkState = Object.assign({}, masterState, forkStateFullDoc ? { - _meta: flatClone(forkStateFullDoc._meta), - _attachments: {}, - _rev: getDefaultRevision() - } : { - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision(), - _attachments: {} - }); - - /** - * TODO for unknown reason we need - * to manually set the lwt and the _rev here - * to fix the pouchdb tests. This is not required for - * the other RxStorage implementations which means something is wrong. - */ - newForkState._meta.lwt = now(); - newForkState._rev = masterState._rev ? masterState._rev : createRevision(state.input.hashFunction, newForkState, forkStateFullDoc); - - /** - * If the remote works with revisions, - * we store the height of the next fork-state revision - * inside of the documents meta data. - * By doing so we can filter it out in the upstream - * and detect the document as being equal to master or not. - * This is used for example in the CouchDB replication plugin. - */ - if (masterState._rev) { - var nextRevisionHeight = !forkStateFullDoc ? 1 : parseRevision(forkStateFullDoc._rev).height + 1; - newForkState._meta[state.input.identifier] = nextRevisionHeight; - } - var forkWriteRow = { - previous: forkStateFullDoc, - document: newForkState - }; - writeRowsToFork.push(forkWriteRow); - writeRowsToForkById[docId] = forkWriteRow; - writeRowsToMeta[docId] = getMetaWriteRow(state, masterState, assumedMaster ? assumedMaster.metaDocument : undefined); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })); + return _context.abrupt("return", PROMISE_RESOLVE_VOID); + case 20: + /** + * All other master states need to be written to the forkInstance + * and metaInstance. + */ + newForkState = Object.assign({}, masterState, forkStateFullDoc ? { + _meta: flatClone(forkStateFullDoc._meta), + _attachments: {}, + _rev: getDefaultRevision() + } : { + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision(), + _attachments: {} + }); + /** + * If the remote works with revisions, + * we store the height of the next fork-state revision + * inside of the documents meta data. + * By doing so we can filter it out in the upstream + * and detect the document as being equal to master or not. + * This is used for example in the CouchDB replication plugin. + */ + if (masterState._rev) { + nextRevisionHeight = !forkStateFullDoc ? 1 : parseRevision(forkStateFullDoc._rev).height + 1; + newForkState._meta[state.input.identifier] = nextRevisionHeight; + } + forkWriteRow = { + previous: forkStateFullDoc, + document: newForkState + }; + writeRowsToFork.push(forkWriteRow); + writeRowsToForkById[docId] = forkWriteRow; + writeRowsToMeta[docId] = getMetaWriteRow(state, masterState, assumedMaster ? assumedMaster.metaDocument : undefined); + case 26: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); }).then(function () { if (writeRowsToFork.length > 0) { return state.input.forkInstance.bulkWrite(writeRowsToFork, state.downstreamBulkWriteFlag).then(function (forkWriteResult) { @@ -441,6 +320,19 @@ export function startReplicationDownstream(state) { state.events.processed.down.next(writeRowsToForkById[docId]); useMetaWriteRows.push(writeRowsToMeta[docId]); }); + Object.values(forkWriteResult.error).forEach(function (error) { + /** + * We do not have to care about downstream conflict errors here + * because on conflict, it will be solved locally and result in another write. + */ + if (error.status === 409) { + return; + } + // other non-conflict errors must be handled + state.events.error.next(newRxError('RC_PULL', { + writeError: error + })); + }); }); } }).then(function () { diff --git a/dist/es/replication-protocol/downstream.js.map b/dist/es/replication-protocol/downstream.js.map index c95711d0597..d7765ad7b7e 100644 --- a/dist/es/replication-protocol/downstream.js.map +++ b/dist/es/replication-protocol/downstream.js.map @@ -1 +1 @@ -{"version":3,"file":"downstream.js","names":["firstValueFrom","filter","stackCheckpoints","createRevision","ensureNotFalsy","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","now","parseRevision","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","getLastCheckpointDoc","setCheckpoint","writeDocToDocState","getAssumedMasterState","getMetaWriteRow","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","startReplicationDownstream","downstreamResyncOnce","stats","down","events","canceled","getValue","checkpointQueue","lastCheckpoint","Promise","all","promises","lastTimeMasterChangesRequested","timer","replicationHandler","masterChangesSince","input","pullBatchSize","downResult","documents","length","checkpoint","push","persistFromMaster","openTasks","addNewTask","task","taskWithTime","time","streamQueue","useTasks","active","next","innerTaskWithTime","shift","downstreamProcessChanges","firstSyncDone","sub","masterChangeStream$","subscribe","masterChangeStreamEmit","pipe","unsubscribe","tasks","docsOfAllTasks","forEach","Error","concat","persistenceQueue","nonPersistedFromMaster","docs","docData","docId","primaryPath","downDocsById","useCheckpoint","docIds","Object","keys","writeRowsToFork","writeRowsToForkById","writeRowsToMeta","useMetaWriteRows","forkInstance","findDocumentsById","currentForkState","assumedMasterState","map","forkStateFullDoc","forkStateDocData","undefined","masterState","assumedMaster","metaDocument","isResolvedConflict","_rev","isAssumedMasterEqualToForkStatePromise","conflictHandler","realMasterState","newDocumentState","r","isEqual","isAssumedMasterEqualToForkState","_meta","identifier","height","areStatesExactlyEqualPromise","areStatesExactlyEqual","newForkState","assign","_attachments","lwt","hashFunction","nextRevisionHeight","forkWriteRow","previous","document","bulkWrite","downstreamBulkWriteFlag","forkWriteResult","success","processed","metaInstance","unhandledError","error"],"sources":["../../../src/replication-protocol/downstream.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter\n} from 'rxjs';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxStorageInstanceReplicationState,\n BulkWriteRow,\n BulkWriteRowById,\n RxStorageReplicationMeta,\n RxDocumentData,\n ById,\n WithDeleted,\n DocumentsWithCheckpoint\n} from '../types';\nimport {\n createRevision,\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now,\n parseRevision,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from '../util';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all documents from the master to the fork.\n * The downstream has two operation modes\n * - Sync by iterating over the checkpoints via downstreamResyncOnce()\n * - Sync by listening to the changestream via downstreamProcessChanges()\n * We need this to be able to do initial syncs\n * and still can have fast event based sync when the client is not offline.\n */\nexport function startReplicationDownstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n\n\n type Task = DocumentsWithCheckpoint | 'RESYNC';\n type TaskWithTime = {\n time: number;\n task: Task;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n function addNewTask(task: Task): void {\n state.stats.down.addNewTask = state.stats.down.addNewTask + 1;\n const taskWithTime = {\n time: timer++,\n task\n };\n openTasks.push(taskWithTime);\n state.streamQueue.down = state.streamQueue.down\n .then(() => {\n const useTasks: Task[] = [];\n while (openTasks.length > 0) {\n state.events.active.down.next(true);\n const innerTaskWithTime = ensureNotFalsy(openTasks.shift());\n\n /**\n * If the task came in before the last time we started the pull\n * from the master, then we can drop the task.\n */\n if (innerTaskWithTime.time < lastTimeMasterChangesRequested) {\n continue;\n }\n\n if (innerTaskWithTime.task === 'RESYNC') {\n if (useTasks.length === 0) {\n useTasks.push(innerTaskWithTime.task);\n break;\n } else {\n break;\n }\n }\n\n useTasks.push(innerTaskWithTime.task);\n }\n\n if (useTasks.length === 0) return;\n\n if (useTasks[0] === 'RESYNC') {\n return downstreamResyncOnce();\n } else {\n return downstreamProcessChanges(useTasks);\n }\n }).then(() => {\n state.events.active.down.next(false);\n if (!state.firstSyncDone.down.getValue()) {\n state.firstSyncDone.down.next(true);\n }\n });\n }\n addNewTask('RESYNC');\n\n /**\n * If a write on the master happens, we have to trigger the downstream.\n */\n const sub = replicationHandler\n .masterChangeStream$\n .subscribe((task: Task) => {\n state.stats.down.masterChangeStreamEmit = state.stats.down.masterChangeStreamEmit + 1;\n addNewTask(task);\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n /**\n * For faster performance, we directly start each write\n * and then await all writes at the end.\n */\n let lastTimeMasterChangesRequested: number = -1;\n async function downstreamResyncOnce() {\n state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'down'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n lastTimeMasterChangesRequested = timer++;\n const downResult = await replicationHandler.masterChangesSince(\n lastCheckpoint,\n state.input.pullBatchSize\n );\n\n if (downResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, downResult.checkpoint]);\n\n promises.push(\n persistFromMaster(\n downResult.documents,\n lastCheckpoint\n )\n );\n\n /**\n * By definition we stop pull when the pulled documents\n * do not fill up the pullBatchSize because we\n * can assume that the remote has no more documents.\n */\n if (downResult.documents.length < state.input.pullBatchSize) {\n break;\n }\n\n }\n await Promise.all(promises);\n }\n\n\n function downstreamProcessChanges(tasks: Task[]) {\n state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1;\n let docsOfAllTasks: WithDeleted[] = [];\n let lastCheckpoint: CheckpointType | undefined = null as any;\n\n tasks.forEach(task => {\n if (task === 'RESYNC') {\n throw new Error('SNH');\n }\n docsOfAllTasks = docsOfAllTasks.concat(task.documents);\n lastCheckpoint = stackCheckpoints([lastCheckpoint, task.checkpoint]);\n });\n return persistFromMaster(\n docsOfAllTasks,\n ensureNotFalsy(lastCheckpoint)\n );\n }\n\n\n /**\n * It can happen that the calls to masterChangesSince() or the changeStream()\n * are way faster then how fast the documents can be persisted.\n * Therefore we merge all incoming downResults into the nonPersistedFromMaster object\n * and process them together if possible.\n * This often bundles up single writes and improves performance\n * by processing the documents in bulks.\n */\n let persistenceQueue = PROMISE_RESOLVE_VOID;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n function persistFromMaster(\n docs: WithDeleted[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.down.persistFromMaster = state.stats.down.persistFromMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n /**\n * Run in the queue\n * with all open documents from nonPersistedFromMaster.\n */\n persistenceQueue = persistenceQueue.then(() => {\n const downDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(downDocsById);\n\n if (\n state.events.canceled.getValue() ||\n docIds.length === 0\n ) {\n return PROMISE_RESOLVE_VOID;\n }\n\n const writeRowsToFork: BulkWriteRow[] = [];\n const writeRowsToForkById: ById> = {};\n const writeRowsToMeta: BulkWriteRowById = {};\n const useMetaWriteRows: BulkWriteRow[] = [];\n\n return Promise.all([\n state.input.forkInstance.findDocumentsById(docIds, true),\n getAssumedMasterState(\n state,\n docIds\n )\n ]).then(([\n currentForkState,\n assumedMasterState\n ]) => {\n return Promise.all(\n docIds.map(async (docId) => {\n const forkStateFullDoc: RxDocumentData | undefined = currentForkState[docId];\n const forkStateDocData: WithDeleted | undefined = forkStateFullDoc ? writeDocToDocState(forkStateFullDoc) : undefined;\n const masterState = downDocsById[docId];\n const assumedMaster = assumedMasterState[docId];\n\n if (\n assumedMaster &&\n assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev\n ) {\n /**\n * The current fork state represents a resolved conflict\n * that first must be send to the master in the upstream.\n * All conflicts are resolved by the upstream.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n const isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: assumedMaster.docData,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-0').then(r => r.isEqual);\n let isAssumedMasterEqualToForkState = await isAssumedMasterEqualToForkStatePromise;\n\n if (\n !isAssumedMasterEqualToForkState &&\n (\n assumedMaster &&\n (assumedMaster.docData as any)._rev &&\n forkStateFullDoc._meta[state.input.identifier] &&\n parseRevision(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]\n )\n ) {\n isAssumedMasterEqualToForkState = true;\n }\n if (\n (\n forkStateFullDoc &&\n assumedMaster &&\n isAssumedMasterEqualToForkState === false\n ) ||\n (\n forkStateFullDoc && !assumedMaster\n )\n ) {\n /**\n * We have a non-upstream-replicated\n * local write to the fork.\n * This means we ignore the downstream of this document\n * because anyway the upstream will first resolve the conflict.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n\n const areStatesExactlyEqualPromise = !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: masterState,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-1').then(r => r.isEqual);\n const areStatesExactlyEqual = await areStatesExactlyEqualPromise;\n\n if (\n forkStateDocData &&\n areStatesExactlyEqual\n ) {\n /**\n * Document states are exactly equal.\n * This can happen when the replication is shut down\n * unexpected like when the user goes offline.\n *\n * Only when the assumedMaster is different from the forkState,\n * we have to patch the document in the meta instance.\n */\n if (\n !assumedMaster ||\n isAssumedMasterEqualToForkState === false\n ) {\n useMetaWriteRows.push(\n getMetaWriteRow(\n state,\n forkStateDocData,\n assumedMaster ? assumedMaster.metaDocument : undefined\n )\n );\n }\n return PROMISE_RESOLVE_VOID;\n }\n\n /**\n * All other master states need to be written to the forkInstance\n * and metaInstance.\n */\n const newForkState = Object.assign(\n {},\n masterState,\n forkStateFullDoc ? {\n _meta: flatClone(forkStateFullDoc._meta),\n _attachments: {},\n _rev: getDefaultRevision()\n } : {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n });\n\n\n /**\n * TODO for unknown reason we need\n * to manually set the lwt and the _rev here\n * to fix the pouchdb tests. This is not required for\n * the other RxStorage implementations which means something is wrong.\n */\n newForkState._meta.lwt = now();\n newForkState._rev = (masterState as any)._rev ? (masterState as any)._rev : createRevision(\n state.input.hashFunction,\n newForkState,\n forkStateFullDoc\n );\n\n /**\n * If the remote works with revisions,\n * we store the height of the next fork-state revision\n * inside of the documents meta data.\n * By doing so we can filter it out in the upstream\n * and detect the document as being equal to master or not.\n * This is used for example in the CouchDB replication plugin.\n */\n if ((masterState as any)._rev) {\n const nextRevisionHeight = !forkStateFullDoc ? 1 : parseRevision(forkStateFullDoc._rev).height + 1;\n newForkState._meta[state.input.identifier] = nextRevisionHeight;\n }\n\n const forkWriteRow = {\n previous: forkStateFullDoc,\n document: newForkState\n };\n\n writeRowsToFork.push(forkWriteRow);\n writeRowsToForkById[docId] = forkWriteRow;\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n masterState,\n assumedMaster ? assumedMaster.metaDocument : undefined\n );\n })\n );\n }).then(() => {\n if (writeRowsToFork.length > 0) {\n return state.input.forkInstance.bulkWrite(\n writeRowsToFork,\n state.downstreamBulkWriteFlag\n ).then((forkWriteResult) => {\n Object.keys(forkWriteResult.success).forEach((docId) => {\n state.events.processed.down.next(writeRowsToForkById[docId]);\n useMetaWriteRows.push(writeRowsToMeta[docId]);\n });\n });\n }\n }).then(() => {\n if (useMetaWriteRows.length > 0) {\n return state.input.metaInstance.bulkWrite(\n useMetaWriteRows,\n 'replication-down-write-meta'\n );\n }\n }).then(() => {\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'down',\n useCheckpoint\n ));\n });\n }).catch(unhandledError => state.events.error.next(unhandledError));\n return persistenceQueue;\n }\n}\n"],"mappings":"AAAA,SACIA,cAAc,EACdC,MAAM,QACH,MAAM;AACb,SAASC,gBAAgB,QAAQ,sBAAsB;AAWvD,SACIC,cAAc,EACdC,cAAc,EACdC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,GAAG,EACHC,aAAa,EACbC,qBAAqB,EACrBC,oBAAoB,QACjB,SAAS;AAChB,SACIC,oBAAoB,EACpBC,aAAa,QACV,cAAc;AACrB,SAASC,kBAAkB,QAAQ,UAAU;AAC7C,SACIC,qBAAqB,EACrBC,eAAe,QACZ,iBAAiB;;AAExB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAJO,iBAAiBC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE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AACJ"} \ No newline at end of file +{"version":3,"file":"downstream.js","names":["firstValueFrom","filter","newRxError","stackCheckpoints","ensureNotFalsy","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","parseRevision","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","getLastCheckpointDoc","setCheckpoint","writeDocToDocState","getAssumedMasterState","getMetaWriteRow","startReplicationDownstream","state","replicationHandler","input","timer","openTasks","addNewTask","task","stats","down","taskWithTime","time","push","streamQueue","then","useTasks","length","events","active","next","innerTaskWithTime","shift","lastTimeMasterChangesRequested","downstreamResyncOnce","downstreamProcessChanges","firstSyncDone","getValue","sub","masterChangeStream$","subscribe","masterChangeStreamEmit","canceled","pipe","unsubscribe","checkpointQueue","lastCheckpoint","promises","masterChangesSince","pullBatchSize","downResult","documents","checkpoint","persistFromMaster","Promise","all","tasks","docsOfAllTasks","forEach","Error","concat","persistenceQueue","nonPersistedFromMaster","docs","docData","docId","primaryPath","downDocsById","useCheckpoint","docIds","Object","keys","writeRowsToFork","writeRowsToForkById","writeRowsToMeta","useMetaWriteRows","forkInstance","findDocumentsById","currentForkState","assumedMasterState","map","forkStateFullDoc","forkStateDocData","undefined","masterState","assumedMaster","metaDocument","isResolvedConflict","_rev","isAssumedMasterEqualToForkStatePromise","conflictHandler","realMasterState","newDocumentState","r","isEqual","isAssumedMasterEqualToForkState","_meta","identifier","height","areStatesExactlyEqualPromise","areStatesExactlyEqual","newForkState","assign","_attachments","nextRevisionHeight","forkWriteRow","previous","document","bulkWrite","downstreamBulkWriteFlag","forkWriteResult","success","processed","values","error","status","writeError","metaInstance","unhandledError"],"sources":["../../../src/replication-protocol/downstream.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter\n} from 'rxjs';\nimport { newRxError } from '../rx-error';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxStorageInstanceReplicationState,\n BulkWriteRow,\n BulkWriteRowById,\n RxStorageReplicationMeta,\n RxDocumentData,\n ById,\n WithDeleted,\n DocumentsWithCheckpoint\n} from '../types';\nimport {\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n parseRevision,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all documents from the master to the fork.\n * The downstream has two operation modes\n * - Sync by iterating over the checkpoints via downstreamResyncOnce()\n * - Sync by listening to the changestream via downstreamProcessChanges()\n * We need this to be able to do initial syncs\n * and still can have fast event based sync when the client is not offline.\n */\nexport function startReplicationDownstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n\n\n type Task = DocumentsWithCheckpoint | 'RESYNC';\n type TaskWithTime = {\n time: number;\n task: Task;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n function addNewTask(task: Task): void {\n state.stats.down.addNewTask = state.stats.down.addNewTask + 1;\n const taskWithTime = {\n time: timer++,\n task\n };\n openTasks.push(taskWithTime);\n state.streamQueue.down = state.streamQueue.down\n .then(() => {\n const useTasks: Task[] = [];\n while (openTasks.length > 0) {\n state.events.active.down.next(true);\n const innerTaskWithTime = ensureNotFalsy(openTasks.shift());\n\n /**\n * If the task came in before the last time we started the pull\n * from the master, then we can drop the task.\n */\n if (innerTaskWithTime.time < lastTimeMasterChangesRequested) {\n continue;\n }\n\n if (innerTaskWithTime.task === 'RESYNC') {\n if (useTasks.length === 0) {\n useTasks.push(innerTaskWithTime.task);\n break;\n } else {\n break;\n }\n }\n\n useTasks.push(innerTaskWithTime.task);\n }\n\n if (useTasks.length === 0) return;\n\n if (useTasks[0] === 'RESYNC') {\n return downstreamResyncOnce();\n } else {\n return downstreamProcessChanges(useTasks);\n }\n }).then(() => {\n state.events.active.down.next(false);\n if (!state.firstSyncDone.down.getValue()) {\n state.firstSyncDone.down.next(true);\n }\n });\n }\n addNewTask('RESYNC');\n\n /**\n * If a write on the master happens, we have to trigger the downstream.\n */\n const sub = replicationHandler\n .masterChangeStream$\n .subscribe((task: Task) => {\n state.stats.down.masterChangeStreamEmit = state.stats.down.masterChangeStreamEmit + 1;\n addNewTask(task);\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n /**\n * For faster performance, we directly start each write\n * and then await all writes at the end.\n */\n let lastTimeMasterChangesRequested: number = -1;\n async function downstreamResyncOnce() {\n state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'down'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n lastTimeMasterChangesRequested = timer++;\n const downResult = await replicationHandler.masterChangesSince(\n lastCheckpoint,\n state.input.pullBatchSize\n );\n\n if (downResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, downResult.checkpoint]);\n\n promises.push(\n persistFromMaster(\n downResult.documents,\n lastCheckpoint\n )\n );\n\n /**\n * By definition we stop pull when the pulled documents\n * do not fill up the pullBatchSize because we\n * can assume that the remote has no more documents.\n */\n if (downResult.documents.length < state.input.pullBatchSize) {\n break;\n }\n\n }\n await Promise.all(promises);\n }\n\n\n function downstreamProcessChanges(tasks: Task[]) {\n state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1;\n let docsOfAllTasks: WithDeleted[] = [];\n let lastCheckpoint: CheckpointType | undefined = null as any;\n\n tasks.forEach(task => {\n if (task === 'RESYNC') {\n throw new Error('SNH');\n }\n docsOfAllTasks = docsOfAllTasks.concat(task.documents);\n lastCheckpoint = stackCheckpoints([lastCheckpoint, task.checkpoint]);\n });\n return persistFromMaster(\n docsOfAllTasks,\n ensureNotFalsy(lastCheckpoint)\n );\n }\n\n\n /**\n * It can happen that the calls to masterChangesSince() or the changeStream()\n * are way faster then how fast the documents can be persisted.\n * Therefore we merge all incoming downResults into the nonPersistedFromMaster object\n * and process them together if possible.\n * This often bundles up single writes and improves performance\n * by processing the documents in bulks.\n */\n let persistenceQueue = PROMISE_RESOLVE_VOID;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n function persistFromMaster(\n docs: WithDeleted[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.down.persistFromMaster = state.stats.down.persistFromMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n /**\n * Run in the queue\n * with all open documents from nonPersistedFromMaster.\n */\n persistenceQueue = persistenceQueue.then(() => {\n const downDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(downDocsById);\n\n if (\n state.events.canceled.getValue() ||\n docIds.length === 0\n ) {\n return PROMISE_RESOLVE_VOID;\n }\n\n const writeRowsToFork: BulkWriteRow[] = [];\n const writeRowsToForkById: ById> = {};\n const writeRowsToMeta: BulkWriteRowById = {};\n const useMetaWriteRows: BulkWriteRow[] = [];\n\n return Promise.all([\n state.input.forkInstance.findDocumentsById(docIds, true),\n getAssumedMasterState(\n state,\n docIds\n )\n ]).then(([\n currentForkState,\n assumedMasterState\n ]) => {\n return Promise.all(\n docIds.map(async (docId) => {\n const forkStateFullDoc: RxDocumentData | undefined = currentForkState[docId];\n const forkStateDocData: WithDeleted | undefined = forkStateFullDoc ? writeDocToDocState(forkStateFullDoc) : undefined;\n const masterState = downDocsById[docId];\n const assumedMaster = assumedMasterState[docId];\n\n if (\n assumedMaster &&\n assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev\n ) {\n /**\n * The current fork state represents a resolved conflict\n * that first must be send to the master in the upstream.\n * All conflicts are resolved by the upstream.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n const isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: assumedMaster.docData,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-0').then(r => r.isEqual);\n let isAssumedMasterEqualToForkState = await isAssumedMasterEqualToForkStatePromise;\n\n if (\n !isAssumedMasterEqualToForkState &&\n (\n assumedMaster &&\n (assumedMaster.docData as any)._rev &&\n forkStateFullDoc._meta[state.input.identifier] &&\n parseRevision(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]\n )\n ) {\n isAssumedMasterEqualToForkState = true;\n }\n if (\n (\n forkStateFullDoc &&\n assumedMaster &&\n isAssumedMasterEqualToForkState === false\n ) ||\n (\n forkStateFullDoc && !assumedMaster\n )\n ) {\n /**\n * We have a non-upstream-replicated\n * local write to the fork.\n * This means we ignore the downstream of this document\n * because anyway the upstream will first resolve the conflict.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n\n const areStatesExactlyEqualPromise = !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: masterState,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-1').then(r => r.isEqual);\n const areStatesExactlyEqual = await areStatesExactlyEqualPromise;\n\n if (\n forkStateDocData &&\n areStatesExactlyEqual\n ) {\n /**\n * Document states are exactly equal.\n * This can happen when the replication is shut down\n * unexpected like when the user goes offline.\n *\n * Only when the assumedMaster is different from the forkState,\n * we have to patch the document in the meta instance.\n */\n if (\n !assumedMaster ||\n isAssumedMasterEqualToForkState === false\n ) {\n useMetaWriteRows.push(\n getMetaWriteRow(\n state,\n forkStateDocData,\n assumedMaster ? assumedMaster.metaDocument : undefined\n )\n );\n }\n return PROMISE_RESOLVE_VOID;\n }\n\n /**\n * All other master states need to be written to the forkInstance\n * and metaInstance.\n */\n const newForkState = Object.assign(\n {},\n masterState,\n forkStateFullDoc ? {\n _meta: flatClone(forkStateFullDoc._meta),\n _attachments: {},\n _rev: getDefaultRevision()\n } : {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n });\n\n /**\n * If the remote works with revisions,\n * we store the height of the next fork-state revision\n * inside of the documents meta data.\n * By doing so we can filter it out in the upstream\n * and detect the document as being equal to master or not.\n * This is used for example in the CouchDB replication plugin.\n */\n if ((masterState as any)._rev) {\n const nextRevisionHeight = !forkStateFullDoc ? 1 : parseRevision(forkStateFullDoc._rev).height + 1;\n newForkState._meta[state.input.identifier] = nextRevisionHeight;\n }\n\n const forkWriteRow = {\n previous: forkStateFullDoc,\n document: newForkState\n };\n\n writeRowsToFork.push(forkWriteRow);\n writeRowsToForkById[docId] = forkWriteRow;\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n masterState,\n assumedMaster ? assumedMaster.metaDocument : undefined\n );\n })\n );\n }).then(() => {\n if (writeRowsToFork.length > 0) {\n return state.input.forkInstance.bulkWrite(\n writeRowsToFork,\n state.downstreamBulkWriteFlag\n ).then((forkWriteResult) => {\n Object.keys(forkWriteResult.success).forEach((docId) => {\n state.events.processed.down.next(writeRowsToForkById[docId]);\n useMetaWriteRows.push(writeRowsToMeta[docId]);\n });\n Object.values(forkWriteResult.error).forEach(error => {\n /**\n * We do not have to care about downstream conflict errors here\n * because on conflict, it will be solved locally and result in another write.\n */\n if (error.status === 409) {\n return;\n }\n // other non-conflict errors must be handled\n state.events.error.next(newRxError('RC_PULL', {\n writeError: error\n }));\n });\n });\n }\n }).then(() => {\n if (useMetaWriteRows.length > 0) {\n return state.input.metaInstance.bulkWrite(\n useMetaWriteRows,\n 'replication-down-write-meta'\n );\n }\n }).then(() => {\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'down',\n useCheckpoint\n ));\n });\n }).catch(unhandledError => state.events.error.next(unhandledError));\n return persistenceQueue;\n }\n}\n"],"mappings":";;AAAA,SACIA,cAAc,EACdC,MAAM,QACH,MAAM;AACb,SAASC,UAAU,QAAQ,aAAa;AACxC,SAASC,gBAAgB,QAAQ,sBAAsB;AAWvD,SACIC,cAAc,EACdC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,aAAa,EACbC,qBAAqB,EACrBC,oBAAoB,QACjB,kBAAkB;AACzB,SACIC,oBAAoB,EACpBC,aAAa,QACV,cAAc;AACrB,SAASC,kBAAkB,QAAQ,UAAU;AAC7C,SACIC,qBAAqB,EACrBC,eAAe,QACZ,iBAAiB;;AAExB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,0BAA0B,CACtCC,KAAmD,EACrD;EACE,IAAMC,kBAAkB,GAAGD,KAAK,CAACE,KAAK,CAACD,kBAAkB;;EAEzD;EACA,IAAIE,KAAK,GAAG,CAAC;EAQb,IAAMC,SAAyB,GAAG,EAAE;EAGpC,SAASC,UAAU,CAACC,IAAU,EAAQ;IAClCN,KAAK,CAACO,KAAK,CAACC,IAAI,CAACH,UAAU,GAAGL,KAAK,CAACO,KAAK,CAACC,IAAI,CAACH,UAAU,GAAG,CAAC;IAC7D,IAAMI,YAAY,GAAG;MACjBC,IAAI,EAAEP,KAAK,EAAE;MACbG,IAAI,EAAJA;IACJ,CAAC;IACDF,SAAS,CAACO,IAAI,CAACF,YAAY,CAAC;IAC5BT,KAAK,CAACY,WAAW,CAACJ,IAAI,GAAGR,KAAK,CAACY,WAAW,CAACJ,IAAI,CAC1CK,IAAI,CAAC,YAAM;MACR,IAAMC,QAAgB,GAAG,EAAE;MAC3B,OAAOV,SAAS,CAACW,MAAM,GAAG,CAA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AACxD,OAAO,CAAC,UAAAwD,KAAK,EAAI;cAClD;AAC5B;AACA;AACA;cAC4B,IAAIA,KAAK,CAACC,MAAM,KAAK,GAAG,EAAE;gBACtB;cACJ;cACA;cACAvG,KAAK,CAACgB,MAAM,CAACsF,KAAK,CAACpF,IAAI,CAACjC,UAAU,CAAC,SAAS,EAAE;gBAC1CuH,UAAU,EAAEF;cAChB,CAAC,CAAC,CAAC;YACP,CAAC,CAAC;UACN,CAAC,CAAC;QACN;MACJ,CAAC,CAAC,CAACzF,IAAI,CAAC,YAAM;QACV,IAAIkD,gBAAgB,CAAChD,MAAM,GAAG,CAAC,EAAE;UAC7B,OAAOf,KAAK,CAACE,KAAK,CAACuG,YAAY,CAACT,SAAS,CACrCjC,gBAAgB,EAChB,6BAA6B,CAChC;QACL;MACJ,CAAC,CAAC,CAAClD,IAAI,CAAC,YAAM;QACV;AAChB;AACA;AACA;AACA;QACgBb,KAAK,CAACiC,eAAe,GAAGjC,KAAK,CAACiC,eAAe,CAACpB,IAAI,CAAC;UAAA,OAAMlB,aAAa,CAClEK,KAAK,EACL,MAAM,EACNwD,aAAa,CAChB;QAAA,EAAC;MACN,CAAC,CAAC;IACN,CAAC,CAAC,SAAM,CAAC,UAAAkD,cAAc;MAAA,OAAI1G,KAAK,CAACgB,MAAM,CAACsF,KAAK,CAACpF,IAAI,CAACwF,cAAc,CAAC;IAAA,EAAC;IACnE,OAAOzD,gBAAgB;EAC3B;AACJ"} \ No newline at end of file diff --git a/dist/es/replication-protocol/helper.js b/dist/es/replication-protocol/helper.js index 87c32cf1bb6..9dbb8c84b7f 100644 --- a/dist/es/replication-protocol/helper.js +++ b/dist/es/replication-protocol/helper.js @@ -1,5 +1,5 @@ -import { createRevision, flatClone, getDefaultRevision, now } from '../util'; -export function docStateToWriteDoc(hashFunction, docState, previous) { +import { createRevision, flatClone, getDefaultRevision, now } from '../plugins/utils'; +export function docStateToWriteDoc(databaseInstanceToken, docState, previous) { var docData = Object.assign({}, docState, { _attachments: {}, _meta: { @@ -7,7 +7,7 @@ export function docStateToWriteDoc(hashFunction, docState, previous) { }, _rev: getDefaultRevision() }); - docData._rev = createRevision(hashFunction, docData, previous); + docData._rev = createRevision(databaseInstanceToken, previous); return docData; } export function writeDocToDocState(writeDoc) { diff --git a/dist/es/replication-protocol/helper.js.map b/dist/es/replication-protocol/helper.js.map index 03f8dda46d0..fc521999494 100644 --- a/dist/es/replication-protocol/helper.js.map +++ b/dist/es/replication-protocol/helper.js.map @@ -1 +1 @@ -{"version":3,"file":"helper.js","names":["createRevision","flatClone","getDefaultRevision","now","docStateToWriteDoc","hashFunction","docState","previous","docData","Object","assign","_attachments","_meta","lwt","_rev","writeDocToDocState","writeDoc","ret"],"sources":["../../../src/replication-protocol/helper.ts"],"sourcesContent":["import type {\n HashFunction,\n RxDocumentData,\n WithDeleted\n} from '../types';\nimport {\n createRevision,\n flatClone,\n getDefaultRevision,\n now\n} from '../util';\n\nexport function docStateToWriteDoc(\n hashFunction: HashFunction,\n docState: WithDeleted,\n previous?: RxDocumentData\n): RxDocumentData {\n const docData: RxDocumentData = Object.assign(\n {},\n docState,\n {\n _attachments: {},\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision()\n }\n );\n docData._rev = createRevision(\n hashFunction,\n docData,\n previous\n );\n return docData;\n}\n\nexport function writeDocToDocState(\n writeDoc: RxDocumentData\n): WithDeleted {\n const ret = flatClone(writeDoc);\n delete (ret as any)._attachments;\n delete (ret as any)._meta;\n delete (ret as any)._rev;\n return ret;\n}\n"],"mappings":"AAKA,SACIA,cAAc,EACdC,SAAS,EACTC,kBAAkB,EAClBC,GAAG,QACA,SAAS;AAEhB,OAAO,SAASC,kBAAkB,CAC9BC,YAA0B,EAC1BC,QAAgC,EAChCC,QAAoC,EACX;EACzB,IAAMC,OAAkC,GAAGC,MAAM,CAACC,MAAM,CACpD,CAAC,CAAC,EACFJ,QAAQ,EACR;IACIK,YAAY,EAAE,CAAC,CAAC;IAChBC,KAAK,EAAE;MACHC,GAAG,EAAEV,GAAG;IACZ,CAAC;IACDW,IAAI,EAAEZ,kBAAkB;EAC5B,CAAC,CACJ;EACDM,OAAO,CAACM,IAAI,GAAGd,cAAc,CACzBK,YAAY,EACZG,OAAO,EACPD,QAAQ,CACX;EACD,OAAOC,OAAO;AAClB;AAEA,OAAO,SAASO,kBAAkB,CAC9BC,QAAmC,EACb;EACtB,IAAMC,GAAG,GAAGhB,SAAS,CAACe,QAAQ,CAAC;EAC/B,OAAQC,GAAG,CAASN,YAAY;EAChC,OAAQM,GAAG,CAASL,KAAK;EACzB,OAAQK,GAAG,CAASH,IAAI;EACxB,OAAOG,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"helper.js","names":["createRevision","flatClone","getDefaultRevision","now","docStateToWriteDoc","databaseInstanceToken","docState","previous","docData","Object","assign","_attachments","_meta","lwt","_rev","writeDocToDocState","writeDoc","ret"],"sources":["../../../src/replication-protocol/helper.ts"],"sourcesContent":["import type {\n RxDocumentData,\n WithDeleted\n} from '../types';\nimport {\n createRevision,\n flatClone,\n getDefaultRevision,\n now\n} from '../plugins/utils';\n\nexport function docStateToWriteDoc(\n databaseInstanceToken: string,\n docState: WithDeleted,\n previous?: RxDocumentData\n): RxDocumentData {\n const docData: RxDocumentData = Object.assign(\n {},\n docState,\n {\n _attachments: {},\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision()\n }\n );\n docData._rev = createRevision(\n databaseInstanceToken,\n previous\n );\n return docData;\n}\n\nexport function writeDocToDocState(\n writeDoc: RxDocumentData\n): WithDeleted {\n const ret = flatClone(writeDoc);\n delete (ret as any)._attachments;\n delete (ret as any)._meta;\n delete (ret as any)._rev;\n return ret;\n}\n"],"mappings":"AAIA,SACIA,cAAc,EACdC,SAAS,EACTC,kBAAkB,EAClBC,GAAG,QACA,kBAAkB;AAEzB,OAAO,SAASC,kBAAkB,CAC9BC,qBAA6B,EAC7BC,QAAgC,EAChCC,QAAoC,EACX;EACzB,IAAMC,OAAkC,GAAGC,MAAM,CAACC,MAAM,CACpD,CAAC,CAAC,EACFJ,QAAQ,EACR;IACIK,YAAY,EAAE,CAAC,CAAC;IAChBC,KAAK,EAAE;MACHC,GAAG,EAAEV,GAAG;IACZ,CAAC;IACDW,IAAI,EAAEZ,kBAAkB;EAC5B,CAAC,CACJ;EACDM,OAAO,CAACM,IAAI,GAAGd,cAAc,CACzBK,qBAAqB,EACrBE,QAAQ,CACX;EACD,OAAOC,OAAO;AAClB;AAEA,OAAO,SAASO,kBAAkB,CAC9BC,QAAmC,EACb;EACtB,IAAMC,GAAG,GAAGhB,SAAS,CAACe,QAAQ,CAAC;EAC/B,OAAQC,GAAG,CAASN,YAAY;EAChC,OAAQM,GAAG,CAASL,KAAK;EACzB,OAAQK,GAAG,CAASH,IAAI;EACxB,OAAOG,GAAG;AACd"} \ No newline at end of file diff --git a/dist/es/replication-protocol/index.js b/dist/es/replication-protocol/index.js index 246ec9d9d1d..39221ec3f3f 100644 --- a/dist/es/replication-protocol/index.js +++ b/dist/es/replication-protocol/index.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * These files contain the replication protocol. * It can be used to replicated RxStorageInstances or RxCollections @@ -6,186 +8,11 @@ import { BehaviorSubject, combineLatest, filter, firstValueFrom, map, Subject } from 'rxjs'; import { getPrimaryFieldOfPrimaryKey } from '../rx-schema-helper'; -import { ensureNotFalsy, PROMISE_RESOLVE_VOID } from '../util'; +import { ensureNotFalsy, PROMISE_RESOLVE_VOID } from '../plugins/utils'; import { getCheckpointKey } from './checkpoint'; import { startReplicationDownstream } from './downstream'; import { docStateToWriteDoc, writeDocToDocState } from './helper'; import { startReplicationUpstream } from './upstream'; -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -export var awaitRxStorageReplicationIdle = function awaitRxStorageReplicationIdle(state) { - try { - return Promise.resolve(awaitRxStorageReplicationFirstInSync(state)).then(function () { - var _exit = false; - return _for(function () { - return !_exit; - }, void 0, function () { - var _state$streamQueue = state.streamQueue, - down = _state$streamQueue.down, - up = _state$streamQueue.up; - return Promise.resolve(Promise.all([up, down])).then(function () { - if (down === state.streamQueue.down && up === state.streamQueue.up) { - _exit = true; - } - }); - /** - * If the Promises have not been reasigned - * after awaiting them, we know that the replication - * is in idle state at this point in time. - */ - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; export * from './checkpoint'; export * from './downstream'; export * from './upstream'; @@ -254,7 +81,43 @@ export function awaitRxStorageReplicationFirstInSync(state) { export function awaitRxStorageReplicationInSync(replicationState) { return Promise.all([replicationState.streamQueue.up, replicationState.streamQueue.down, replicationState.checkpointQueue]); } -export function rxStorageInstanceToReplicationHandler(instance, conflictHandler, hashFunction) { +export function awaitRxStorageReplicationIdle(_x) { + return _awaitRxStorageReplicationIdle.apply(this, arguments); +} +function _awaitRxStorageReplicationIdle() { + _awaitRxStorageReplicationIdle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(state) { + var _state$streamQueue, down, up; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return awaitRxStorageReplicationFirstInSync(state); + case 2: + if (!true) { + _context3.next = 10; + break; + } + _state$streamQueue = state.streamQueue, down = _state$streamQueue.down, up = _state$streamQueue.up; + _context3.next = 6; + return Promise.all([up, down]); + case 6: + if (!(down === state.streamQueue.down && up === state.streamQueue.up)) { + _context3.next = 8; + break; + } + return _context3.abrupt("return"); + case 8: + _context3.next = 2; + break; + case 10: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _awaitRxStorageReplicationIdle.apply(this, arguments); +} +export function rxStorageInstanceToReplicationHandler(instance, conflictHandler, databaseInstanceToken) { var primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey); var replicationHandler = { masterChangeStream$: instance.changeStream().pipe(map(function (eventBulk) { @@ -276,75 +139,109 @@ export function rxStorageInstanceToReplicationHandler(instance, conflictHandler, }; }); }, - masterWrite: function masterWrite(rows) { - try { - var rowById = {}; - rows.forEach(function (row) { - var docId = row.newDocumentState[primaryPath]; - rowById[docId] = row; - }); - var ids = Object.keys(rowById); - return Promise.resolve(instance.findDocumentsById(ids, true)).then(function (masterDocsState) { - var conflicts = []; - var writeRows = []; - return Promise.resolve(Promise.all(Object.entries(rowById).map(function (_ref) { - try { - var id = _ref[0], - row = _ref[1]; - var masterState = masterDocsState[id]; - var _temp3 = function () { - if (!masterState) { - writeRows.push({ - document: docStateToWriteDoc(hashFunction, row.newDocumentState) - }); - } else { - var _temp4 = function () { - if (masterState && !row.assumedMasterState) { - conflicts.push(writeDocToDocState(masterState)); - } else return Promise.resolve(conflictHandler({ - realMasterState: writeDocToDocState(masterState), - newDocumentState: ensureNotFalsy(row.assumedMasterState) - }, 'rxStorageInstanceToReplicationHandler-masterWrite')).then(function (_conflictHandler) { - if (_conflictHandler.isEqual === true) { + masterWrite: function () { + var _masterWrite = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rows) { + var rowById, ids, masterDocsState, conflicts, writeRows, result; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + rowById = {}; + rows.forEach(function (row) { + var docId = row.newDocumentState[primaryPath]; + rowById[docId] = row; + }); + ids = Object.keys(rowById); + _context2.next = 5; + return instance.findDocumentsById(ids, true); + case 5: + masterDocsState = _context2.sent; + conflicts = []; + writeRows = []; + _context2.next = 10; + return Promise.all(Object.entries(rowById).map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref) { + var id, row, masterState; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + id = _ref[0], row = _ref[1]; + masterState = masterDocsState[id]; + if (masterState) { + _context.next = 6; + break; + } + writeRows.push({ + document: docStateToWriteDoc(databaseInstanceToken, row.newDocumentState) + }); + _context.next = 18; + break; + case 6: + if (!(masterState && !row.assumedMasterState)) { + _context.next = 10; + break; + } + conflicts.push(writeDocToDocState(masterState)); + _context.next = 18; + break; + case 10: + _context.next = 12; + return conflictHandler({ + realMasterState: writeDocToDocState(masterState), + newDocumentState: ensureNotFalsy(row.assumedMasterState) + }, 'rxStorageInstanceToReplicationHandler-masterWrite'); + case 12: + _context.t0 = _context.sent.isEqual; + if (!(_context.t0 === true)) { + _context.next = 17; + break; + } writeRows.push({ previous: masterState, - document: docStateToWriteDoc(hashFunction, row.newDocumentState, masterState) + document: docStateToWriteDoc(databaseInstanceToken, row.newDocumentState, masterState) }); - } else { + _context.next = 18; + break; + case 17: conflicts.push(writeDocToDocState(masterState)); - } - }); - }(); - if (_temp4 && _temp4.then) return _temp4.then(function () {}); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp = function () { - if (writeRows.length > 0) { - return Promise.resolve(instance.bulkWrite(writeRows, 'replication-master-write')).then(function (result) { - Object.values(result.error).forEach(function (err) { - if (err.status !== 409) { - throw new Error('non conflict error'); - } else { - conflicts.push(writeDocToDocState(ensureNotFalsy(err.documentInDb))); + case 18: + case "end": + return _context.stop(); } - }); - }); + }, _callee); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }())); + case 10: + if (!(writeRows.length > 0)) { + _context2.next = 15; + break; } - }(); - return _temp && _temp.then ? _temp.then(function () { - return conflicts; - }) : conflicts; - }); - }); - } catch (e) { - return Promise.reject(e); + _context2.next = 13; + return instance.bulkWrite(writeRows, 'replication-master-write'); + case 13: + result = _context2.sent; + Object.values(result.error).forEach(function (err) { + if (err.status !== 409) { + throw new Error('non conflict error'); + } else { + conflicts.push(writeDocToDocState(ensureNotFalsy(err.documentInDb))); + } + }); + case 15: + return _context2.abrupt("return", conflicts); + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function masterWrite(_x2) { + return _masterWrite.apply(this, arguments); } - } + return masterWrite; + }() }; return replicationHandler; } diff --git a/dist/es/replication-protocol/index.js.map b/dist/es/replication-protocol/index.js.map index 5d36c617271..34bcb91e626 100644 --- a/dist/es/replication-protocol/index.js.map +++ b/dist/es/replication-protocol/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","firstValueFrom","map","Subject","getPrimaryFieldOfPrimaryKey","ensureNotFalsy","PROMISE_RESOLVE_VOID","getCheckpointKey","startReplicationDownstream","docStateToWriteDoc","writeDocToDocState","startReplicationUpstream","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","awaitRxStorageReplicationIdle","awaitRxStorageReplicationFirstInSync","streamQueue","down","up","Promise","all","replicateRxStorageInstance","input","checkpointKey","primaryPath","forkInstance","schema","primaryKey","downstreamBulkWriteFlag","events","canceled","active","processed","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","checkpointQueue","lastCheckpointDoc","pipe","awaitRxStorageReplicationInSync","replicationState","rxStorageInstanceToReplicationHandler","instance","conflictHandler","hashFunction","replicationHandler","masterChangeStream$","changeStream","eventBulk","ret","checkpoint","documents","event","documentData","masterChangesSince","batchSize","getChangedDocumentsSince","length","d","masterWrite","rows","rowById","forEach","row","docId","newDocumentState","ids","Object","keys","findDocumentsById","masterDocsState","conflicts","writeRows","entries","id","masterState","push","document","assumedMasterState","realMasterState","isEqual","previous","bulkWrite","values","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n map,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n HashFunction,\n RxConflictHandler,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types';\nimport {\n ensureNotFalsy,\n PROMISE_RESOLVE_VOID\n} from '../util';\nimport {\n getCheckpointKey\n} from './checkpoint';\nimport { startReplicationDownstream } from './downstream';\nimport { docStateToWriteDoc, writeDocToDocState } from './helper';\nimport { startReplicationUpstream } from './upstream';\n\n\nexport * from './checkpoint';\nexport * from './downstream';\nexport * from './upstream';\nexport * from './meta-instance';\nexport * from './conflicts';\nexport * from './helper';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n const checkpointKey = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n input,\n checkpointKey,\n downstreamBulkWriteFlag: 'replication-downstream-' + checkpointKey,\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reasigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n hashFunction: HashFunction\n): RxReplicationHandler {\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n map(eventBulk => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: eventBulk.events.map(event => {\n return writeDocToDocState(ensureNotFalsy(event.documentData) as any);\n })\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return instance.getChangedDocumentsSince(\n batchSize,\n checkpoint\n ).then(result => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: result.documents.map(d => writeDocToDocState(d))\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsState = await instance.findDocumentsById(\n ids,\n true\n );\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState[id];\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(hashFunction, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(hashFunction, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState));\n }\n })\n );\n\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n Object\n .values(result.error)\n .forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb))\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAGA,SACIA,eAAe,EACfC,aAAa,EACbC,MAAM,EACNC,cAAc,EACdC,GAAG,EACHC,OAAO,QACJ,MAAM;AACb,SACIC,2BAA2B,QACxB,qBAAqB;AAc5B,SACIC,cAAc,EACdC,oBAAoB,QACjB,SAAS;AAChB,SACIC,gBAAgB,QACb,cAAc;AACrB,SAASC,0BAA0B,QAAQ,cAAc;AACzD,SAASC,kBAAkB,EAAEC,kBAAkB,QAAQ,UAAU;AACjE,SAASC,wBAAwB,QAAQ,YAAY;AAD9C,iBAAiBC,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACK,IAAI,EAAE;MACxBL,KAAK,CAACK,IAAI,CAAC,QAAQD,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,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AG,EAAE;sBACpB,MAAM,IAAIC,KAAK,CAAC,oBAAoB,CAAC;oBACzC,CAAC,MAAM;sBACHf,SAAS,CAACK,IAAI,CACVvG,kBAAkB,CAACL,cAAc,CAACoH,GAAG,CAACG,YAAY,CAAC,CAAC,CACvD;oBACL;kBACJ,CAAC,CAAC;gBAAC;cAAA;YAAA;YAAA;cAEX,OAAOhB,SAAS;YAAC,KAAVA,SAAS;UAAA;QAAA;MACpB,CAAC;QAAA;MAAA;IAAA;EACL,CAAC;EAED,OAAO1B,kBAAkB;AAC7B;AAGA,OAAO,SAAS2C,0BAA0B,CACtChD,gBAAwD,EAC1D;EACEA,gBAAgB,CAACvB,MAAM,CAACC,QAAQ,CAACuE,IAAI,CAAC,IAAI,CAAC;EAC3CjD,gBAAgB,CAACvB,MAAM,CAACE,MAAM,CAACb,EAAE,CAACoF,QAAQ,EAAE;EAC5ClD,gBAAgB,CAACvB,MAAM,CAACE,MAAM,CAACd,IAAI,CAACqF,QAAQ,EAAE;EAC9ClD,gBAAgB,CAACvB,MAAM,CAACG,SAAS,CAACd,EAAE,CAACoF,QAAQ,EAAE;EAC/ClD,gBAAgB,CAACvB,MAAM,CAACG,SAAS,CAACf,IAAI,CAACqF,QAAQ,EAAE;EACjDlD,gBAAgB,CAACvB,MAAM,CAACI,iBAAiB,CAACqE,QAAQ,EAAE;EACpDlD,gBAAgB,CAACvB,MAAM,CAACC,QAAQ,CAACwE,QAAQ,EAAE;AAC/C"} \ No newline at end of file +{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","firstValueFrom","map","Subject","getPrimaryFieldOfPrimaryKey","ensureNotFalsy","PROMISE_RESOLVE_VOID","getCheckpointKey","startReplicationDownstream","docStateToWriteDoc","writeDocToDocState","startReplicationUpstream","replicateRxStorageInstance","input","checkpointKey","state","primaryPath","forkInstance","schema","primaryKey","downstreamBulkWriteFlag","events","canceled","active","down","up","processed","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","streamQueue","checkpointQueue","lastCheckpointDoc","awaitRxStorageReplicationFirstInSync","pipe","v","then","awaitRxStorageReplicationInSync","replicationState","Promise","all","awaitRxStorageReplicationIdle","rxStorageInstanceToReplicationHandler","instance","conflictHandler","databaseInstanceToken","replicationHandler","masterChangeStream$","changeStream","eventBulk","ret","checkpoint","documents","event","documentData","masterChangesSince","batchSize","getChangedDocumentsSince","result","length","d","masterWrite","rows","rowById","forEach","row","docId","newDocumentState","ids","Object","keys","findDocumentsById","masterDocsState","conflicts","writeRows","entries","id","masterState","push","document","assumedMasterState","realMasterState","isEqual","previous","bulkWrite","values","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n map,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n RxConflictHandler,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types';\nimport {\n ensureNotFalsy,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils';\nimport {\n getCheckpointKey\n} from './checkpoint';\nimport { startReplicationDownstream } from './downstream';\nimport { docStateToWriteDoc, writeDocToDocState } from './helper';\nimport { startReplicationUpstream } from './upstream';\n\n\nexport * from './checkpoint';\nexport * from './downstream';\nexport * from './upstream';\nexport * from './meta-instance';\nexport * from './conflicts';\nexport * from './helper';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n const checkpointKey = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n input,\n checkpointKey,\n downstreamBulkWriteFlag: 'replication-downstream-' + checkpointKey,\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reasigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n databaseInstanceToken: string\n): RxReplicationHandler {\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n map(eventBulk => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: eventBulk.events.map(event => {\n return writeDocToDocState(ensureNotFalsy(event.documentData) as any);\n })\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return instance.getChangedDocumentsSince(\n batchSize,\n checkpoint\n ).then(result => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: result.documents.map(d => writeDocToDocState(d))\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsState = await instance.findDocumentsById(\n ids,\n true\n );\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState[id];\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(databaseInstanceToken, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(databaseInstanceToken, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState));\n }\n })\n );\n\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n Object\n .values(result.error)\n .forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb))\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;;AAGA,SACIA,eAAe,EACfC,aAAa,EACbC,MAAM,EACNC,cAAc,EACdC,GAAG,EACHC,OAAO,QACJ,MAAM;AACb,SACIC,2BAA2B,QACxB,qBAAqB;AAa5B,SACIC,cAAc,EACdC,oBAAoB,QACjB,kBAAkB;AACzB,SACIC,gBAAgB,QACb,cAAc;AACrB,SAASC,0BAA0B,QAAQ,cAAc;AACzD,SAASC,kBAAkB,EAAEC,kBAAkB,QAAQ,UAAU;AACjE,SAASC,wBAAwB,QAAQ,YAAY;AAGrD,cAAc,cAAc;AAC5B,cAAc,cAAc;AAC5B,cAAc,YAAY;AAC1B,cAAc,iBAAiB;AAC/B,cAAc,aAAa;AAC3B,cAAc,UAAU;AAGxB,OAAO,SAASC,0BAA0B,CACtCC,KAAmD,EACP;EAC5C,IAAMC,aAAa,GAAGP,gBAAgB,CAACM,KAAK,CAAC;EAC7C,IAAME,KAAmD,GAAG;IACxDC,WAAW,EAAEZ,2BAA2B,CAACS,KAAK,CAACI,YAAY,CAACC,MAAM,CAACC,UAAU,CAAC;IAC9EN,KAAK,EAALA,KAAK;IACLC,aAAa,EAAbA,aAAa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,CAACM,iBAAiB,CAAC6E,QAAQ,EAAE;EACpDtD,gBAAgB,CAAC7B,MAAM,CAACC,QAAQ,CAACkF,QAAQ,EAAE;AAC/C"} \ No newline at end of file diff --git a/dist/es/replication-protocol/meta-instance.js b/dist/es/replication-protocol/meta-instance.js index 68fa2131dd9..876259f4ee1 100644 --- a/dist/es/replication-protocol/meta-instance.js +++ b/dist/es/replication-protocol/meta-instance.js @@ -1,6 +1,6 @@ import { fillWithDefaultSettings, getComposedPrimaryKeyOfDocumentData } from '../rx-schema-helper'; import { flatCloneDocWithMeta } from '../rx-storage-helper'; -import { getDefaultRevision, createRevision, now } from '../util'; +import { getDefaultRevision, createRevision, now } from '../plugins/utils'; export var RX_REPLICATION_META_INSTANCE_SCHEMA = fillWithDefaultSettings({ primaryKey: { key: 'id', @@ -80,7 +80,7 @@ export function getMetaWriteRow(state, newMasterDocState, previous, isResolvedCo newMeta.isResolvedConflict = isResolvedConflict; newMeta._meta.lwt = now(); newMeta.id = getComposedPrimaryKeyOfDocumentData(RX_REPLICATION_META_INSTANCE_SCHEMA, newMeta); - newMeta._rev = createRevision(state.input.hashFunction, newMeta, previous); + newMeta._rev = createRevision(state.input.identifier, previous); return { previous: previous, document: newMeta diff --git a/dist/es/replication-protocol/meta-instance.js.map b/dist/es/replication-protocol/meta-instance.js.map index 2c1d17cfedb..a47f21eeca8 100644 --- a/dist/es/replication-protocol/meta-instance.js.map +++ b/dist/es/replication-protocol/meta-instance.js.map @@ -1 +1 @@ -{"version":3,"file":"meta-instance.js","names":["fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","flatCloneDocWithMeta","getDefaultRevision","createRevision","now","RX_REPLICATION_META_INSTANCE_SCHEMA","primaryKey","key","fields","separator","type","version","additionalProperties","properties","id","minLength","maxLength","replicationIdentifier","isCheckpoint","itemId","data","isResolvedConflict","required","getAssumedMasterState","state","docIds","input","metaInstance","findDocumentsById","map","docId","useId","checkpointKey","then","metaDocs","ret","Object","values","forEach","metaDoc","docData","metaDocument","getMetaWriteRow","newMasterDocState","previous","primaryPath","newMeta","_attachments","_deleted","_rev","_meta","lwt","hashFunction","document"],"sources":["../../../src/replication-protocol/meta-instance.ts"],"sourcesContent":["import {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from '../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n ById,\n RxDocumentData,\n RxJsonSchema,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport { getDefaultRevision, createRevision, now } from '../util';\n\nexport const RX_REPLICATION_META_INSTANCE_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n primaryKey: {\n key: 'id',\n fields: [\n 'replicationIdentifier',\n 'itemId',\n 'isCheckpoint'\n ],\n separator: '|'\n },\n type: 'object',\n version: 0,\n additionalProperties: false,\n properties: {\n id: {\n type: 'string',\n minLength: 1,\n maxLength: 100\n },\n replicationIdentifier: {\n type: 'string'\n },\n isCheckpoint: {\n type: 'string',\n enum: [\n '0',\n '1'\n ],\n maxLength: 1\n },\n itemId: {\n type: 'string'\n },\n data: {\n type: 'object',\n additionalProperties: true\n },\n isResolvedConflict: {\n type: 'string'\n }\n },\n required: [\n 'id',\n 'replicationIdentifier',\n 'isCheckpoint',\n 'itemId',\n 'data'\n ]\n});\n\n\n/**\n * Returns the document states of what the fork instance\n * assumes to be the latest state on the master instance.\n */\nexport function getAssumedMasterState(\n state: RxStorageInstanceReplicationState,\n docIds: string[]\n): Promise;\n metaDocument: RxDocumentData;\n }>> {\n return state.input.metaInstance.findDocumentsById(\n docIds.map(docId => {\n const useId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n itemId: docId,\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0'\n }\n );\n return useId;\n }),\n true\n ).then(metaDocs => {\n const ret: {\n [docId: string]: {\n docData: RxDocumentData;\n metaDocument: RxDocumentData;\n };\n } = {};\n Object\n .values(metaDocs)\n .forEach((metaDoc) => {\n ret[metaDoc.itemId] = {\n docData: metaDoc.data,\n metaDocument: metaDoc\n };\n });\n\n return ret;\n });\n}\n\n\nexport function getMetaWriteRow(\n state: RxStorageInstanceReplicationState,\n newMasterDocState: WithDeleted,\n previous?: RxDocumentData,\n isResolvedConflict?: string\n): BulkWriteRow {\n const docId: string = (newMasterDocState as any)[state.primaryPath];\n const newMeta: RxDocumentData = previous ? flatCloneDocWithMeta(\n previous\n ) : {\n id: '',\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0',\n itemId: docId,\n data: newMasterDocState,\n _attachments: {},\n _deleted: false,\n _rev: getDefaultRevision(),\n _meta: {\n lwt: 0\n }\n };\n newMeta.data = newMasterDocState;\n newMeta.isResolvedConflict = isResolvedConflict;\n newMeta._meta.lwt = now();\n newMeta.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newMeta\n );\n newMeta._rev = createRevision(\n state.input.hashFunction,\n newMeta,\n previous\n );\n return {\n previous,\n document: newMeta\n };\n}\n"],"mappings":"AAAA,SACIA,uBAAuB,EACvBC,mCAAmC,QAChC,qBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,sBAAsB;AAU3D,SAASC,kBAAkB,EAAEC,cAAc,EAAEC,GAAG,QAAQ,SAAS;AAEjE,OAAO,IAAMC,mCAA2F,GAAGN,uBAAuB,CAAC;EAC/HO,UAAU,EAAE;IACRC,GAAG,EAAE,IAAI;IACTC,MAAM,EAAE,CACJ,uBAAuB,EACvB,QAAQ,EACR,cAAc,CACjB;IACDC,SAAS,EAAE;EACf,CAAC;EACDC,IAAI,EAAE,QAAQ;EACdC,OAAO,EAAE,CAAC;EACVC,oBAAoB,EAAE,KAAK;EAC3BC,UAAU,EAAE;IACRC,EAAE,EAAE;MACAJ,IAAI,EAAE,QAAQ;MACdK,SAAS,EAAE,CAAC;MACZC,SAAS,EAAE;IACf,CAAC;IAC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B,iBAAyC,EACzCC,QAAmD,EACnDvB,kBAA2B,EACW;EACtC,IAAMS,KAAa,GAAIa,iBAAiB,CAASnB,KAAK,CAACqB,WAAW,CAAC;EACnE,IAAMC,OAAiD,GAAGF,QAAQ,GAAG3C,oBAAoB,CACrF2C,QAAQ,CACX,GAAG;IACA9B,EAAE,EAAE,EAAE;IACNG,qBAAqB,EAAEO,KAAK,CAACQ,aAAa;IAC1Cd,YAAY,EAAE,GAAG;IACjBC,MAAM,EAAEW,KAAK;IACbV,IAAI,EAAEuB,iBAAiB;IACvBI,YAAY,EAAE,CAAC,CAAC;IAChBC,QAAQ,EAAE,KAAK;IACfC,IAAI,EAAE/C,kBAAkB,EAAE;IAC1BgD,KAAK,EAAE;MACHC,GAAG,EAAE;IACT;EACJ,CAAC;EACDL,OAAO,CAAC1B,IAAI,GAAGuB,iBAAiB;EAChCG,OAAO,CAACzB,kBAAkB,GAAGA,kBAAkB;EAC/CyB,OAAO,CAACI,KAAK,CAACC,GAAG,GAAG/C,GAAG,EAAE;EACzB0C,OAAO,CAAChC,EAAE,GAAGd,mCAAmC,CAC5CK,mCAAmC,EACnCyC,OAAO,CACV;EACDA,OAAO,CAACG,IAAI,GAAG9C,cAAc,CACzBqB,KAAK,CAACE,KAAK,CAAC0B,YAAY,EACxBN,OAAO,EACPF,QAAQ,CACX;EACD,OAAO;IACHA,QAAQ,EAARA,QAAQ;IACRS,QAAQ,EAAEP;EACd,CAAC;AACL"} \ No newline at end of file +{"version":3,"file":"meta-instance.js","names":["fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","flatCloneDocWithMeta","getDefaultRevision","createRevision","now","RX_REPLICATION_META_INSTANCE_SCHEMA","primaryKey","key","fields","separator","type","version","additionalProperties","properties","id","minLength","maxLength","replicationIdentifier","isCheckpoint","itemId","data","isResolvedConflict","required","getAssumedMasterState","state","docIds","input","metaInstance","findDocumentsById","map","docId","useId","checkpointKey","then","metaDocs","ret","Object","values","forEach","metaDoc","docData","metaDocument","getMetaWriteRow","newMasterDocState","previous","primaryPath","newMeta","_attachments","_deleted","_rev","_meta","lwt","identifier","document"],"sources":["../../../src/replication-protocol/meta-instance.ts"],"sourcesContent":["import {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from '../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n ById,\n RxDocumentData,\n RxJsonSchema,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport { getDefaultRevision, createRevision, now } from '../plugins/utils';\n\nexport const RX_REPLICATION_META_INSTANCE_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n primaryKey: {\n key: 'id',\n fields: [\n 'replicationIdentifier',\n 'itemId',\n 'isCheckpoint'\n ],\n separator: '|'\n },\n type: 'object',\n version: 0,\n additionalProperties: false,\n properties: {\n id: {\n type: 'string',\n minLength: 1,\n maxLength: 100\n },\n replicationIdentifier: {\n type: 'string'\n },\n isCheckpoint: {\n type: 'string',\n enum: [\n '0',\n '1'\n ],\n maxLength: 1\n },\n itemId: {\n type: 'string'\n },\n data: {\n type: 'object',\n additionalProperties: true\n },\n isResolvedConflict: {\n type: 'string'\n }\n },\n required: [\n 'id',\n 'replicationIdentifier',\n 'isCheckpoint',\n 'itemId',\n 'data'\n ]\n});\n\n\n/**\n * Returns the document states of what the fork instance\n * assumes to be the latest state on the master instance.\n */\nexport function getAssumedMasterState(\n state: RxStorageInstanceReplicationState,\n docIds: string[]\n): Promise;\n metaDocument: RxDocumentData;\n }>> {\n return state.input.metaInstance.findDocumentsById(\n docIds.map(docId => {\n const useId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n itemId: docId,\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0'\n }\n );\n return useId;\n }),\n true\n ).then(metaDocs => {\n const ret: {\n [docId: string]: {\n docData: RxDocumentData;\n metaDocument: RxDocumentData;\n };\n } = {};\n Object\n .values(metaDocs)\n .forEach((metaDoc) => {\n ret[metaDoc.itemId] = {\n docData: metaDoc.data,\n metaDocument: metaDoc\n };\n });\n\n return ret;\n });\n}\n\n\nexport function getMetaWriteRow(\n state: RxStorageInstanceReplicationState,\n newMasterDocState: WithDeleted,\n previous?: RxDocumentData,\n isResolvedConflict?: string\n): BulkWriteRow {\n const docId: string = (newMasterDocState as any)[state.primaryPath];\n const newMeta: RxDocumentData = previous ? flatCloneDocWithMeta(\n previous\n ) : {\n id: '',\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0',\n itemId: docId,\n data: newMasterDocState,\n _attachments: {},\n _deleted: false,\n _rev: getDefaultRevision(),\n _meta: {\n lwt: 0\n }\n };\n newMeta.data = newMasterDocState;\n newMeta.isResolvedConflict = isResolvedConflict;\n newMeta._meta.lwt = now();\n newMeta.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newMeta\n );\n newMeta._rev = createRevision(\n state.input.identifier,\n previous\n );\n return {\n previous,\n document: newMeta\n };\n}\n"],"mappings":"AAAA,SACIA,uBAAuB,EACvBC,mCAAmC,QAChC,qBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,sBAAsB;AAU3D,SAASC,kBAAkB,EAAEC,cAAc,EAAEC,GAAG,QAAQ,kBAAkB;AAE1E,OAAO,IAAMC,mCAA2F,GAAGN,uBAAuB,CAAC;EAC/HO,UAAU,EAAE;IACRC,GAAG,EAAE,IAAI;IACTC,MAAM,EAAE,CACJ,uBAAuB,EACvB,QAAQ,EACR,cAAc,CACjB;IACDC,SAAS,EAAE;EACf,CAAC;EACDC,IAAI,EAAE,QAAQ;EACdC,OAAO,EAAE,CAAC;EACVC,oBAAoB,EAAE,KAAK;EAC3BC,UAAU,EAAE;IACRC,EAAE,EAAE;MACAJ,IAAI,EAAE,QAAQ;MACdK,SAAS,EAAE,CAAC;MACZC,SAAS,EAAE;IACf,CAAC;IACDC,qBAAqB,EA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CC,QAAmD,EACnDvB,kBAA2B,EACW;EACtC,IAAMS,KAAa,GAAIa,iBAAiB,CAASnB,KAAK,CAACqB,WAAW,CAAC;EACnE,IAAMC,OAAiD,GAAGF,QAAQ,GAAG3C,oBAAoB,CACrF2C,QAAQ,CACX,GAAG;IACA9B,EAAE,EAAE,EAAE;IACNG,qBAAqB,EAAEO,KAAK,CAACQ,aAAa;IAC1Cd,YAAY,EAAE,GAAG;IACjBC,MAAM,EAAEW,KAAK;IACbV,IAAI,EAAEuB,iBAAiB;IACvBI,YAAY,EAAE,CAAC,CAAC;IAChBC,QAAQ,EAAE,KAAK;IACfC,IAAI,EAAE/C,kBAAkB,EAAE;IAC1BgD,KAAK,EAAE;MACHC,GAAG,EAAE;IACT;EACJ,CAAC;EACDL,OAAO,CAAC1B,IAAI,GAAGuB,iBAAiB;EAChCG,OAAO,CAACzB,kBAAkB,GAAGA,kBAAkB;EAC/CyB,OAAO,CAACI,KAAK,CAACC,GAAG,GAAG/C,GAAG,EAAE;EACzB0C,OAAO,CAAChC,EAAE,GAAGd,mCAAmC,CAC5CK,mCAAmC,EACnCyC,OAAO,CACV;EACDA,OAAO,CAACG,IAAI,GAAG9C,cAAc,CACzBqB,KAAK,CAACE,KAAK,CAAC0B,UAAU,EACtBR,QAAQ,CACX;EACD,OAAO;IACHA,QAAQ,EAARA,QAAQ;IACRS,QAAQ,EAAEP;EACd,CAAC;AACL"} \ No newline at end of file diff --git a/dist/es/replication-protocol/upstream.js b/dist/es/replication-protocol/upstream.js index cee43ca410e..c6013c43ef7 100644 --- a/dist/es/replication-protocol/upstream.js +++ b/dist/es/replication-protocol/upstream.js @@ -1,6 +1,8 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { firstValueFrom, filter } from 'rxjs'; import { stackCheckpoints } from '../rx-storage-helper'; -import { batchArray, ensureNotFalsy, parseRevision, PROMISE_RESOLVE_FALSE } from '../util'; +import { batchArray, ensureNotFalsy, parseRevision, PROMISE_RESOLVE_FALSE } from '../plugins/utils'; import { getLastCheckpointDoc, setCheckpoint } from './checkpoint'; import { resolveConflictError } from './conflicts'; import { writeDocToDocState } from './helper'; @@ -14,210 +16,7 @@ import { getAssumedMasterState, getMetaWriteRow } from './meta-instance'; * In contrast to the master, the fork can be assumed to never loose connection, * so we do not have to prepare for missed out events. */ -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - const observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} export function startReplicationUpstream(state) { - var upstreamInitialSync = function upstreamInitialSync() { - try { - state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1; - if (state.events.canceled.getValue()) { - return Promise.resolve(); - } - state.checkpointQueue = state.checkpointQueue.then(function () { - return getLastCheckpointDoc(state, 'up'); - }); - return Promise.resolve(state.checkpointQueue).then(function (lastCheckpoint) { - var _interrupt = false; - function _temp11() { - /** - * If we had conflicts during the initial sync, - * it means that we likely have new writes to the fork - * and so we have to run the initial sync again to upastream these new writes. - */ - return Promise.resolve(Promise.all(promises)).then(function (resolvedPromises) { - var hadConflicts = resolvedPromises.find(function (r) { - return !!r; - }); - var _temp9 = function () { - if (hadConflicts) { - return Promise.resolve(upstreamInitialSync()).then(function () {}); - } else if (!state.firstSyncDone.up.getValue()) { - state.firstSyncDone.up.next(true); - } - }(); - if (_temp9 && _temp9.then) return _temp9.then(function () {}); - }); - } - var promises = []; - var _temp10 = _for(function () { - return !_interrupt && !state.events.canceled.getValue(); - }, void 0, function () { - initialSyncStartTime = timer++; - return Promise.resolve(state.input.forkInstance.getChangedDocumentsSince(state.input.pushBatchSize, lastCheckpoint)).then(function (upResult) { - if (upResult.documents.length === 0) { - _interrupt = true; - return; - } - lastCheckpoint = stackCheckpoints([lastCheckpoint, upResult.checkpoint]); - promises.push(persistToMaster(upResult.documents, ensureNotFalsy(lastCheckpoint))); - }); - }); - return _temp10 && _temp10.then ? _temp10.then(_temp11) : _temp11(_temp10); - }); - } catch (e) { - return Promise.reject(e); - } - }; - /** - * Takes all open tasks an processes them at once. - */ var replicationHandler = state.input.replicationHandler; state.streamQueue.up = state.streamQueue.up.then(function () { return upstreamInitialSync().then(function () { @@ -250,6 +49,82 @@ export function startReplicationUpstream(state) { }))).then(function () { return sub.unsubscribe(); }); + function upstreamInitialSync() { + return _upstreamInitialSync.apply(this, arguments); + } + /** + * Takes all open tasks an processes them at once. + */ + function _upstreamInitialSync() { + _upstreamInitialSync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { + var lastCheckpoint, promises, upResult, resolvedPromises, hadConflicts; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1; + if (!state.events.canceled.getValue()) { + _context4.next = 3; + break; + } + return _context4.abrupt("return"); + case 3: + state.checkpointQueue = state.checkpointQueue.then(function () { + return getLastCheckpointDoc(state, 'up'); + }); + _context4.next = 6; + return state.checkpointQueue; + case 6: + lastCheckpoint = _context4.sent; + promises = []; + case 8: + if (state.events.canceled.getValue()) { + _context4.next = 19; + break; + } + initialSyncStartTime = timer++; + _context4.next = 12; + return state.input.forkInstance.getChangedDocumentsSince(state.input.pushBatchSize, lastCheckpoint); + case 12: + upResult = _context4.sent; + if (!(upResult.documents.length === 0)) { + _context4.next = 15; + break; + } + return _context4.abrupt("break", 19); + case 15: + lastCheckpoint = stackCheckpoints([lastCheckpoint, upResult.checkpoint]); + promises.push(persistToMaster(upResult.documents, ensureNotFalsy(lastCheckpoint))); + _context4.next = 8; + break; + case 19: + _context4.next = 21; + return Promise.all(promises); + case 21: + resolvedPromises = _context4.sent; + hadConflicts = resolvedPromises.find(function (r) { + return !!r; + }); + if (!hadConflicts) { + _context4.next = 28; + break; + } + _context4.next = 26; + return upstreamInitialSync(); + case 26: + _context4.next = 29; + break; + case 28: + if (!state.firstSyncDone.up.getValue()) { + state.firstSyncDone.up.next(true); + } + case 29: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _upstreamInitialSync.apply(this, arguments); + } function processTasks() { if (state.events.canceled.getValue() || openTasks.length === 0) { state.events.active.up.next(false); @@ -308,191 +183,242 @@ export function startReplicationUpstream(state) { nonPersistedFromMaster.docs[docId] = docData; }); nonPersistedFromMaster.checkpoint = checkpoint; - persistenceQueue = persistenceQueue.then(function () { - try { - if (state.events.canceled.getValue()) { - return Promise.resolve(false); - } - var upDocsById = nonPersistedFromMaster.docs; - nonPersistedFromMaster.docs = {}; - var useCheckpoint = nonPersistedFromMaster.checkpoint; - var docIds = Object.keys(upDocsById); - if (docIds.length === 0) { - return Promise.resolve(false); - } - return Promise.resolve(getAssumedMasterState(state, docIds)).then(function (assumedMasterState) { - var writeRowsToMaster = {}; - var writeRowsToMasterIds = []; - var writeRowsToMeta = {}; - var forkStateById = {}; - return Promise.resolve(Promise.all(docIds.map(function (docId) { - try { - var _temp8 = function _temp8(_state$input$conflict) { - if (_temp7 && _state$input$conflict.isEqual || - /** - * If the master works with _rev fields, - * we use that to check if our current doc state - * is different from the assumedMasterDoc. - */ - - assumedMasterDoc && assumedMasterDoc.docData._rev && parseRevision(fullDocData._rev).height === fullDocData._meta[state.input.identifier]) { - _exit = true; - return; - } - writeRowsToMasterIds.push(docId); - writeRowsToMaster[docId] = { - assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined, - newDocumentState: docData - }; - writeRowsToMeta[docId] = getMetaWriteRow(state, docData, assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined); - }; - var _exit = false; - var fullDocData = upDocsById[docId]; - forkStateById[docId] = fullDocData; - var docData = writeDocToDocState(fullDocData); - var assumedMasterDoc = assumedMasterState[docId]; - - /** - * If the master state is equal to the - * fork state, we can assume that the document state is already - * replicated. - */ - var _temp7 = assumedMasterDoc && - // if the isResolvedConflict is correct, we do not have to compare the documents. - assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev; - return Promise.resolve(_temp7 ? Promise.resolve(state.input.conflictHandler({ - realMasterState: assumedMasterDoc.docData, - newDocumentState: docData - }, 'upstream-check-if-equal')).then(_temp8) : _temp8(_temp7)); - } catch (e) { - return Promise.reject(e); + persistenceQueue = persistenceQueue.then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var upDocsById, useCheckpoint, docIds, assumedMasterState, writeRowsToMaster, writeRowsToMasterIds, writeRowsToMeta, forkStateById, writeRowsArray, conflictIds, conflictsById, writeBatches, useWriteRowsToMeta, hadConflictWrites, conflictWriteFork, conflictWriteMeta, forkWriteResult, useMetaWrites; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!state.events.canceled.getValue()) { + _context3.next = 2; + break; } - }))).then(function () { - if (writeRowsToMasterIds.length === 0) { - return false; + return _context3.abrupt("return", false); + case 2: + upDocsById = nonPersistedFromMaster.docs; + nonPersistedFromMaster.docs = {}; + useCheckpoint = nonPersistedFromMaster.checkpoint; + docIds = Object.keys(upDocsById); + if (!(docIds.length === 0)) { + _context3.next = 8; + break; } - var writeRowsArray = Object.values(writeRowsToMaster); - var conflictIds = new Set(); - var conflictsById = {}; + return _context3.abrupt("return", false); + case 8: + _context3.next = 10; + return getAssumedMasterState(state, docIds); + case 10: + assumedMasterState = _context3.sent; + writeRowsToMaster = {}; + writeRowsToMasterIds = []; + writeRowsToMeta = {}; + forkStateById = {}; + _context3.next = 17; + return Promise.all(docIds.map( /*#__PURE__*/function () { + var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(docId) { + var fullDocData, docData, assumedMasterDoc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + fullDocData = upDocsById[docId]; + forkStateById[docId] = fullDocData; + docData = writeDocToDocState(fullDocData); + assumedMasterDoc = assumedMasterState[docId]; + /** + * If the master state is equal to the + * fork state, we can assume that the document state is already + * replicated. + */ + _context.t1 = assumedMasterDoc && + // if the isResolvedConflict is correct, we do not have to compare the documents. + assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev; + if (!_context.t1) { + _context.next = 9; + break; + } + _context.next = 8; + return state.input.conflictHandler({ + realMasterState: assumedMasterDoc.docData, + newDocumentState: docData + }, 'upstream-check-if-equal'); + case 8: + _context.t1 = _context.sent.isEqual; + case 9: + _context.t0 = _context.t1; + if (_context.t0) { + _context.next = 12; + break; + } + _context.t0 = + /** + * If the master works with _rev fields, + * we use that to check if our current doc state + * is different from the assumedMasterDoc. + */ + assumedMasterDoc && assumedMasterDoc.docData._rev && parseRevision(fullDocData._rev).height === fullDocData._meta[state.input.identifier]; + case 12: + if (!_context.t0) { + _context.next = 14; + break; + } + return _context.abrupt("return"); + case 14: + writeRowsToMasterIds.push(docId); + writeRowsToMaster[docId] = { + assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined, + newDocumentState: docData + }; + writeRowsToMeta[docId] = getMetaWriteRow(state, docData, assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined); + case 17: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); + case 17: + if (!(writeRowsToMasterIds.length === 0)) { + _context3.next = 19; + break; + } + return _context3.abrupt("return", false); + case 19: + writeRowsArray = Object.values(writeRowsToMaster); + conflictIds = new Set(); + conflictsById = {}; /** * To always respect the push.batchSize, * we have to split the write rows into batches * to ensure that replicationHandler.masterWrite() is never * called with more documents than what the batchSize limits. */ - var writeBatches = batchArray(writeRowsArray, state.input.pushBatchSize); - return Promise.resolve(Promise.all(writeBatches.map(function (writeBatch) { - try { - return Promise.resolve(replicationHandler.masterWrite(writeBatch)).then(function (masterWriteResult) { - masterWriteResult.forEach(function (conflictDoc) { - var id = conflictDoc[state.primaryPath]; - conflictIds.add(id); - conflictsById[id] = conflictDoc; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - function _temp6() { - function _temp4() { - /** - * For better performance we do not await checkpoint writes, - * but to ensure order on parallel checkpoint writes, - * we have to use a queue. - */ - state.checkpointQueue = state.checkpointQueue.then(function () { - return setCheckpoint(state, 'up', useCheckpoint); - }); - return hadConflictWrites; - } - /** - * Resolve conflicts by writing a new document - * state to the fork instance and the 'real' master state - * to the meta instance. - * Non-409 errors will be detected by resolveConflictError() - */ - var hadConflictWrites = false; - var _temp3 = function () { - if (conflictIds.size > 0) { - state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1; - var conflictWriteFork = []; - var conflictWriteMeta = {}; - return Promise.resolve(Promise.all(Object.entries(conflictsById).map(function (_ref) { - var docId = _ref[0], - realMasterState = _ref[1]; - var writeToMasterRow = writeRowsToMaster[docId]; - var input = { - newDocumentState: writeToMasterRow.newDocumentState, - assumedMasterState: writeToMasterRow.assumedMasterState, - realMasterState: realMasterState - }; - return resolveConflictError(state, input, forkStateById[docId]).then(function (resolved) { - if (resolved) { - state.events.resolvedConflicts.next({ - input: input, - output: resolved.output - }); - conflictWriteFork.push({ - previous: forkStateById[docId], - document: resolved.resolvedDoc - }); - var assumedMasterDoc = assumedMasterState[docId]; - conflictWriteMeta[docId] = getMetaWriteRow(state, ensureNotFalsy(realMasterState), assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined, resolved.resolvedDoc._rev); - } + writeBatches = batchArray(writeRowsArray, state.input.pushBatchSize); + _context3.next = 25; + return Promise.all(writeBatches.map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(writeBatch) { + var masterWriteResult; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return replicationHandler.masterWrite(writeBatch); + case 2: + masterWriteResult = _context2.sent; + masterWriteResult.forEach(function (conflictDoc) { + var id = conflictDoc[state.primaryPath]; + conflictIds.add(id); + conflictsById[id] = conflictDoc; }); - }))).then(function () { - var _temp2 = function () { - if (conflictWriteFork.length > 0) { - hadConflictWrites = true; - state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1; - return Promise.resolve(state.input.forkInstance.bulkWrite(conflictWriteFork, 'replication-up-write-conflict')).then(function (forkWriteResult) { - /** - * Errors in the forkWriteResult must not be handled - * because they have been caused by a write to the forkInstance - * in between which will anyway trigger a new upstream cycle - * that will then resolved the conflict again. - */ - var useMetaWrites = []; - Object.keys(forkWriteResult.success).forEach(function (docId) { - useMetaWrites.push(conflictWriteMeta[docId]); - }); - var _temp = function () { - if (useMetaWrites.length > 0) { - return Promise.resolve(state.input.metaInstance.bulkWrite(useMetaWrites, 'replication-up-write-conflict-meta')).then(function () {}); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); // TODO what to do with conflicts while writing to the metaInstance? - } - }(); - if (_temp2 && _temp2.then) return _temp2.then(function () {}); - }); + case 4: + case "end": + return _context2.stop(); } - }(); - return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3); + }, _callee2); + })); + return function (_x2) { + return _ref3.apply(this, arguments); + }; + }())); + case 25: + useWriteRowsToMeta = []; + writeRowsToMasterIds.forEach(function (docId) { + if (!conflictIds.has(docId)) { + state.events.processed.up.next(writeRowsToMaster[docId]); + useWriteRowsToMeta.push(writeRowsToMeta[docId]); } - var useWriteRowsToMeta = []; - writeRowsToMasterIds.forEach(function (docId) { - if (!conflictIds.has(docId)) { - state.events.processed.up.next(writeRowsToMaster[docId]); - useWriteRowsToMeta.push(writeRowsToMeta[docId]); + }); + if (!(useWriteRowsToMeta.length > 0)) { + _context3.next = 30; + break; + } + _context3.next = 30; + return state.input.metaInstance.bulkWrite(useWriteRowsToMeta, 'replication-up-write-meta'); + case 30: + /** + * Resolve conflicts by writing a new document + * state to the fork instance and the 'real' master state + * to the meta instance. + * Non-409 errors will be detected by resolveConflictError() + */ + hadConflictWrites = false; + if (!(conflictIds.size > 0)) { + _context3.next = 48; + break; + } + state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1; + conflictWriteFork = []; + conflictWriteMeta = {}; + _context3.next = 37; + return Promise.all(Object.entries(conflictsById).map(function (_ref4) { + var docId = _ref4[0], + realMasterState = _ref4[1]; + var writeToMasterRow = writeRowsToMaster[docId]; + var input = { + newDocumentState: writeToMasterRow.newDocumentState, + assumedMasterState: writeToMasterRow.assumedMasterState, + realMasterState: realMasterState + }; + return resolveConflictError(state, input, forkStateById[docId]).then(function (resolved) { + if (resolved) { + state.events.resolvedConflicts.next({ + input: input, + output: resolved.output + }); + conflictWriteFork.push({ + previous: forkStateById[docId], + document: resolved.resolvedDoc + }); + var assumedMasterDoc = assumedMasterState[docId]; + conflictWriteMeta[docId] = getMetaWriteRow(state, ensureNotFalsy(realMasterState), assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined, resolved.resolvedDoc._rev); } }); - var _temp5 = function () { - if (useWriteRowsToMeta.length > 0) { - return Promise.resolve(state.input.metaInstance.bulkWrite(useWriteRowsToMeta, 'replication-up-write-meta')).then(function () {}); // TODO what happens when we have conflicts here? - } - }(); - return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5); + })); + case 37: + if (!(conflictWriteFork.length > 0)) { + _context3.next = 48; + break; + } + hadConflictWrites = true; + state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1; + _context3.next = 42; + return state.input.forkInstance.bulkWrite(conflictWriteFork, 'replication-up-write-conflict'); + case 42: + forkWriteResult = _context3.sent; + /** + * Errors in the forkWriteResult must not be handled + * because they have been caused by a write to the forkInstance + * in between which will anyway trigger a new upstream cycle + * that will then resolved the conflict again. + */ + useMetaWrites = []; + Object.keys(forkWriteResult.success).forEach(function (docId) { + useMetaWrites.push(conflictWriteMeta[docId]); }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })["catch"](function (unhandledError) { + if (!(useMetaWrites.length > 0)) { + _context3.next = 48; + break; + } + _context3.next = 48; + return state.input.metaInstance.bulkWrite(useMetaWrites, 'replication-up-write-conflict-meta'); + case 48: + /** + * For better performance we do not await checkpoint writes, + * but to ensure order on parallel checkpoint writes, + * we have to use a queue. + */ + state.checkpointQueue = state.checkpointQueue.then(function () { + return setCheckpoint(state, 'up', useCheckpoint); + }); + return _context3.abrupt("return", hadConflictWrites); + case 50: + case "end": + return _context3.stop(); + } + }, _callee3); + })))["catch"](function (unhandledError) { state.events.error.next(unhandledError); return false; }); diff --git a/dist/es/replication-protocol/upstream.js.map b/dist/es/replication-protocol/upstream.js.map index 3e9284b111b..1745d7ff5e7 100644 --- a/dist/es/replication-protocol/upstream.js.map +++ b/dist/es/replication-protocol/upstream.js.map @@ -1 +1 @@ -{"version":3,"file":"upstream.js","names":["firstValueFrom","filter","stackCheckpoints","batchArray","ensureNotFalsy","parseRevision","PROMISE_RESOLVE_FALSE","getLastCheckpointDoc","setCheckpoint","resolveConflictError","writeDocToDocState","getAssumedMasterState","getMetaWriteRow","pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","startReplicationUpstream","upstreamInitialSync","stats","up","events","canceled","getValue","checkpointQueue","lastCheckpoint","Promise","all","promises","resolvedPromises","hadConflicts","find","r","firstSyncDone","next","initialSyncStartTime","timer","input","forkInstance","getChangedDocumentsSince","pushBatchSize","upResult","documents","length","checkpoint","push","persistToMaster","replicationHandler","streamQueue","processTasks","openTasks","sub","changeStream","pipe","eventBulk","context","downstreamBulkWriteFlag","subscribe","forkChangeStreamEmit","task","time","waitBeforePersist","unsubscribe","active","docs","taskWithTime","shift","concat","map","documentData","promise","persistenceQueue","nonPersistedFromMaster","forEach","docData","docId","primaryPath","upDocsById","useCheckpoint","docIds","Object","keys","assumedMasterState","writeRowsToMaster","writeRowsToMasterIds","writeRowsToMeta","forkStateById","isEqual","assumedMasterDoc","_rev","fullDocData","height","_meta","identifier","undefined","newDocumentState","metaDocument","isResolvedConflict","conflictHandler","realMasterState","writeRowsArray","values","conflictIds","Set","conflictsById","writeBatches","writeBatch","masterWrite","masterWriteResult","conflictDoc","id","add","hadConflictWrites","size","persistToMasterHadConflicts","conflictWriteFork","conflictWriteMeta","entries","writeToMasterRow","resolved","resolvedConflicts","output","previous","document","resolvedDoc","persistToMasterConflictWrites","bulkWrite","forkWriteResult","useMetaWrites","success","metaInstance","useWriteRowsToMeta","has","processed","unhandledError","error"],"sources":["../../../src/replication-protocol/upstream.ts"],"sourcesContent":["import { firstValueFrom, filter } from 'rxjs';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowById,\n ById,\n EventBulk,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n RxStorageChangeEvent,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport {\n batchArray,\n ensureNotFalsy,\n parseRevision,\n PROMISE_RESOLVE_FALSE\n} from '../util';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { resolveConflictError } from './conflicts';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all document changes from the fork to the master.\n * The upstream runs on two modes:\n * - For initial replication, a checkpoint-iteration is used\n * - For ongoing local writes, we just subscribe to the changeStream of the fork.\n * In contrast to the master, the fork can be assumed to never loose connection,\n * so we do not have to prepare for missed out events.\n */\nexport function startReplicationUpstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n state.streamQueue.up = state.streamQueue.up.then(() => {\n return upstreamInitialSync().then(() => {\n processTasks();\n });\n });\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n let initialSyncStartTime = -1;\n\n type Task = EventBulk, any>;\n type TaskWithTime = {\n task: Task;\n time: number;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n const sub = state.input.forkInstance.changeStream()\n .pipe(\n filter(eventBulk => eventBulk.context !== state.downstreamBulkWriteFlag)\n ).subscribe(eventBulk => {\n state.stats.up.forkChangeStreamEmit = state.stats.up.forkChangeStreamEmit + 1;\n openTasks.push({\n task: eventBulk,\n time: timer++\n });\n if (state.input.waitBeforePersist) {\n return state.input.waitBeforePersist()\n .then(() => processTasks());\n } else {\n return processTasks();\n }\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n async function upstreamInitialSync() {\n state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'up'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n initialSyncStartTime = timer++;\n const upResult = await state.input.forkInstance.getChangedDocumentsSince(\n state.input.pushBatchSize,\n lastCheckpoint\n );\n if (upResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, upResult.checkpoint]);\n\n promises.push(\n persistToMaster(\n upResult.documents,\n ensureNotFalsy(lastCheckpoint)\n )\n );\n }\n\n /**\n * If we had conflicts during the initial sync,\n * it means that we likely have new writes to the fork\n * and so we have to run the initial sync again to upastream these new writes.\n */\n const resolvedPromises = await Promise.all(promises);\n const hadConflicts = resolvedPromises.find(r => !!r);\n if (hadConflicts) {\n await upstreamInitialSync();\n } else if (!state.firstSyncDone.up.getValue()) {\n state.firstSyncDone.up.next(true);\n }\n }\n\n\n /**\n * Takes all open tasks an processes them at once.\n */\n function processTasks() {\n if (\n state.events.canceled.getValue() ||\n openTasks.length === 0\n ) {\n state.events.active.up.next(false);\n return;\n }\n state.stats.up.processTasks = state.stats.up.processTasks + 1;\n state.events.active.up.next(true);\n state.streamQueue.up = state.streamQueue.up.then(() => {\n /**\n * Merge/filter all open tasks\n */\n let docs: RxDocumentData[] = [];\n let checkpoint: CheckpointType = {} as any;\n while (openTasks.length > 0) {\n const taskWithTime = ensureNotFalsy(openTasks.shift());\n /**\n * If the task came in before the last time the initial sync fetching\n * has run, we can ignore the task because the initial sync already processed\n * these documents.\n */\n if (taskWithTime.time < initialSyncStartTime) {\n continue;\n }\n\n docs = docs.concat(\n taskWithTime.task.events.map(r => {\n return r.documentData as any;\n })\n );\n checkpoint = stackCheckpoints([checkpoint, taskWithTime.task.checkpoint]);\n }\n\n const promise = docs.length === 0 ? PROMISE_RESOLVE_FALSE : persistToMaster(\n docs,\n checkpoint\n );\n return promise.then(() => {\n if (openTasks.length === 0) {\n state.events.active.up.next(false);\n } else {\n processTasks();\n }\n });\n });\n }\n\n let persistenceQueue: Promise = PROMISE_RESOLVE_FALSE;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n /**\n * Returns true if had conflicts,\n * false if not.\n */\n function persistToMaster(\n docs: RxDocumentData[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.up.persistToMaster = state.stats.up.persistToMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n\n persistenceQueue = persistenceQueue.then(async () => {\n if (state.events.canceled.getValue()) {\n return false;\n }\n\n const upDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(upDocsById);\n if (docIds.length === 0) {\n return false;\n }\n\n const assumedMasterState = await getAssumedMasterState(\n state,\n docIds\n );\n\n const writeRowsToMaster: ById> = {};\n const writeRowsToMasterIds: string[] = [];\n const writeRowsToMeta: BulkWriteRowById = {};\n const forkStateById: ById> = {};\n\n await Promise.all(\n docIds.map(async (docId) => {\n const fullDocData: RxDocumentData = upDocsById[docId];\n forkStateById[docId] = fullDocData;\n const docData: WithDeleted = writeDocToDocState(fullDocData);\n const assumedMasterDoc = assumedMasterState[docId];\n\n /**\n * If the master state is equal to the\n * fork state, we can assume that the document state is already\n * replicated.\n */\n if (\n (\n assumedMasterDoc &&\n // if the isResolvedConflict is correct, we do not have to compare the documents.\n assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev\n &&\n (await state.input.conflictHandler({\n realMasterState: assumedMasterDoc.docData,\n newDocumentState: docData\n }, 'upstream-check-if-equal')).isEqual\n )\n ||\n /**\n * If the master works with _rev fields,\n * we use that to check if our current doc state\n * is different from the assumedMasterDoc.\n */\n (\n assumedMasterDoc &&\n (assumedMasterDoc.docData as any)._rev &&\n parseRevision(fullDocData._rev).height === fullDocData._meta[state.input.identifier]\n )\n ) {\n return;\n }\n\n writeRowsToMasterIds.push(docId);\n\n writeRowsToMaster[docId] = {\n assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined,\n newDocumentState: docData\n };\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n docData,\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined\n );\n })\n );\n\n if (writeRowsToMasterIds.length === 0) {\n return false;\n }\n\n\n const writeRowsArray = Object.values(writeRowsToMaster);\n const conflictIds: Set = new Set();\n const conflictsById: ById> = {};\n\n /**\n * To always respect the push.batchSize,\n * we have to split the write rows into batches\n * to ensure that replicationHandler.masterWrite() is never\n * called with more documents than what the batchSize limits.\n */\n const writeBatches = batchArray(writeRowsArray, state.input.pushBatchSize);\n await Promise.all(\n writeBatches.map(async (writeBatch) => {\n const masterWriteResult = await replicationHandler.masterWrite(writeBatch);\n masterWriteResult.forEach(conflictDoc => {\n const id = (conflictDoc as any)[state.primaryPath];\n conflictIds.add(id);\n conflictsById[id] = conflictDoc;\n });\n })\n );\n\n\n const useWriteRowsToMeta: BulkWriteRow[] = [];\n\n\n writeRowsToMasterIds.forEach(docId => {\n if (!conflictIds.has(docId)) {\n state.events.processed.up.next(writeRowsToMaster[docId]);\n useWriteRowsToMeta.push(writeRowsToMeta[docId]);\n }\n });\n\n if (useWriteRowsToMeta.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useWriteRowsToMeta,\n 'replication-up-write-meta'\n );\n // TODO what happens when we have conflicts here?\n }\n\n /**\n * Resolve conflicts by writing a new document\n * state to the fork instance and the 'real' master state\n * to the meta instance.\n * Non-409 errors will be detected by resolveConflictError()\n */\n let hadConflictWrites = false;\n if (conflictIds.size > 0) {\n state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1;\n const conflictWriteFork: BulkWriteRow[] = [];\n const conflictWriteMeta: BulkWriteRowById = {};\n await Promise.all(\n Object\n .entries(conflictsById)\n .map(([docId, realMasterState]) => {\n const writeToMasterRow = writeRowsToMaster[docId];\n const input = {\n newDocumentState: writeToMasterRow.newDocumentState,\n assumedMasterState: writeToMasterRow.assumedMasterState,\n realMasterState\n };\n return resolveConflictError(\n state,\n input,\n forkStateById[docId]\n ).then(resolved => {\n if (resolved) {\n state.events.resolvedConflicts.next({\n input,\n output: resolved.output\n });\n conflictWriteFork.push({\n previous: forkStateById[docId],\n document: resolved.resolvedDoc\n });\n const assumedMasterDoc = assumedMasterState[docId];\n conflictWriteMeta[docId] = getMetaWriteRow(\n state,\n ensureNotFalsy(realMasterState),\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined,\n resolved.resolvedDoc._rev\n );\n }\n });\n })\n );\n\n if (conflictWriteFork.length > 0) {\n hadConflictWrites = true;\n\n state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1;\n const forkWriteResult = await state.input.forkInstance.bulkWrite(\n conflictWriteFork,\n 'replication-up-write-conflict'\n );\n /**\n * Errors in the forkWriteResult must not be handled\n * because they have been caused by a write to the forkInstance\n * in between which will anyway trigger a new upstream cycle\n * that will then resolved the conflict again.\n */\n const useMetaWrites: BulkWriteRow[] = [];\n Object\n .keys(forkWriteResult.success)\n .forEach((docId) => {\n useMetaWrites.push(\n conflictWriteMeta[docId]\n );\n });\n if (useMetaWrites.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useMetaWrites,\n 'replication-up-write-conflict-meta'\n );\n }\n // TODO what to do with conflicts while writing to the metaInstance?\n }\n }\n\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'up',\n useCheckpoint\n ));\n\n return hadConflictWrites;\n }).catch(unhandledError => {\n state.events.error.next(unhandledError);\n return false;\n });\n\n return persistenceQueue;\n }\n}\n\n"],"mappings":"AAAA,SAASA,cAAc,EAAEC,MAAM,QAAQ,MAAM;AAC7C,SAASC,gBAAgB,QAAQ,sBAAsB;AAavD,SACIC,UAAU,EACVC,cAAc,EACdC,aAAa,EACbC,qBAAqB,QAClB,SAAS;AAChB,SACIC,oBAAoB,EACpBC,aAAa,QACV,cAAc;AACrB,SAASC,oBAAoB,QAAQ,aAAa;AAClD,SAASC,kBAAkB,QAAQ,UAAU;AAC7C,SACIC,qBAAqB,EACrBC,eAAe,QACZ,iBAAiB;;AAExB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,iBAAiBC,I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AK,EAAK;8BAChBqD,aAAa,CAACnF,IAAI,CACduE,iBAAiB,CAACzC,KAAK,CAAC,CAC3B;4BACL,CAAC,CAAC;4BAAC;8BAAA,IACHqD,aAAa,CAACrF,MAAM,GAAG,CAAC;gCAAA,uBAClBpD,KAAK,CAAC8C,KAAK,CAAC6F,YAAY,CAACJ,SAAS,CACpCE,aAAa,EACb,oCAAoC,CACvC;8BAAA;4BAAA;4BAAA;0BAAA,IAEL;wBAAA;sBAAA;sBAAA;oBAAA;kBAAA;gBAAA;gBAAA;cAAA;cA7FR,IAAMG,kBAA4D,GAAG,EAAE;cAGvE/C,oBAAoB,CAACX,OAAO,CAAC,UAAAE,KAAK,EAAI;gBAClC,IAAI,CAAC2B,WAAW,CAAC8B,GAAG,CAACzD,KAAK,CAAC,EAAE;kBACzBpF,KAAK,CAAC8B,MAAM,CAACgH,SAAS,CAACjH,EAAE,CAACc,IAAI,CAACiD,iBAAiB,CAACR,KAAK,CAAC,CAAC;kBACxDwD,kBAAkB,CAACtF,IAAI,CAACwC,eAAe,CAACV,KAAK,CAAC,CAAC;gBACnD;cACJ,CAAC,CAAC;cAAC;gBAAA,IAECwD,kBAAkB,CAACxF,MAAM,GAAG,CAAC;kBAAA,uBACvBpD,KAAK,CAAC8C,KAAK,CAAC6F,YAAY,CAACJ,SAAS,CACpCK,kBAAkB,EAClB,2BAA2B,CAC9B,wBACD;gBAAA;cAAA;cAAA;YAAA;UAAA;QAAA;MA8FR,CAAC;QAAA;MAAA;IAAA,EAAC,SAAM,CAAC,UAAAG,cAAc,EAAI;MACvB/I,KAAK,CAAC8B,MAAM,CAACkH,KAAK,CAACrG,IAAI,CAACoG,cAAc,CAAC;MACvC,OAAO,KAAK;IAChB,CAAC,CAAC;IAEF,OAAO/D,gBAAgB;EAC3B;AACJ"} \ No newline at end of file +{"version":3,"file":"upstream.js","names":["firstValueFrom","filter","stackCheckpoints","batchArray","ensureNotFalsy","parseRevision","PROMISE_RESOLVE_FALSE","getLastCheckpointDoc","setCheckpoint","resolveConflictError","writeDocToDocState","getAssumedMasterState","getMetaWriteRow","startReplicationUpstream","state","replicationHandler","input","streamQueue","up","then","upstreamInitialSync","processTasks","timer","initialSyncStartTime","openTasks","sub","forkInstance","changeStream","pipe","eventBulk","context","downstreamBulkWriteFlag","subscribe","stats","forkChangeStreamEmit","push","task","time","waitBeforePersist","events","canceled","unsubscribe","getValue","checkpointQueue","lastCheckpoint","promises","getChangedDocumentsSince","pushBatchSize","upResult","documents","length","checkpoint","persistToMaster","Promise","all","resolvedPromises","hadConflicts","find","r","firstSyncDone","next","active","docs","taskWithTime","shift","concat","map","documentData","promise","persistenceQueue","nonPersistedFromMaster","forEach","docData","docId","primaryPath","upDocsById","useCheckpoint","docIds","Object","keys","assumedMasterState","writeRowsToMaster","writeRowsToMasterIds","writeRowsToMeta","forkStateById","fullDocData","assumedMasterDoc","metaDocument","isResolvedConflict","_rev","conflictHandler","realMasterState","newDocumentState","isEqual","height","_meta","identifier","undefined","writeRowsArray","values","conflictIds","Set","conflictsById","writeBatches","writeBatch","masterWrite","masterWriteResult","conflictDoc","id","add","useWriteRowsToMeta","has","processed","metaInstance","bulkWrite","hadConflictWrites","size","persistToMasterHadConflicts","conflictWriteFork","conflictWriteMeta","entries","writeToMasterRow","resolved","resolvedConflicts","output","previous","document","resolvedDoc","persistToMasterConflictWrites","forkWriteResult","useMetaWrites","success","unhandledError","error"],"sources":["../../../src/replication-protocol/upstream.ts"],"sourcesContent":["import { firstValueFrom, filter } from 'rxjs';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowById,\n ById,\n EventBulk,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n RxStorageChangeEvent,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport {\n batchArray,\n ensureNotFalsy,\n parseRevision,\n PROMISE_RESOLVE_FALSE\n} from '../plugins/utils';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { resolveConflictError } from './conflicts';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all document changes from the fork to the master.\n * The upstream runs on two modes:\n * - For initial replication, a checkpoint-iteration is used\n * - For ongoing local writes, we just subscribe to the changeStream of the fork.\n * In contrast to the master, the fork can be assumed to never loose connection,\n * so we do not have to prepare for missed out events.\n */\nexport function startReplicationUpstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n state.streamQueue.up = state.streamQueue.up.then(() => {\n return upstreamInitialSync().then(() => {\n processTasks();\n });\n });\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n let initialSyncStartTime = -1;\n\n type Task = EventBulk, any>;\n type TaskWithTime = {\n task: Task;\n time: number;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n const sub = state.input.forkInstance.changeStream()\n .pipe(\n filter(eventBulk => eventBulk.context !== state.downstreamBulkWriteFlag)\n ).subscribe(eventBulk => {\n state.stats.up.forkChangeStreamEmit = state.stats.up.forkChangeStreamEmit + 1;\n openTasks.push({\n task: eventBulk,\n time: timer++\n });\n if (state.input.waitBeforePersist) {\n return state.input.waitBeforePersist()\n .then(() => processTasks());\n } else {\n return processTasks();\n }\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n async function upstreamInitialSync() {\n state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'up'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n initialSyncStartTime = timer++;\n const upResult = await state.input.forkInstance.getChangedDocumentsSince(\n state.input.pushBatchSize,\n lastCheckpoint\n );\n if (upResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, upResult.checkpoint]);\n\n promises.push(\n persistToMaster(\n upResult.documents,\n ensureNotFalsy(lastCheckpoint)\n )\n );\n }\n\n /**\n * If we had conflicts during the initial sync,\n * it means that we likely have new writes to the fork\n * and so we have to run the initial sync again to upstream these new writes.\n */\n const resolvedPromises = await Promise.all(promises);\n const hadConflicts = resolvedPromises.find(r => !!r);\n if (hadConflicts) {\n await upstreamInitialSync();\n } else if (!state.firstSyncDone.up.getValue()) {\n state.firstSyncDone.up.next(true);\n }\n }\n\n\n /**\n * Takes all open tasks an processes them at once.\n */\n function processTasks() {\n if (\n state.events.canceled.getValue() ||\n openTasks.length === 0\n ) {\n state.events.active.up.next(false);\n return;\n }\n state.stats.up.processTasks = state.stats.up.processTasks + 1;\n state.events.active.up.next(true);\n state.streamQueue.up = state.streamQueue.up.then(() => {\n /**\n * Merge/filter all open tasks\n */\n let docs: RxDocumentData[] = [];\n let checkpoint: CheckpointType = {} as any;\n while (openTasks.length > 0) {\n const taskWithTime = ensureNotFalsy(openTasks.shift());\n /**\n * If the task came in before the last time the initial sync fetching\n * has run, we can ignore the task because the initial sync already processed\n * these documents.\n */\n if (taskWithTime.time < initialSyncStartTime) {\n continue;\n }\n\n docs = docs.concat(\n taskWithTime.task.events.map(r => {\n return r.documentData as any;\n })\n );\n checkpoint = stackCheckpoints([checkpoint, taskWithTime.task.checkpoint]);\n }\n\n const promise = docs.length === 0 ? PROMISE_RESOLVE_FALSE : persistToMaster(\n docs,\n checkpoint\n );\n return promise.then(() => {\n if (openTasks.length === 0) {\n state.events.active.up.next(false);\n } else {\n processTasks();\n }\n });\n });\n }\n\n let persistenceQueue: Promise = PROMISE_RESOLVE_FALSE;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n /**\n * Returns true if had conflicts,\n * false if not.\n */\n function persistToMaster(\n docs: RxDocumentData[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.up.persistToMaster = state.stats.up.persistToMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n\n persistenceQueue = persistenceQueue.then(async () => {\n if (state.events.canceled.getValue()) {\n return false;\n }\n\n const upDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(upDocsById);\n if (docIds.length === 0) {\n return false;\n }\n\n const assumedMasterState = await getAssumedMasterState(\n state,\n docIds\n );\n\n const writeRowsToMaster: ById> = {};\n const writeRowsToMasterIds: string[] = [];\n const writeRowsToMeta: BulkWriteRowById = {};\n const forkStateById: ById> = {};\n\n await Promise.all(\n docIds.map(async (docId) => {\n const fullDocData: RxDocumentData = upDocsById[docId];\n forkStateById[docId] = fullDocData;\n const docData: WithDeleted = writeDocToDocState(fullDocData);\n const assumedMasterDoc = assumedMasterState[docId];\n\n /**\n * If the master state is equal to the\n * fork state, we can assume that the document state is already\n * replicated.\n */\n if (\n (\n assumedMasterDoc &&\n // if the isResolvedConflict is correct, we do not have to compare the documents.\n assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev\n &&\n (await state.input.conflictHandler({\n realMasterState: assumedMasterDoc.docData,\n newDocumentState: docData\n }, 'upstream-check-if-equal')).isEqual\n )\n ||\n /**\n * If the master works with _rev fields,\n * we use that to check if our current doc state\n * is different from the assumedMasterDoc.\n */\n (\n assumedMasterDoc &&\n (assumedMasterDoc.docData as any)._rev &&\n parseRevision(fullDocData._rev).height === fullDocData._meta[state.input.identifier]\n )\n ) {\n return;\n }\n\n writeRowsToMasterIds.push(docId);\n\n writeRowsToMaster[docId] = {\n assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined,\n newDocumentState: docData\n };\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n docData,\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined\n );\n })\n );\n\n if (writeRowsToMasterIds.length === 0) {\n return false;\n }\n\n\n const writeRowsArray = Object.values(writeRowsToMaster);\n const conflictIds: Set = new Set();\n const conflictsById: ById> = {};\n\n /**\n * To always respect the push.batchSize,\n * we have to split the write rows into batches\n * to ensure that replicationHandler.masterWrite() is never\n * called with more documents than what the batchSize limits.\n */\n const writeBatches = batchArray(writeRowsArray, state.input.pushBatchSize);\n await Promise.all(\n writeBatches.map(async (writeBatch) => {\n const masterWriteResult = await replicationHandler.masterWrite(writeBatch);\n masterWriteResult.forEach(conflictDoc => {\n const id = (conflictDoc as any)[state.primaryPath];\n conflictIds.add(id);\n conflictsById[id] = conflictDoc;\n });\n })\n );\n\n\n const useWriteRowsToMeta: BulkWriteRow[] = [];\n\n\n writeRowsToMasterIds.forEach(docId => {\n if (!conflictIds.has(docId)) {\n state.events.processed.up.next(writeRowsToMaster[docId]);\n useWriteRowsToMeta.push(writeRowsToMeta[docId]);\n }\n });\n\n if (useWriteRowsToMeta.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useWriteRowsToMeta,\n 'replication-up-write-meta'\n );\n // TODO what happens when we have conflicts here?\n }\n\n /**\n * Resolve conflicts by writing a new document\n * state to the fork instance and the 'real' master state\n * to the meta instance.\n * Non-409 errors will be detected by resolveConflictError()\n */\n let hadConflictWrites = false;\n if (conflictIds.size > 0) {\n state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1;\n const conflictWriteFork: BulkWriteRow[] = [];\n const conflictWriteMeta: BulkWriteRowById = {};\n await Promise.all(\n Object\n .entries(conflictsById)\n .map(([docId, realMasterState]) => {\n const writeToMasterRow = writeRowsToMaster[docId];\n const input = {\n newDocumentState: writeToMasterRow.newDocumentState,\n assumedMasterState: writeToMasterRow.assumedMasterState,\n realMasterState\n };\n return resolveConflictError(\n state,\n input,\n forkStateById[docId]\n ).then(resolved => {\n if (resolved) {\n state.events.resolvedConflicts.next({\n input,\n output: resolved.output\n });\n conflictWriteFork.push({\n previous: forkStateById[docId],\n document: resolved.resolvedDoc\n });\n const assumedMasterDoc = assumedMasterState[docId];\n conflictWriteMeta[docId] = getMetaWriteRow(\n state,\n ensureNotFalsy(realMasterState),\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined,\n resolved.resolvedDoc._rev\n );\n }\n });\n })\n );\n\n if (conflictWriteFork.length > 0) {\n hadConflictWrites = true;\n\n state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1;\n const forkWriteResult = await state.input.forkInstance.bulkWrite(\n conflictWriteFork,\n 'replication-up-write-conflict'\n );\n /**\n * Errors in the forkWriteResult must not be handled\n * because they have been caused by a write to the forkInstance\n * in between which will anyway trigger a new upstream cycle\n * that will then resolved the conflict again.\n */\n const useMetaWrites: BulkWriteRow[] = [];\n Object\n .keys(forkWriteResult.success)\n .forEach((docId) => {\n useMetaWrites.push(\n conflictWriteMeta[docId]\n );\n });\n if (useMetaWrites.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useMetaWrites,\n 'replication-up-write-conflict-meta'\n );\n }\n // TODO what to do with conflicts while writing to the metaInstance?\n }\n }\n\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'up',\n useCheckpoint\n ));\n\n return hadConflictWrites;\n }).catch(unhandledError => {\n state.events.error.next(unhandledError);\n return false;\n });\n\n return persistenceQueue;\n }\n}\n\n"],"mappings":";;AAAA,SAASA,cAAc,EAAEC,MAAM,QAAQ,MAAM;AAC7C,SAASC,gBAAgB,QAAQ,sBAAsB;AAavD,SACIC,UAAU,EACVC,cAAc,EACdC,aAAa,EACbC,qBAAqB,QAClB,kBAAkB;AACzB,SACIC,oBAAoB,EACpBC,aAAa,QACV,cAAc;AACrB,SAASC,oBAAoB,QAAQ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AM,CAAC,UAAAiB,cAAc,EAAI;MACvBtH,KAAK,CAACyB,MAAM,CAAC8F,KAAK,CAACzE,IAAI,CAACwE,cAAc,CAAC;MACvC,OAAO,KAAK;IAChB,CAAC,CAAC;IAEF,OAAO/D,gBAAgB;EAC3B;AACJ"} \ No newline at end of file diff --git a/dist/es/rx-collection-helper.js b/dist/es/rx-collection-helper.js index e702009e199..d058d62186d 100644 --- a/dist/es/rx-collection-helper.js +++ b/dist/es/rx-collection-helper.js @@ -1,4 +1,6 @@ -import { createRevision, getDefaultRevision, getDefaultRxDocumentMeta, now } from './util'; +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { createRevision, getDefaultRevision, getDefaultRxDocumentMeta, now } from './plugins/utils'; import { fillPrimaryKey } from './rx-schema-helper'; import { runAsyncPluginHooks } from './hooks'; import { getAllCollectionDocuments } from './rx-database-internal-store'; @@ -8,112 +10,6 @@ import { flatCloneDocWithMeta } from './rx-storage-helper'; * fills in the default data. * This also clones the data. */ - -/** - * Removes the main storage of the collection - * and all connected storages like the ones from the replication meta etc. - */ -export var removeCollectionStorages = function removeCollectionStorages(storage, databaseInternalStorage, databaseInstanceToken, databaseName, collectionName, -/** - * If no hash function is provided, - * we assume that the whole internal store is removed anyway - * so we do not have to delete the meta documents. - */ -hashFunction) { - try { - return Promise.resolve(getAllCollectionDocuments(storage.statics, databaseInternalStorage)).then(function (allCollectionMetaDocs) { - var relevantCollectionMetaDocs = allCollectionMetaDocs.filter(function (metaDoc) { - return metaDoc.data.name === collectionName; - }); - var removeStorages = []; - relevantCollectionMetaDocs.forEach(function (metaDoc) { - removeStorages.push({ - collectionName: metaDoc.data.name, - schema: metaDoc.data.schema, - isCollection: true - }); - metaDoc.data.connectedStorages.forEach(function (row) { - return removeStorages.push({ - collectionName: row.collectionName, - isCollection: false, - schema: row.schema - }); - }); - }); - - // ensure uniqueness - var alreadyAdded = new Set(); - removeStorages = removeStorages.filter(function (row) { - var key = row.collectionName + '||' + row.schema.version; - if (alreadyAdded.has(key)) { - return false; - } else { - alreadyAdded.add(key); - return true; - } - }); - - // remove all the storages - return Promise.resolve(Promise.all(removeStorages.map(function (row) { - try { - return Promise.resolve(storage.createStorageInstance({ - collectionName: row.collectionName, - databaseInstanceToken: databaseInstanceToken, - databaseName: databaseName, - multiInstance: false, - options: {}, - schema: row.schema - })).then(function (storageInstance) { - return Promise.resolve(storageInstance.remove()).then(function () { - var _temp2 = function () { - if (row.isCollection) { - return Promise.resolve(runAsyncPluginHooks('postRemoveRxCollection', { - storage: storage, - databaseName: databaseName, - collectionName: collectionName - })).then(function () {}); - } - }(); - if (_temp2 && _temp2.then) return _temp2.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp = function () { - if (hashFunction) { - var writeRows = relevantCollectionMetaDocs.map(function (doc) { - var writeDoc = flatCloneDocWithMeta(doc); - writeDoc._deleted = true; - writeDoc._meta.lwt = now(); - writeDoc._rev = createRevision(hashFunction, writeDoc, doc); - return { - previous: doc, - document: writeDoc - }; - }); - return Promise.resolve(databaseInternalStorage.bulkWrite(writeRows, 'rx-database-remove-collection-all')).then(function () {}); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); // remove the meta documents - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Creates the storage instances that are used internally in the collection - */ -export var createRxCollectionStorageInstance = function createRxCollectionStorageInstance(rxDatabase, storageInstanceCreationParams) { - try { - storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance; - return Promise.resolve(rxDatabase.storage.createStorageInstance(storageInstanceCreationParams)); - } catch (e) { - return Promise.reject(e); - } -}; export function fillObjectDataBeforeInsert(schema, data) { var useJson = schema.fillObjectWithDefaults(data); useJson = fillPrimaryKey(schema.primaryPath, schema.jsonSchema, useJson); @@ -129,4 +25,153 @@ export function fillObjectDataBeforeInsert(schema, data) { } return useJson; } + +/** + * Creates the storage instances that are used internally in the collection + */ +export function createRxCollectionStorageInstance(_x, _x2) { + return _createRxCollectionStorageInstance.apply(this, arguments); +} + +/** + * Removes the main storage of the collection + * and all connected storages like the ones from the replication meta etc. + */ +function _createRxCollectionStorageInstance() { + _createRxCollectionStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(rxDatabase, storageInstanceCreationParams) { + var storageInstance; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance; + _context.next = 3; + return rxDatabase.storage.createStorageInstance(storageInstanceCreationParams); + case 3: + storageInstance = _context.sent; + return _context.abrupt("return", storageInstance); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _createRxCollectionStorageInstance.apply(this, arguments); +} +export function removeCollectionStorages(_x3, _x4, _x5, _x6, _x7, _x8) { + return _removeCollectionStorages.apply(this, arguments); +} +function _removeCollectionStorages() { + _removeCollectionStorages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(storage, databaseInternalStorage, databaseInstanceToken, databaseName, collectionName, + /** + * If no hash function is provided, + * we assume that the whole internal store is removed anyway + * so we do not have to delete the meta documents. + */ + hashFunction) { + var allCollectionMetaDocs, relevantCollectionMetaDocs, removeStorages, alreadyAdded, writeRows; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getAllCollectionDocuments(storage.statics, databaseInternalStorage); + case 2: + allCollectionMetaDocs = _context3.sent; + relevantCollectionMetaDocs = allCollectionMetaDocs.filter(function (metaDoc) { + return metaDoc.data.name === collectionName; + }); + removeStorages = []; + relevantCollectionMetaDocs.forEach(function (metaDoc) { + removeStorages.push({ + collectionName: metaDoc.data.name, + schema: metaDoc.data.schema, + isCollection: true + }); + metaDoc.data.connectedStorages.forEach(function (row) { + return removeStorages.push({ + collectionName: row.collectionName, + isCollection: false, + schema: row.schema + }); + }); + }); + + // ensure uniqueness + alreadyAdded = new Set(); + removeStorages = removeStorages.filter(function (row) { + var key = row.collectionName + '||' + row.schema.version; + if (alreadyAdded.has(key)) { + return false; + } else { + alreadyAdded.add(key); + return true; + } + }); + + // remove all the storages + _context3.next = 10; + return Promise.all(removeStorages.map( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(row) { + var storageInstance; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return storage.createStorageInstance({ + collectionName: row.collectionName, + databaseInstanceToken: databaseInstanceToken, + databaseName: databaseName, + multiInstance: false, + options: {}, + schema: row.schema + }); + case 2: + storageInstance = _context2.sent; + _context2.next = 5; + return storageInstance.remove(); + case 5: + if (!row.isCollection) { + _context2.next = 8; + break; + } + _context2.next = 8; + return runAsyncPluginHooks('postRemoveRxCollection', { + storage: storage, + databaseName: databaseName, + collectionName: collectionName + }); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x9) { + return _ref.apply(this, arguments); + }; + }())); + case 10: + if (!hashFunction) { + _context3.next = 14; + break; + } + writeRows = relevantCollectionMetaDocs.map(function (doc) { + var writeDoc = flatCloneDocWithMeta(doc); + writeDoc._deleted = true; + writeDoc._meta.lwt = now(); + writeDoc._rev = createRevision(databaseInstanceToken, doc); + return { + previous: doc, + document: writeDoc + }; + }); + _context3.next = 14; + return databaseInternalStorage.bulkWrite(writeRows, 'rx-database-remove-collection-all'); + case 14: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _removeCollectionStorages.apply(this, arguments); +} //# sourceMappingURL=rx-collection-helper.js.map \ No newline at end of file diff --git a/dist/es/rx-collection-helper.js.map b/dist/es/rx-collection-helper.js.map index eb373eff371..9ef807c662b 100644 --- a/dist/es/rx-collection-helper.js.map +++ b/dist/es/rx-collection-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection-helper.js","names":["createRevision","getDefaultRevision","getDefaultRxDocumentMeta","now","fillPrimaryKey","runAsyncPluginHooks","getAllCollectionDocuments","flatCloneDocWithMeta","removeCollectionStorages","storage","databaseInternalStorage","databaseInstanceToken","databaseName","collectionName","hashFunction","statics","allCollectionMetaDocs","relevantCollectionMetaDocs","filter","metaDoc","data","name","removeStorages","forEach","push","schema","isCollection","connectedStorages","row","alreadyAdded","Set","key","version","has","add","Promise","all","map","createStorageInstance","multiInstance","options","storageInstance","remove","writeRows","doc","writeDoc","_deleted","_meta","lwt","_rev","previous","document","bulkWrite","createRxCollectionStorageInstance","rxDatabase","storageInstanceCreationParams","fillObjectDataBeforeInsert","useJson","fillObjectWithDefaults","primaryPath","jsonSchema","hasOwnProperty","_attachments"],"sources":["../../src/rx-collection-helper.ts"],"sourcesContent":["import type {\n HashFunction,\n InternalStoreDocType,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\nimport {\n createRevision,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now\n} from './util';\nimport {\n fillPrimaryKey\n} from './rx-schema-helper';\nimport type { RxSchema } from './rx-schema';\nimport { runAsyncPluginHooks } from './hooks';\nimport { getAllCollectionDocuments } from './rx-database-internal-store';\nimport { flatCloneDocWithMeta } from './rx-storage-helper';\n\n/**\n * fills in the default data.\n * This also clones the data.\n */\nexport function fillObjectDataBeforeInsert(\n schema: RxSchema,\n data: Partial> | any\n): RxDocumentData {\n let useJson = schema.fillObjectWithDefaults(data);\n useJson = fillPrimaryKey(\n schema.primaryPath,\n schema.jsonSchema,\n useJson\n );\n useJson._meta = getDefaultRxDocumentMeta();\n if (!useJson.hasOwnProperty('_deleted')) {\n useJson._deleted = false;\n }\n if (!useJson.hasOwnProperty('_attachments')) {\n useJson._attachments = {};\n }\n if (!useJson.hasOwnProperty('_rev')) {\n useJson._rev = getDefaultRevision();\n }\n return useJson;\n}\n\n/**\n * Creates the storage instances that are used internally in the collection\n */\nexport async function createRxCollectionStorageInstance(\n rxDatabase: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstanceCreationParams: RxStorageInstanceCreationParams\n): Promise> {\n storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance;\n const storageInstance = await rxDatabase.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n return storageInstance;\n}\n\n/**\n * Removes the main storage of the collection\n * and all connected storages like the ones from the replication meta etc.\n */\nexport async function removeCollectionStorages(\n storage: RxStorage,\n databaseInternalStorage: RxStorageInstance, any, any>,\n databaseInstanceToken: string,\n databaseName: string,\n collectionName: string,\n /**\n * If no hash function is provided,\n * we assume that the whole internal store is removed anyway\n * so we do not have to delete the meta documents.\n */\n hashFunction?: HashFunction,\n) {\n const allCollectionMetaDocs = await getAllCollectionDocuments(\n storage.statics,\n databaseInternalStorage\n );\n const relevantCollectionMetaDocs = allCollectionMetaDocs\n .filter(metaDoc => metaDoc.data.name === collectionName);\n\n let removeStorages: {\n collectionName: string;\n schema: RxJsonSchema;\n isCollection: boolean;\n }[] = [];\n relevantCollectionMetaDocs.forEach(metaDoc => {\n removeStorages.push({\n collectionName: metaDoc.data.name,\n schema: metaDoc.data.schema,\n isCollection: true\n });\n metaDoc.data.connectedStorages.forEach(row => removeStorages.push({\n collectionName: row.collectionName,\n isCollection: false,\n schema: row.schema\n }));\n });\n\n // ensure uniqueness\n const alreadyAdded = new Set();\n removeStorages = removeStorages.filter(row => {\n const key = row.collectionName + '||' + row.schema.version;\n if (alreadyAdded.has(key)) {\n return false;\n } else {\n alreadyAdded.add(key);\n return true;\n }\n });\n\n // remove all the storages\n await Promise.all(\n removeStorages\n .map(async (row) => {\n const storageInstance = await storage.createStorageInstance({\n collectionName: row.collectionName,\n databaseInstanceToken,\n databaseName,\n multiInstance: false,\n options: {},\n schema: row.schema\n });\n await storageInstance.remove();\n if (row.isCollection) {\n await runAsyncPluginHooks('postRemoveRxCollection', {\n storage,\n databaseName: databaseName,\n collectionName\n });\n }\n })\n );\n\n // remove the meta documents\n if (hashFunction) {\n const writeRows = relevantCollectionMetaDocs.map(doc => {\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n writeDoc._meta.lwt = now();\n writeDoc._rev = createRevision(\n hashFunction,\n writeDoc,\n doc\n );\n return {\n previous: doc,\n document: writeDoc\n };\n });\n await databaseInternalStorage.bulkWrite(\n writeRows,\n 'rx-database-remove-collection-all'\n );\n }\n}\n"],"mappings":"AAUA,SACIA,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,GAAG,QACA,QAAQ;AACf,SACIC,cAAc,QACX,oBAAoB;AAE3B,SAASC,mBAAmB,QAAQ,SAAS;AAC7C,SAASC,yBAAyB,QAAQ,8BAA8B;AACxE,SAASC,oBAAoB,QAAQ,qBAAqB;;AAE1D;AACA;AACA;AACA;;AAsCA;AACA;AACA;AACA;AACA,WAAsBC,wBAAwB,YAAxBA,wBAAwB,CAC1CC,OAA4B,EAC5BC,uBAA+E,EAC/EC,qBAA6B,EAC7BC,YAAoB,EACpBC,cAAsB;AACtB;AACJ;AACA;AACA;AACA;AACIC,YAA2B;EAAA,IAC7B;IAAA,uBACsCR,yBAAyB,CACzDG,OAAO,CAACM,OAAO,EACfL,uBAAuB,CAC1B,iBAHKM,qBAAqB;MAI3B,IAAMC,0BAA0B,GAAGD,qBAAqB,CACnDE,MAAM,CAAC,UAAAC,OAAO;QAAA,OAAIA,OAAO,CAACC,IAAI,CAACC,IAAI,KAAKR,cAAc;MAAA,EAAC;MAE5D,IAAIS,cAID,GAAG,EAAE;MACRL,0BAA0B,CAACM,OAAO,CAAC,UAAAJ,OAAO,EAAI;QAC1CG,cAAc,CAACE,IAAI,CAAC;UAChBX,cAAc,EAAEM,OAAO,CAACC,IAAI,CAACC,IAAI;UACjCI,MAAM,EAAEN,OAAO,CAACC,IAAI,CAACK,MAAM;UAC3BC,YAAY,EAAE;QAClB,CAAC,CAAC;QACFP,OAAO,CAACC,IAAI,CAACO,iBA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,KAAK;EAC5B;EACA,IAAI,CAACW,OAAO,CAACI,cAAc,CAAC,cAAc,CAAC,EAAE;IACzCJ,OAAO,CAACK,YAAY,GAAG,CAAC,CAAC;EAC7B;EACA,IAAI,CAACL,OAAO,CAACI,cAAc,CAAC,MAAM,CAAC,EAAE;IACjCJ,OAAO,CAACR,IAAI,GAAGhD,kBAAkB,EAAE;EACvC;EACA,OAAOwD,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"rx-collection-helper.js","names":["createRevision","getDefaultRevision","getDefaultRxDocumentMeta","now","fillPrimaryKey","runAsyncPluginHooks","getAllCollectionDocuments","flatCloneDocWithMeta","fillObjectDataBeforeInsert","schema","data","useJson","fillObjectWithDefaults","primaryPath","jsonSchema","_meta","hasOwnProperty","_deleted","_attachments","_rev","createRxCollectionStorageInstance","rxDatabase","storageInstanceCreationParams","multiInstance","storage","createStorageInstance","storageInstance","removeCollectionStorages","databaseInternalStorage","databaseInstanceToken","databaseName","collectionName","hashFunction","statics","allCollectionMetaDocs","relevantCollectionMetaDocs","filter","metaDoc","name","removeStorages","forEach","push","isCollection","connectedStorages","row","alreadyAdded","Set","key","version","has","add","Promise","all","map","options","remove","writeRows","doc","writeDoc","lwt","previous","document","bulkWrite"],"sources":["../../src/rx-collection-helper.ts"],"sourcesContent":["import type {\n HashFunction,\n InternalStoreDocType,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\nimport {\n createRevision,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now\n} from './plugins/utils';\nimport {\n fillPrimaryKey\n} from './rx-schema-helper';\nimport type { RxSchema } from './rx-schema';\nimport { runAsyncPluginHooks } from './hooks';\nimport { getAllCollectionDocuments } from './rx-database-internal-store';\nimport { flatCloneDocWithMeta } from './rx-storage-helper';\n\n/**\n * fills in the default data.\n * This also clones the data.\n */\nexport function fillObjectDataBeforeInsert(\n schema: RxSchema,\n data: Partial> | any\n): RxDocumentData {\n let useJson = schema.fillObjectWithDefaults(data);\n useJson = fillPrimaryKey(\n schema.primaryPath,\n schema.jsonSchema,\n useJson\n );\n useJson._meta = getDefaultRxDocumentMeta();\n if (!useJson.hasOwnProperty('_deleted')) {\n useJson._deleted = false;\n }\n if (!useJson.hasOwnProperty('_attachments')) {\n useJson._attachments = {};\n }\n if (!useJson.hasOwnProperty('_rev')) {\n useJson._rev = getDefaultRevision();\n }\n return useJson;\n}\n\n/**\n * Creates the storage instances that are used internally in the collection\n */\nexport async function createRxCollectionStorageInstance(\n rxDatabase: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstanceCreationParams: RxStorageInstanceCreationParams\n): Promise> {\n storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance;\n const storageInstance = await rxDatabase.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n return storageInstance;\n}\n\n/**\n * Removes the main storage of the collection\n * and all connected storages like the ones from the replication meta etc.\n */\nexport async function removeCollectionStorages(\n storage: RxStorage,\n databaseInternalStorage: RxStorageInstance, any, any>,\n databaseInstanceToken: string,\n databaseName: string,\n collectionName: string,\n /**\n * If no hash function is provided,\n * we assume that the whole internal store is removed anyway\n * so we do not have to delete the meta documents.\n */\n hashFunction?: HashFunction,\n) {\n const allCollectionMetaDocs = await getAllCollectionDocuments(\n storage.statics,\n databaseInternalStorage\n );\n const relevantCollectionMetaDocs = allCollectionMetaDocs\n .filter(metaDoc => metaDoc.data.name === collectionName);\n\n let removeStorages: {\n collectionName: string;\n schema: RxJsonSchema;\n isCollection: boolean;\n }[] = [];\n relevantCollectionMetaDocs.forEach(metaDoc => {\n removeStorages.push({\n collectionName: metaDoc.data.name,\n schema: metaDoc.data.schema,\n isCollection: true\n });\n metaDoc.data.connectedStorages.forEach(row => removeStorages.push({\n collectionName: row.collectionName,\n isCollection: false,\n schema: row.schema\n }));\n });\n\n // ensure uniqueness\n const alreadyAdded = new Set();\n removeStorages = removeStorages.filter(row => {\n const key = row.collectionName + '||' + row.schema.version;\n if (alreadyAdded.has(key)) {\n return false;\n } else {\n alreadyAdded.add(key);\n return true;\n }\n });\n\n // remove all the storages\n await Promise.all(\n removeStorages\n .map(async (row) => {\n const storageInstance = await storage.createStorageInstance({\n collectionName: row.collectionName,\n databaseInstanceToken,\n databaseName,\n multiInstance: false,\n options: {},\n schema: row.schema\n });\n await storageInstance.remove();\n if (row.isCollection) {\n await runAsyncPluginHooks('postRemoveRxCollection', {\n storage,\n databaseName: databaseName,\n collectionName\n });\n }\n })\n );\n\n // remove the meta documents\n if (hashFunction) {\n const writeRows = relevantCollectionMetaDocs.map(doc => {\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n writeDoc._meta.lwt = now();\n writeDoc._rev = createRevision(\n databaseInstanceToken,\n doc\n );\n return {\n previous: doc,\n document: writeDoc\n };\n });\n await databaseInternalStorage.bulkWrite(\n writeRows,\n 'rx-database-remove-collection-all'\n );\n }\n}\n"],"mappings":";;AAUA,SACIA,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,GAAG,QACA,iBAAiB;AACxB,SACIC,cAAc,QACX,oBAAoB;AAE3B,SAASC,mBAAmB,QAAQ,SAAS;AAC7C,SAASC,yBAAyB,QAAQ,8BAA8B;AACxE,SAASC,oBAAoB,QAAQ,qBAAqB;;AAE1D;AACA;AACA;AACA;AACA,OAAO,SAASC,0BAA0B,CACtCC,MAA2B,EAC3BC,IAA8C,EACrB;EACzB,IAAIC,OAAO,GAAGF,MAAM,CAACG,sBAAsB,CAACF,IAAI,CAAC;EACjDC,OAAO,GAAGP,cAAc,CACpBK,MAAM,CAACI,WAAW,EAClBJ,MAAM,CAACK,UAAU,EACjBH,OAAO,CACV;EACDA,OAAO,CAACI,KAAK,GAAGb,wBAAwB,EAAE;EAC1C,IAAI,CAACS,OAAO,CAACK,cAAc,CAAC,UAAU,CAAC,EAAE;IACrCL,OAAO,CAACM,QAAQ,GAAG,KAAK;EAC5B;EACA,IAAI,CAACN,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;oBAAA;oBAAA,OACVrC,mBAAmB,CAAC,wBAAwB,EAAE;sBAChDmB,OAAO,EAAPA,OAAO;sBACPM,YAAY,EAAEA,YAAY;sBAC1BC,cAAc,EAAdA;oBACJ,CAAC,CAAC;kBAAA;kBAAA;oBAAA;gBAAA;cAAA;YAAA,CAET;YAAA;cAAA;YAAA;UAAA,IAAC,CACT;QAAA;UAAA,KAGGC,YAAY;YAAA;YAAA;UAAA;UACNwB,SAAS,GAAGrB,0BAA0B,CAACkB,GAAG,CAAC,UAAAI,GAAG,EAAI;YACpD,IAAMC,QAAQ,GAAGnD,oBAAoB,CAACkD,GAAG,CAAC;YAC1CC,QAAQ,CAACzC,QAAQ,GAAG,IAAI;YACxByC,QAAQ,CAAC3C,KAAK,CAAC4C,GAAG,GAAGxD,GAAG,EAAE;YAC1BuD,QAAQ,CAACvC,IAAI,GAAGnB,cAAc,CAC1B6B,qBAAqB,EACrB4B,GAAG,CACN;YACD,OAAO;cACHG,QAAQ,EAAEH,GAAG;cACbI,QAAQ,EAAEH;YACd,CAAC;UACL,CAAC,CAAC;UAAA;UAAA,OACI9B,uBAAuB,CAACkC,SAAS,CACnCN,SAAS,EACT,mCAAmC,CACtC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAER;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/rx-collection.js b/dist/es/rx-collection.js index 4c6bb631193..84a0bc9487b 100644 --- a/dist/es/rx-collection.js +++ b/dist/es/rx-collection.js @@ -1,16 +1,20 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _createClass from "@babel/runtime/helpers/createClass"; -import { filter, startWith, mergeMap, shareReplay } from 'rxjs/operators'; -import { ucfirst, flatClone, promiseSeries, pluginMissing, ensureNotFalsy, getFromMapOrThrow, clone, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_VOID, RXJS_SHARE_REPLAY_DEFAULTS, getDefaultRxDocumentMeta, getDefaultRevision, nextTick } from './util'; +import _regeneratorRuntime from "@babel/runtime/regenerator"; +import { filter, mergeMap } from 'rxjs/operators'; +import { ucfirst, flatClone, promiseSeries, pluginMissing, ensureNotFalsy, getFromMapOrThrow, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_VOID, getDefaultRxDocumentMeta, getDefaultRevision } from './plugins/utils'; import { fillObjectDataBeforeInsert, createRxCollectionStorageInstance, removeCollectionStorages } from './rx-collection-helper'; import { createRxQuery, _getDefaultQuery } from './rx-query'; import { newRxError, newRxTypeError } from './rx-error'; -import { DocCache } from './doc-cache'; +import { DocumentCache } from './doc-cache'; import { createQueryCache, defaultCacheReplacementPolicy } from './query-cache'; import { createChangeEventBuffer } from './change-event-buffer'; import { runAsyncPluginHooks, runPluginHooks } from './hooks'; -import { createRxDocument } from './rx-document-prototype-merge'; +import { createNewRxDocument } from './rx-document-prototype-merge'; import { getWrappedStorageInstance, storageChangeEventToRxChangeEvent, throwIfIsStorageWriteError } from './rx-storage-helper'; import { defaultConflictHandler } from './replication-protocol'; +import { IncrementalWriteQueue } from './incremental-write'; +import { beforeDocumentUpdateWrite } from './rx-document'; var HOOKS_WHEN = ['pre', 'post']; var HOOKS_KEYS = ['insert', 'save', 'remove', 'create']; var hooksApplied = false; @@ -30,11 +34,12 @@ export var RxCollectionBase = /*#__PURE__*/function () { var conflictHandler = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : defaultConflictHandler; this.storageInstance = {}; this.timeouts = new Set(); - this._atomicUpsertQueues = new Map(); + this.incrementalWriteQueue = {}; + this._incrementalUpsertQueues = new Map(); this.synced = false; this.hooks = {}; this._subs = []; - this._docCache = new DocCache(); + this._docCache = {}; this._queryCache = createQueryCache(); this.$ = {}; this._changeEventBuffer = {}; @@ -55,73 +60,81 @@ export var RxCollectionBase = /*#__PURE__*/function () { _applyHookFunctions(this.asRxCollection); } var _proto = RxCollectionBase.prototype; - _proto.prepare = function prepare() { - try { + _proto.prepare = /*#__PURE__*/function () { + var _prepare = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var _this = this; - _this.storageInstance = getWrappedStorageInstance(_this.database, _this.internalStorageInstance, _this.schema.jsonSchema); - _this.$ = _this.database.eventBulks$.pipe(filter(function (changeEventBulk) { - return changeEventBulk.collectionName === _this.name; - }), mergeMap(function (changeEventBulk) { - return changeEventBulk.events; - })); - _this._changeEventBuffer = createChangeEventBuffer(_this.asRxCollection); - - /** - * Instead of resolving the EventBulk array here and spit it into - * single events, we should fully work with event bulks internally - * to save performance. - */ - return Promise.resolve(_this.database.storageToken).then(function (databaseStorageToken) { - var subDocs = _this.storageInstance.changeStream().subscribe(function (eventBulk) { - var changeEventBulk = { - id: eventBulk.id, - internal: false, - collectionName: _this.name, - storageToken: databaseStorageToken, - events: eventBulk.events.map(function (ev) { - return storageChangeEventToRxChangeEvent(false, ev, _this); - }), - databaseToken: _this.database.token, - checkpoint: eventBulk.checkpoint, - context: eventBulk.context - }; - _this.database.$emit(changeEventBulk); - }); - _this._subs.push(subDocs); - - /** - * When a write happens to the collection - * we find the changed document in the docCache - * and tell it that it has to change its data. - */ - _this._subs.push(_this.$.pipe(filter(function (cE) { - return !cE.isLocal; - })).subscribe(function (cE) { - // when data changes, send it to RxDocument in docCache - var doc = _this._docCache.get(cE.documentId); - if (doc) { - doc._handleChangeEvent(cE); - } - })); + var databaseStorageToken, subDocs; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + this.storageInstance = getWrappedStorageInstance(this.database, this.internalStorageInstance, this.schema.jsonSchema); + this.incrementalWriteQueue = new IncrementalWriteQueue(this.storageInstance, this.schema.primaryPath, function (newData, oldData) { + return beforeDocumentUpdateWrite(_this, newData, oldData); + }, function (result) { + return _this._runHooks('post', 'save', result); + }); + this.$ = this.database.eventBulks$.pipe(filter(function (changeEventBulk) { + return changeEventBulk.collectionName === _this.name; + }), mergeMap(function (changeEventBulk) { + return changeEventBulk.events; + })); + this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection); + this._docCache = new DocumentCache(this.schema.primaryPath, this.$.pipe(filter(function (cE) { + return !cE.isLocal; + })), function (docData) { + return createNewRxDocument(_this.asRxCollection, docData); + }); - /** - * Resolve the conflict tasks - * of the RxStorageInstance - */ - _this._subs.push(_this.storageInstance.conflictResultionTasks().subscribe(function (task) { - _this.conflictHandler(task.input, task.context).then(function (output) { - _this.storageInstance.resolveConflictResultionTask({ - id: task.id, - output: output + /** + * Instead of resolving the EventBulk array here and spit it into + * single events, we should fully work with event bulks internally + * to save performance. + */ + _context.next = 7; + return this.database.storageToken; + case 7: + databaseStorageToken = _context.sent; + subDocs = this.storageInstance.changeStream().subscribe(function (eventBulk) { + var changeEventBulk = { + id: eventBulk.id, + internal: false, + collectionName: _this.name, + storageToken: databaseStorageToken, + events: eventBulk.events.map(function (ev) { + return storageChangeEventToRxChangeEvent(false, ev, _this); + }), + databaseToken: _this.database.token, + checkpoint: eventBulk.checkpoint, + context: eventBulk.context + }; + _this.database.$emit(changeEventBulk); }); - }); - })); - return PROMISE_RESOLVE_VOID; - }); - } catch (e) { - return Promise.reject(e); + this._subs.push(subDocs); + + /** + * Resolve the conflict tasks + * of the RxStorageInstance + */ + this._subs.push(this.storageInstance.conflictResultionTasks().subscribe(function (task) { + _this.conflictHandler(task.input, task.context).then(function (output) { + _this.storageInstance.resolveConflictResultionTask({ + id: task.id, + output: output + }); + }); + })); + return _context.abrupt("return", PROMISE_RESOLVE_VOID); + case 12: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function prepare() { + return _prepare.apply(this, arguments); } - } // overwritte by migration-plugin + return prepare; + }() // overwritte by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { throw pluginMissing('migration'); @@ -137,182 +150,272 @@ export var RxCollectionBase = /*#__PURE__*/function () { var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; return this.getDataMigrator().migratePromise(batchSize); }; - _proto.insert = function insert(json) { - try { - var _this2 = this; - // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later - var useJson = fillObjectDataBeforeInsert(_this2.schema, json); - return Promise.resolve(_this2.bulkInsert([useJson])).then(function (writeResult) { - var isError = writeResult.error[0]; - throwIfIsStorageWriteError(_this2, useJson[_this2.schema.primaryPath], json, isError); - var insertResult = ensureNotFalsy(writeResult.success[0]); - return insertResult; - }); - } catch (e) { - return Promise.reject(e); + _proto.insert = /*#__PURE__*/function () { + var _insert = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(json) { + var useJson, writeResult, isError, insertResult; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later + useJson = fillObjectDataBeforeInsert(this.schema, json); + _context2.next = 3; + return this.bulkInsert([useJson]); + case 3: + writeResult = _context2.sent; + isError = writeResult.error[0]; + throwIfIsStorageWriteError(this, useJson[this.schema.primaryPath], json, isError); + insertResult = ensureNotFalsy(writeResult.success[0]); + return _context2.abrupt("return", insertResult); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function insert(_x) { + return _insert.apply(this, arguments); } - }; - _proto.bulkInsert = function bulkInsert(docsData) { - try { - var _temp3 = function _temp3(docs) { - var docsMap = new Map(); - var insertRows = docs.map(function (doc) { - docsMap.set(doc[_this3.schema.primaryPath], doc); - var docData = Object.assign(doc, { - _attachments: {}, - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision(), - _deleted: false - }); - var row = { - document: docData - }; - return row; - }); - return Promise.resolve(_this3.storageInstance.bulkWrite(insertRows, 'rx-collection-bulk-insert')).then(function (results) { - function _temp2() { - return { + return insert; + }(); + _proto.bulkInsert = /*#__PURE__*/function () { + var _bulkInsert = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(docsData) { + var _this2 = this; + var useDocs, docs, docsMap, insertRows, results, successDocData, rxDocuments; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!(docsData.length === 0)) { + _context3.next = 2; + break; + } + return _context3.abrupt("return", { + success: [], + error: [] + }); + case 2: + useDocs = docsData.map(function (docData) { + var useDocData = fillObjectDataBeforeInsert(_this2.schema, docData); + return useDocData; + }); + if (!this.hasHooks('pre', 'insert')) { + _context3.next = 9; + break; + } + _context3.next = 6; + return Promise.all(useDocs.map(function (doc) { + return _this2._runHooks('pre', 'insert', doc).then(function () { + return doc; + }); + })); + case 6: + _context3.t0 = _context3.sent; + _context3.next = 10; + break; + case 9: + _context3.t0 = useDocs; + case 10: + docs = _context3.t0; + docsMap = new Map(); + insertRows = docs.map(function (doc) { + docsMap.set(doc[_this2.schema.primaryPath], doc); + var docData = Object.assign(doc, { + _attachments: {}, + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision(), + _deleted: false + }); + var row = { + document: docData + }; + return row; + }); + _context3.next = 15; + return this.storageInstance.bulkWrite(insertRows, 'rx-collection-bulk-insert'); + case 15: + results = _context3.sent; + // create documents + successDocData = Object.values(results.success); + rxDocuments = successDocData.map(function (writtenDocData) { + return _this2._docCache.getCachedRxDocument(writtenDocData); + }); + if (!this.hasHooks('post', 'insert')) { + _context3.next = 21; + break; + } + _context3.next = 21; + return Promise.all(rxDocuments.map(function (doc) { + return _this2._runHooks('post', 'insert', docsMap.get(doc.primary), doc); + })); + case 21: + return _context3.abrupt("return", { success: rxDocuments, error: Object.values(results.error) - }; - } - // create documents - var successDocData = Object.values(results.success); - var rxDocuments = successDocData.map(function (writtenDocData) { - var doc = createRxDocument(_this3, writtenDocData); - return doc; - }); - var _temp = function () { - if (_this3.hasHooks('post', 'insert')) { - return Promise.resolve(Promise.all(rxDocuments.map(function (doc) { - return _this3._runHooks('post', 'insert', docsMap.get(doc.primary), doc); - }))).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - }; - var _this3 = this; - /** - * Optimization shortcut, - * do nothing when called with an empty array - */ - if (docsData.length === 0) { - return Promise.resolve({ - success: [], - error: [] - }); - } - var useDocs = docsData.map(function (docData) { - var useDocData = fillObjectDataBeforeInsert(_this3.schema, docData); - return useDocData; - }); - var _this3$hasHooks = _this3.hasHooks('pre', 'insert'); - return Promise.resolve(_this3$hasHooks ? Promise.resolve(Promise.all(useDocs.map(function (doc) { - return _this3._runHooks('pre', 'insert', doc).then(function () { - return doc; - }); - }))).then(_temp3) : _temp3(useDocs)); - } catch (e) { - return Promise.reject(e); + }); + case 22: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function bulkInsert(_x2) { + return _bulkInsert.apply(this, arguments); } - }; - _proto.bulkRemove = function bulkRemove(ids) { - try { - var _this4 = this; - /** - * Optimization shortcut, - * do nothing when called with an empty array - */ - if (ids.length === 0) { - return Promise.resolve({ - success: [], - error: [] - }); - } - return Promise.resolve(_this4.findByIds(ids)).then(function (rxDocumentMap) { - var docsData = []; - var docsMap = new Map(); - Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { - var data = clone(rxDocument.toJSON(true)); - docsData.push(data); - docsMap.set(rxDocument.primary, data); - }); - return Promise.resolve(Promise.all(docsData.map(function (doc) { - var primary = doc[_this4.schema.primaryPath]; - return _this4._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); - }))).then(function () { - var removeDocs = docsData.map(function (doc) { - var writeDoc = flatClone(doc); - writeDoc._deleted = true; - return { - previous: doc, - document: writeDoc - }; - }); - return Promise.resolve(_this4.storageInstance.bulkWrite(removeDocs, 'rx-collection-bulk-remove')).then(function (results) { - var successIds = Object.keys(results.success); - - // run hooks - return Promise.resolve(Promise.all(successIds.map(function (id) { - return _this4._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); - }))).then(function () { - var rxDocuments = successIds.map(function (id) { - return rxDocumentMap.get(id); - }); + return bulkInsert; + }(); + _proto.bulkRemove = /*#__PURE__*/function () { + var _bulkRemove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ids) { + var _this3 = this; + var rxDocumentMap, docsData, docsMap, removeDocs, results, successIds, rxDocuments; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(ids.length === 0)) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", { + success: [], + error: [] + }); + case 2: + _context4.next = 4; + return this.findByIds(ids).exec(); + case 4: + rxDocumentMap = _context4.sent; + docsData = []; + docsMap = new Map(); + Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { + var data = rxDocument.toMutableJSON(true); + docsData.push(data); + docsMap.set(rxDocument.primary, data); + }); + _context4.next = 10; + return Promise.all(docsData.map(function (doc) { + var primary = doc[_this3.schema.primaryPath]; + return _this3._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); + })); + case 10: + removeDocs = docsData.map(function (doc) { + var writeDoc = flatClone(doc); + writeDoc._deleted = true; return { - success: rxDocuments, - error: Object.values(results.error) + previous: doc, + document: writeDoc }; }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); + _context4.next = 13; + return this.storageInstance.bulkWrite(removeDocs, 'rx-collection-bulk-remove'); + case 13: + results = _context4.sent; + successIds = Object.keys(results.success); // run hooks + _context4.next = 17; + return Promise.all(successIds.map(function (id) { + return _this3._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); + })); + case 17: + rxDocuments = successIds.map(function (id) { + return getFromMapOrThrow(rxDocumentMap, id); + }); + return _context4.abrupt("return", { + success: rxDocuments, + error: Object.values(results.error) + }); + case 19: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function bulkRemove(_x3) { + return _bulkRemove.apply(this, arguments); } - } + return bulkRemove; + }() /** * same as bulkInsert but overwrites existing document with same primary */ ; - _proto.bulkUpsert = function bulkUpsert(docsData) { - try { - var _this5 = this; - var insertData = []; - var useJsonByDocId = new Map(); - docsData.forEach(function (docData) { - var useJson = fillObjectDataBeforeInsert(_this5.schema, docData); - var primary = useJson[_this5.schema.primaryPath]; - if (!primary) { - throw newRxError('COL3', { - primaryPath: _this5.schema.primaryPath, - data: useJson, - schema: _this5.schema.jsonSchema - }); + _proto.bulkUpsert = + /*#__PURE__*/ + function () { + var _bulkUpsert = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(docsData) { + var _this4 = this; + var insertData, useJsonByDocId, insertResult, ret, updatedDocs; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + insertData = []; + useJsonByDocId = new Map(); + docsData.forEach(function (docData) { + var useJson = fillObjectDataBeforeInsert(_this4.schema, docData); + var primary = useJson[_this4.schema.primaryPath]; + if (!primary) { + throw newRxError('COL3', { + primaryPath: _this4.schema.primaryPath, + data: useJson, + schema: _this4.schema.jsonSchema + }); + } + useJsonByDocId.set(primary, useJson); + insertData.push(useJson); + }); + _context6.next = 5; + return this.bulkInsert(insertData); + case 5: + insertResult = _context6.sent; + ret = insertResult.success.slice(0); + _context6.next = 9; + return Promise.all(insertResult.error.map( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(error) { + var id, writeData, docDataInDb, doc, newDoc; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!(error.status !== 409)) { + _context5.next = 2; + break; + } + throw newRxError('VD2', { + collection: _this4.name, + writeError: error + }); + case 2: + id = error.documentId; + writeData = getFromMapOrThrow(useJsonByDocId, id); + docDataInDb = ensureNotFalsy(error.documentInDb); + doc = _this4._docCache.getCachedRxDocument(docDataInDb); + _context5.next = 8; + return doc.incrementalModify(function () { + return writeData; + }); + case 8: + newDoc = _context5.sent; + return _context5.abrupt("return", newDoc); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x5) { + return _ref.apply(this, arguments); + }; + }())); + case 9: + updatedDocs = _context6.sent; + ret = ret.concat(updatedDocs); + return _context6.abrupt("return", ret); + case 12: + case "end": + return _context6.stop(); } - useJsonByDocId.set(primary, useJson); - insertData.push(useJson); - }); - return Promise.resolve(_this5.bulkInsert(insertData)).then(function (insertResult) { - var ret = insertResult.success.slice(0); - return Promise.resolve(Promise.all(insertResult.error.map(function (error) { - var id = error.documentId; - var writeData = getFromMapOrThrow(useJsonByDocId, id); - var docDataInDb = ensureNotFalsy(error.documentInDb); - var doc = createRxDocument(_this5.asRxCollection, docDataInDb); - return doc.atomicUpdate(function () { - return writeData; - }); - }))).then(function (updatedDocs) { - ret = ret.concat(updatedDocs); - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); + }, _callee6, this); + })); + function bulkUpsert(_x4) { + return _bulkUpsert.apply(this, arguments); } - } + return bulkUpsert; + }() /** * same as insert but overwrites existing document with same primary */ @@ -324,10 +427,10 @@ export var RxCollectionBase = /*#__PURE__*/function () { } /** - * upserts to a RxDocument, uses atomicUpdate if document already exists + * upserts to a RxDocument, uses incrementalModify if document already exists */; - _proto.atomicUpsert = function atomicUpsert(json) { - var _this6 = this; + _proto.incrementalUpsert = function incrementalUpsert(json) { + var _this5 = this; var useJson = fillObjectDataBeforeInsert(this.schema, json); var primary = useJson[this.schema.primaryPath]; if (!primary) { @@ -337,22 +440,20 @@ export var RxCollectionBase = /*#__PURE__*/function () { } // ensure that it won't try 2 parallel runs - var queue = this._atomicUpsertQueues.get(primary); + var queue = this._incrementalUpsertQueues.get(primary); if (!queue) { queue = PROMISE_RESOLVE_VOID; } queue = queue.then(function () { - return _atomicUpsertEnsureRxDocumentExists(_this6, primary, useJson); + return _incrementalUpsertEnsureRxDocumentExists(_this5, primary, useJson); }).then(function (wasInserted) { if (!wasInserted.inserted) { - return _atomicUpsertUpdate(wasInserted.doc, useJson).then(function () { - return wasInserted.doc; - }); + return _incrementalUpsertUpdate(wasInserted.doc, useJson); } else { return wasInserted.doc; } }); - this._atomicUpsertQueues.set(primary, queue); + this._incrementalUpsertQueues.set(primary, queue); return queue; }; _proto.find = function find(queryObj) { @@ -364,7 +465,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { if (!queryObj) { queryObj = _getDefaultQuery(); } - var query = createRxQuery('find', queryObj, this.asRxCollection); + var query = createRxQuery('find', queryObj, this); return query; }; _proto.findOne = function findOne(queryObj) { @@ -385,7 +486,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { throw newRxError('QU6'); } queryObj.limit = 1; - query = createRxQuery('findOne', queryObj, this.asRxCollection); + query = createRxQuery('findOne', queryObj, this); } if (typeof queryObj === 'number' || Array.isArray(queryObj)) { throw newRxTypeError('COL6', { @@ -398,7 +499,7 @@ export var RxCollectionBase = /*#__PURE__*/function () { if (!queryObj) { queryObj = _getDefaultQuery(); } - var query = createRxQuery('count', queryObj, this.asRxCollection); + var query = createRxQuery('count', queryObj, this); return query; } @@ -407,151 +508,14 @@ export var RxCollectionBase = /*#__PURE__*/function () { * has way better performance then running multiple findOne() or a find() with a complex $or-selected */; _proto.findByIds = function findByIds(ids) { - try { - var _this7 = this; - var ret = new Map(); - var mustBeQueried = []; - - // first try to fill from docCache - ids.forEach(function (id) { - var doc = _this7._docCache.get(id); - if (doc) { - ret.set(id, doc); - } else { - mustBeQueried.push(id); - } - }); - - // find everything which was not in docCache - var _temp4 = function () { - if (mustBeQueried.length > 0) { - return Promise.resolve(_this7.storageInstance.findDocumentsById(mustBeQueried, false)).then(function (docs) { - Object.values(docs).forEach(function (docData) { - var doc = createRxDocument(_this7, docData); - ret.set(doc.primary, doc); - }); - }); - } - }(); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(function () { - return ret; - }) : ret); - } catch (e) { - return Promise.reject(e); - } - } - /** - * like this.findByIds but returns an observable - * that always emits the current state - */ - ; - _proto.findByIds$ = function findByIds$(ids) { - var _this8 = this; - var currentValue = null; - var lastChangeEvent = -1; - - /** - * Ensure we do not process events in parallel - */ - var queue = PROMISE_RESOLVE_VOID; - var initialPromise = this.findByIds(ids).then(function (docsMap) { - lastChangeEvent = _this8._changeEventBuffer.counter; - currentValue = docsMap; - }); - var firstEmitDone = false; - return this.$.pipe(startWith(null), - /** - * Optimization shortcut. - * Do not proceed if the emitted RxChangeEvent - * is not relevant for the query. - */ - filter(function (changeEvent) { - if ( - // first emit has no event - changeEvent && ( - // local documents are not relevant for the query - changeEvent.isLocal || - // document of the change is not in the ids list. - !ids.includes(changeEvent.documentId))) { - return false; - } else { - return true; - } - }), mergeMap(function () { - return initialPromise; - }), - /** - * Because shareReplay with refCount: true - * will often subscribe/unsusbscribe - * we always ensure that we handled all missed events - * since the last subscription. - */ - mergeMap(function () { - queue = queue.then(function () { - try { - var _temp7 = function _temp7(_result) { - if (_exit) return _result; - firstEmitDone = true; - return currentValue; - }; - var _exit = false; - /** - * We first have to clone the Map - * to ensure we do not create side effects by mutating - * a Map that has already been returned before. - */ - currentValue = new Map(ensureNotFalsy(currentValue)); - var missedChangeEvents = _this8._changeEventBuffer.getFrom(lastChangeEvent + 1); - lastChangeEvent = _this8._changeEventBuffer.counter; - var _temp6 = function () { - if (missedChangeEvents === null) { - /** - * changeEventBuffer is of bounds -> we must re-execute over the database - * because we cannot calculate the new results just from the events. - */ - return Promise.resolve(_this8.findByIds(ids)).then(function (newResult) { - lastChangeEvent = _this8._changeEventBuffer.counter; - _exit = true; - return newResult; - }); - } else { - var resultHasChanged = false; - missedChangeEvents.forEach(function (rxChangeEvent) { - var docId = rxChangeEvent.documentId; - if (!ids.includes(docId)) { - // document is not relevant for the result set - return; - } - var op = rxChangeEvent.operation; - if (op === 'INSERT' || op === 'UPDATE') { - resultHasChanged = true; - var rxDocument = createRxDocument(_this8.asRxCollection, rxChangeEvent.documentData); - ensureNotFalsy(currentValue).set(docId, rxDocument); - } else { - if (ensureNotFalsy(currentValue).has(docId)) { - resultHasChanged = true; - ensureNotFalsy(currentValue)["delete"](docId); - } - } - }); - - // nothing happened that affects the result -> do not emit - if (!resultHasChanged && firstEmitDone) { - var _temp5 = false; - _exit = true; - return _temp5; - } - } - }(); - return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(_temp7) : _temp7(_temp6)); - } catch (e) { - return Promise.reject(e); - } - }); - return queue; - }), filter(function (x) { - return !!x; - }), shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)); + var _selector2; + var mangoQuery = { + selector: (_selector2 = {}, _selector2[this.schema.primaryPath] = { + $in: ids.slice(0) + }, _selector2) + }; + var query = createRxQuery('findByIds', mangoQuery, this); + return query; } /** @@ -572,29 +536,6 @@ export var RxCollectionBase = /*#__PURE__*/function () { throw pluginMissing('crdt'); } - /** - * sync with a CouchDB endpoint - */; - _proto.syncCouchDB = function syncCouchDB(_syncOptions) { - throw pluginMissing('replication'); - } - - /** - * sync with a GraphQL endpoint - */; - _proto.syncGraphQL = function syncGraphQL(_options) { - throw pluginMissing('replication-graphql'); - }; - _proto.syncCouchDBNew = function syncCouchDBNew(_syncOptions) { - throw pluginMissing('replication-couchdb-new'); - }; - _proto.syncP2P = function syncP2P(_syncOptions) { - throw pluginMissing('replication-p2p'); - }; - _proto.syncFirestore = function syncFirestore(_syncOptions) { - throw pluginMissing('replication-firestore'); - } - /** * HOOKS */; @@ -689,18 +630,18 @@ export var RxCollectionBase = /*#__PURE__*/function () { * so that no running timeouts prevent the exit of the JavaScript process. */; _proto.promiseWait = function promiseWait(time) { - var _this9 = this; + var _this6 = this; var ret = new Promise(function (res) { var timeout = setTimeout(function () { - _this9.timeouts["delete"](timeout); + _this6.timeouts["delete"](timeout); res(); }, time); - _this9.timeouts.add(timeout); + _this6.timeouts.add(timeout); }); return ret; }; _proto.destroy = function destroy() { - var _this10 = this; + var _this7 = this; if (this.destroyed) { return PROMISE_RESOLVE_FALSE; } @@ -727,11 +668,11 @@ export var RxCollectionBase = /*#__PURE__*/function () { * but the change is not added to the changes collection. */ return this.database.requestIdlePromise().then(function () { - return Promise.all(_this10.onDestroy.map(function (fn) { + return Promise.all(_this7.onDestroy.map(function (fn) { return fn(); })); }).then(function () { - return _this10.storageInstance.close(); + return _this7.storageInstance.close(); }).then(function () { /** * Unsubscribing must be done AFTER the storageInstance.close() @@ -739,11 +680,11 @@ export var RxCollectionBase = /*#__PURE__*/function () { * otherwise there might be open conflicts to be resolved which * will then stuck and never resolve. */ - _this10._subs.forEach(function (sub) { + _this7._subs.forEach(function (sub) { return sub.unsubscribe(); }); - delete _this10.database.collections[_this10.name]; - return runAsyncPluginHooks('postDestroyRxCollection', _this10).then(function () { + delete _this7.database.collections[_this7.name]; + return runAsyncPluginHooks('postDestroyRxCollection', _this7).then(function () { return true; }); }); @@ -752,16 +693,29 @@ export var RxCollectionBase = /*#__PURE__*/function () { /** * remove all data of the collection */; - _proto.remove = function remove() { - try { - var _this11 = this; - return Promise.resolve(_this11.destroy()).then(function () { - return Promise.resolve(removeCollectionStorages(_this11.database.storage, _this11.database.internalStore, _this11.database.token, _this11.database.name, _this11.name, _this11.database.hashFunction)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + _proto.remove = + /*#__PURE__*/ + function () { + var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() { + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.destroy(); + case 2: + _context7.next = 4; + return removeCollectionStorages(this.database.storage, this.database.internalStore, this.database.token, this.database.name, this.name, this.database.hashFunction); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _createClass(RxCollectionBase, [{ key: "insert$", get: function get() { @@ -809,13 +763,9 @@ function _applyHookFunctions(collection) { }); }); } -function _atomicUpsertUpdate(doc, json) { - return doc.atomicUpdate(function (_innerDoc) { +function _incrementalUpsertUpdate(doc, json) { + return doc.incrementalModify(function (_innerDoc) { return json; - }).then(function () { - return nextTick(); - }).then(function () { - return doc; }); } @@ -823,15 +773,15 @@ function _atomicUpsertUpdate(doc, json) { * ensures that the given document exists * @return promise that resolves with new doc and flag if inserted */ -function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { +function _incrementalUpsertEnsureRxDocumentExists(rxCollection, primary, json) { /** * Optimisation shortcut, * first try to find the document in the doc-cache */ - var docFromCache = rxCollection._docCache.get(primary); - if (docFromCache) { + var docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary); + if (docDataFromCache) { return Promise.resolve({ - doc: docFromCache, + doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache), inserted: false }); } @@ -855,30 +805,30 @@ function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { /** * creates and prepares a new collection */ -export function createRxCollection(_ref) { - var database = _ref.database, - name = _ref.name, - schema = _ref.schema, - _ref$instanceCreation = _ref.instanceCreationOptions, - instanceCreationOptions = _ref$instanceCreation === void 0 ? {} : _ref$instanceCreation, - _ref$migrationStrateg = _ref.migrationStrategies, - migrationStrategies = _ref$migrationStrateg === void 0 ? {} : _ref$migrationStrateg, - _ref$autoMigrate = _ref.autoMigrate, - autoMigrate = _ref$autoMigrate === void 0 ? true : _ref$autoMigrate, - _ref$statics = _ref.statics, - statics = _ref$statics === void 0 ? {} : _ref$statics, - _ref$methods = _ref.methods, - methods = _ref$methods === void 0 ? {} : _ref$methods, - _ref$attachments = _ref.attachments, - attachments = _ref$attachments === void 0 ? {} : _ref$attachments, - _ref$options = _ref.options, - options = _ref$options === void 0 ? {} : _ref$options, - _ref$localDocuments = _ref.localDocuments, - localDocuments = _ref$localDocuments === void 0 ? false : _ref$localDocuments, - _ref$cacheReplacement = _ref.cacheReplacementPolicy, - cacheReplacementPolicy = _ref$cacheReplacement === void 0 ? defaultCacheReplacementPolicy : _ref$cacheReplacement, - _ref$conflictHandler = _ref.conflictHandler, - conflictHandler = _ref$conflictHandler === void 0 ? defaultConflictHandler : _ref$conflictHandler; +export function createRxCollection(_ref2) { + var database = _ref2.database, + name = _ref2.name, + schema = _ref2.schema, + _ref2$instanceCreatio = _ref2.instanceCreationOptions, + instanceCreationOptions = _ref2$instanceCreatio === void 0 ? {} : _ref2$instanceCreatio, + _ref2$migrationStrate = _ref2.migrationStrategies, + migrationStrategies = _ref2$migrationStrate === void 0 ? {} : _ref2$migrationStrate, + _ref2$autoMigrate = _ref2.autoMigrate, + autoMigrate = _ref2$autoMigrate === void 0 ? true : _ref2$autoMigrate, + _ref2$statics = _ref2.statics, + statics = _ref2$statics === void 0 ? {} : _ref2$statics, + _ref2$methods = _ref2.methods, + methods = _ref2$methods === void 0 ? {} : _ref2$methods, + _ref2$attachments = _ref2.attachments, + attachments = _ref2$attachments === void 0 ? {} : _ref2$attachments, + _ref2$options = _ref2.options, + options = _ref2$options === void 0 ? {} : _ref2$options, + _ref2$localDocuments = _ref2.localDocuments, + localDocuments = _ref2$localDocuments === void 0 ? false : _ref2$localDocuments, + _ref2$cacheReplacemen = _ref2.cacheReplacementPolicy, + cacheReplacementPolicy = _ref2$cacheReplacemen === void 0 ? defaultCacheReplacementPolicy : _ref2$cacheReplacemen, + _ref2$conflictHandler = _ref2.conflictHandler, + conflictHandler = _ref2$conflictHandler === void 0 ? defaultConflictHandler : _ref2$conflictHandler; var storageInstanceCreationParams = { databaseInstanceToken: database.token, databaseName: database.name, @@ -893,9 +843,9 @@ export function createRxCollection(_ref) { var collection = new RxCollectionBase(database, name, schema, storageInstance, instanceCreationOptions, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics, conflictHandler); return collection.prepare().then(function () { // ORM add statics - Object.entries(statics).forEach(function (_ref2) { - var funName = _ref2[0], - fun = _ref2[1]; + Object.entries(statics).forEach(function (_ref3) { + var funName = _ref3[0], + fun = _ref3[1]; Object.defineProperty(collection, funName, { get: function get() { return fun.bind(collection); diff --git a/dist/es/rx-collection.js.map b/dist/es/rx-collection.js.map index b280a46bf06..3253964ac03 100644 --- a/dist/es/rx-collection.js.map +++ b/dist/es/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["filter","startWith","mergeMap","shareReplay","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","clone","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","RXJS_SHARE_REPLAY_DEFAULTS","getDefaultRxDocumentMeta","getDefaultRevision","nextTick","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocCache","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createRxDocument","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","throwIfIsStorageWriteError","defaultConflictHandler","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","_atomicUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","prepare","jsonSchema","eventBulks$","pipe","changeEventBulk","collectionName","events","storageToken","databaseStorageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","map","ev","databaseToken","token","checkpoint","context","$emit","push","cE","isLocal","doc","get","documentId","_handleChangeEvent","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","migrationNeeded","getDataMigrator","migrate","batchSize","migratePromise","insert","json","useJson","bulkInsert","writeResult","isError","error","primaryPath","insertResult","success","docsData","docs","docsMap","insertRows","set","docData","Object","assign","_attachments","_meta","_rev","_deleted","row","document","bulkWrite","results","rxDocuments","values","successDocData","writtenDocData","hasHooks","Promise","all","_runHooks","primary","length","useDocs","useDocData","bulkRemove","ids","findByIds","rxDocumentMap","Array","from","forEach","rxDocument","data","toJSON","removeDocs","writeDoc","previous","successIds","keys","bulkUpsert","insertData","useJsonByDocId","ret","slice","writeData","docDataInDb","documentInDb","atomicUpdate","updatedDocs","concat","upsert","result","atomicUpsert","queue","_atomicUpsertEnsureRxDocumentExists","wasInserted","inserted","_atomicUpsertUpdate","find","queryObj","query","findOne","selector","limit","isArray","count","mustBeQueried","findDocumentsById","findByIds$","currentValue","lastChangeEvent","initialPromise","counter","firstEmitDone","changeEvent","includes","missedChangeEvents","getFrom","newResult","resultHasChanged","rxChangeEvent","docId","op","operation","documentData","has","x","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","syncCouchDB","_syncOptions","syncGraphQL","_options","syncCouchDBNew","syncP2P","syncFirestore","addHook","when","key","fun","parallel","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","res","timeout","setTimeout","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","hashFunction","collection","colProto","getPrototypeOf","fnName","_innerDoc","rxCollection","docFromCache","resolve","exec","newDoc","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","entries","funName","defineProperty","version","creator","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n startWith,\n mergeMap,\n shareReplay\n} from 'rxjs/operators';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n clone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID,\n RXJS_SHARE_REPLAY_DEFAULTS,\n getDefaultRxDocumentMeta,\n getDefaultRevision,\n nextTick\n} from './util';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCouchDBReplicationState,\n MigrationState,\n SyncOptions,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n SyncOptionsGraphQL,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageBulkWriteError,\n RxDocumentData,\n RxDocumentWriteData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex\n} from './types';\nimport type {\n RxGraphQLReplicationState\n} from './plugins/replication-graphql';\nimport type {\n RxCouchDBNewReplicationState,\n SyncOptionsCouchDBNew\n} from './plugins/replication-couchdb-new';\nimport type {\n SyncOptionsP2P,\n RxP2PReplicationPool\n} from './plugins/replication-p2p';\nimport type {\n RxFirestoreReplicationState,\n SyncOptionsFirestore\n} from './plugins/replication-firestore';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: RxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: KeyFunctionMap = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _atomicUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocCache> = new DocCache();\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n\n this.$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * When a write happens to the collection\n * we find the changed document in the docCache\n * and tell it that it has to change its data.\n */\n this._subs.push(\n this.$\n .pipe(\n filter((cE: RxChangeEvent) => !cE.isLocal)\n )\n .subscribe(cE => {\n // when data changes, send it to RxDocument in docCache\n const doc = this._docCache.get(cE.documentId);\n if (doc) {\n doc._handleChangeEvent(cE);\n }\n })\n );\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n // overwritte by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n\n // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later\n const useJson: RxDocumentWriteData = fillObjectDataBeforeInsert(this.schema, json);\n\n const writeResult = await this.bulkInsert([useJson]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, useJson[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageBulkWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[this.schema.primaryPath] as any, doc);\n const docData = Object.assign(doc, {\n _attachments: {},\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _deleted: false\n });\n const row: BulkWriteRow = { document: docData };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const successDocData: RxDocumentData[] = Object.values(results.success);\n const rxDocuments: any[] = successDocData\n .map((writtenDocData) => {\n const doc = createRxDocument(this as any, writtenDocData);\n return doc;\n });\n\n if (this.hasHooks('post', 'insert')) {\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageBulkWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids);\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = clone(rxDocument.toJSON(true)) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = Object.keys(results.success);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments: any[] = successIds.map(id => {\n return rxDocumentMap.get(id);\n });\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise[]> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(error => {\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = createRxDocument(this.asRxCollection, docDataInDb);\n return doc.atomicUpdate(() => writeData);\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[0]);\n }\n\n /**\n * upserts to a RxDocument, uses atomicUpdate if document already exists\n */\n atomicUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._atomicUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _atomicUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _atomicUpsertUpdate(wasInserted.doc, useJson)\n .then(() => wasInserted.doc);\n } else {\n return wasInserted.doc;\n }\n });\n this._atomicUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this.asRxCollection);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null\n > {\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n // cannot have limit on findOne queries because it will be overwritte\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this.asRxCollection);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this.asRxCollection);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n async findByIds(\n ids: string[]\n ): Promise>> {\n\n const ret = new Map();\n const mustBeQueried: string[] = [];\n\n // first try to fill from docCache\n ids.forEach(id => {\n const doc = this._docCache.get(id);\n if (doc) {\n ret.set(id, doc);\n } else {\n mustBeQueried.push(id);\n }\n });\n\n // find everything which was not in docCache\n if (mustBeQueried.length > 0) {\n const docs = await this.storageInstance.findDocumentsById(mustBeQueried, false);\n Object.values(docs).forEach(docData => {\n const doc = createRxDocument(this as any, docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret;\n }\n\n /**\n * like this.findByIds but returns an observable\n * that always emits the current state\n */\n findByIds$(\n ids: string[]\n ): Observable>> {\n let currentValue: Map> | null = null;\n let lastChangeEvent: number = -1;\n\n /**\n * Ensure we do not process events in parallel\n */\n let queue: Promise = PROMISE_RESOLVE_VOID;\n\n const initialPromise = this.findByIds(ids).then(docsMap => {\n lastChangeEvent = this._changeEventBuffer.counter;\n currentValue = docsMap;\n });\n let firstEmitDone = false;\n\n return this.$.pipe(\n startWith(null),\n /**\n * Optimization shortcut.\n * Do not proceed if the emitted RxChangeEvent\n * is not relevant for the query.\n */\n filter(changeEvent => {\n if (\n // first emit has no event\n changeEvent &&\n (\n // local documents are not relevant for the query\n changeEvent.isLocal ||\n // document of the change is not in the ids list.\n !ids.includes(changeEvent.documentId)\n )\n ) {\n return false;\n } else {\n return true;\n }\n }),\n mergeMap(() => initialPromise),\n /**\n * Because shareReplay with refCount: true\n * will often subscribe/unsusbscribe\n * we always ensure that we handled all missed events\n * since the last subscription.\n */\n mergeMap(() => {\n queue = queue.then(async () => {\n /**\n * We first have to clone the Map\n * to ensure we do not create side effects by mutating\n * a Map that has already been returned before.\n */\n currentValue = new Map(ensureNotFalsy(currentValue));\n const missedChangeEvents = this._changeEventBuffer.getFrom(lastChangeEvent + 1);\n lastChangeEvent = this._changeEventBuffer.counter;\n if (missedChangeEvents === null) {\n /**\n * changeEventBuffer is of bounds -> we must re-execute over the database\n * because we cannot calculate the new results just from the events.\n */\n const newResult = await this.findByIds(ids);\n lastChangeEvent = this._changeEventBuffer.counter;\n return newResult;\n } else {\n let resultHasChanged = false;\n missedChangeEvents\n .forEach(rxChangeEvent => {\n const docId = rxChangeEvent.documentId;\n if (!ids.includes(docId)) {\n // document is not relevant for the result set\n return;\n }\n const op = rxChangeEvent.operation;\n if (op === 'INSERT' || op === 'UPDATE') {\n resultHasChanged = true;\n const rxDocument = createRxDocument(\n this.asRxCollection,\n rxChangeEvent.documentData\n );\n ensureNotFalsy(currentValue).set(docId, rxDocument);\n } else {\n if (ensureNotFalsy(currentValue).has(docId)) {\n resultHasChanged = true;\n ensureNotFalsy(currentValue).delete(docId);\n }\n }\n });\n\n // nothing happened that affects the result -> do not emit\n if (!resultHasChanged && firstEmitDone) {\n return false as any;\n }\n }\n firstEmitDone = true;\n return currentValue;\n });\n return queue;\n }),\n filter(x => !!x),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * sync with a CouchDB endpoint\n */\n syncCouchDB(_syncOptions: SyncOptions): RxCouchDBReplicationState {\n throw pluginMissing('replication');\n }\n\n /**\n * sync with a GraphQL endpoint\n */\n syncGraphQL(_options: SyncOptionsGraphQL): RxGraphQLReplicationState {\n throw pluginMissing('replication-graphql');\n }\n\n syncCouchDBNew(_syncOptions: SyncOptionsCouchDBNew): RxCouchDBNewReplicationState {\n throw pluginMissing('replication-couchdb-new');\n }\n\n syncP2P(_syncOptions: SyncOptionsP2P): RxP2PReplicationPool {\n throw pluginMissing('replication-p2p');\n }\n syncFirestore(_syncOptions: SyncOptionsFirestore): RxFirestoreReplicationState {\n throw pluginMissing('replication-firestore');\n }\n\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _atomicUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.atomicUpdate((_innerDoc: RxDocumentData) => {\n return json;\n })\n .then(() => nextTick())\n .then(() => {\n return doc;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _atomicUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docFromCache = rxCollection._docCache.get(primary);\n if (docFromCache) {\n return Promise.resolve({\n doc: docFromCache,\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";AAAA,SACIA,MAAM,EACNC,SAAS,EACTC,QAAQ,EACRC,WAAW,QACR,gBAAgB;AAEvB,SACIC,OAAO,EACPC,SAAS,EACTC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,iBAAiB,EACjBC,KAAK,EACLC,qBAAqB,EACrBC,oBAAoB,EACpBC,0BAA0B,EAC1BC,wBAAwB,EACxBC,kBAAkB,EAClBC,QAAQ,QACL,QAAQ;AACf,SACIC,0BAA0B,EAC1BC,iCAAiC,EACjCC,wBAAwB,QACrB,wBAAwB;AAC/B,SACIC,aAAa,EACbC,gBAAgB,QACb,YAAY;AACnB,SACIC,UAAU,EACVC,cAAc,QACX,YAAY;AAInB,SACIC,QAAQ,QACL,aAAa;AACpB,SAEIC,gBAAgB,EAChBC,6BAA6B,QAC1B,eAAe;AACtB,SAEIC,uBAAuB,QACpB,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AAC,CAAC;MACF,OAAO2M,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,SAIM,CAAC,UAAAuB,GAAG,EAAI;MACV,OAAOhO,eAAe,CAACiM,KAAK,EAAE,CACzBjJ,IAAI,CAAC;QAAA,OAAMuC,OAAO,CAAC0I,MAAM,CAACD,GAAG,CAAC;MAAA,EAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASE,cAAc,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYhP,gBAAgB;AAC1C"} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["filter","mergeMap","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","getDefaultRxDocumentMeta","getDefaultRevision","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","throwIfIsStorageWriteError","defaultConflictHandler","IncrementalWriteQueue","beforeDocumentUpdateWrite","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","eventBulks$","pipe","changeEventBulk","collectionName","events","cE","isLocal","docData","storageToken","databaseStorageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","map","ev","databaseToken","token","checkpoint","context","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","migrationNeeded","getDataMigrator","migrate","batchSize","migratePromise","insert","json","useJson","bulkInsert","writeResult","isError","error","insertResult","success","docsData","length","useDocs","useDocData","hasHooks","Promise","all","doc","docs","docsMap","insertRows","set","Object","assign","_attachments","_meta","_rev","_deleted","row","document","bulkWrite","results","successDocData","values","rxDocuments","writtenDocData","getCachedRxDocument","get","primary","bulkRemove","ids","findByIds","exec","rxDocumentMap","Array","from","forEach","rxDocument","data","toMutableJSON","removeDocs","writeDoc","previous","successIds","keys","bulkUpsert","insertData","useJsonByDocId","ret","slice","status","collection","writeError","documentId","writeData","docDataInDb","documentInDb","incrementalModify","newDoc","updatedDocs","concat","upsert","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","selector","limit","isArray","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","res","timeout","setTimeout","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","hashFunction","operation","colProto","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","entries","funName","defineProperty","version","creator","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n mergeMap\n} from 'rxjs/operators';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID,\n getDefaultRxDocumentMeta,\n getDefaultRevision\n} from './plugins/utils';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocumentCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n MigrationState,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxDocumentWriteData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex\n} from './types';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\nimport { IncrementalWriteQueue } from './incremental-write';\nimport { beforeDocumentUpdateWrite } from './rx-document';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: KeyFunctionMap = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n this.$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n // overwritte by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n\n // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later\n const useJson: RxDocumentWriteData = fillObjectDataBeforeInsert(this.schema, json);\n\n const writeResult = await this.bulkInsert([useJson]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, useJson[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[this.schema.primaryPath] as any, doc);\n const docData = Object.assign(doc, {\n _attachments: {},\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _deleted: false\n });\n const row: BulkWriteRow = { document: docData };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const successDocData: RxDocumentData[] = Object.values(results.success);\n const rxDocuments: any[] = successDocData\n .map((writtenDocData) => this._docCache.getCachedRxDocument(writtenDocData));\n\n if (this.hasHooks('post', 'insert')) {\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = Object.keys(results.success);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise[]> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('VD2', {\n collection: this.name,\n writeError: error\n });\n }\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n return newDoc;\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[0]);\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null\n > {\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n // cannot have limit on findOne queries because it will be overwritte\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery>> {\n const mangoQuery: MangoQuery = {\n selector: {\n [this.schema.primaryPath]: {\n $in: ids.slice(0)\n }\n } as any\n };\n const query = createRxQuery('findByIds', mangoQuery, this as any);\n return query as any;\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;AAAA,SACIA,MA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,eAAe;UACfR,uBAAuB,EAAvBA,uBAAuB;UACvBC,mBAAmB,EAAnBA,mBAAmB;UACnBC,OAAO,EAAPA,OAAO;UACPC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA,OAAO;UACPC,sBAAsB,EAAtBA,sBAAsB;UACtBsM,cAAc,EAAdA,cAAc;UACdrM,OAAO,EAAPA;QACJ;MACJ,CAAC,CAAC;MACF,OAAOyH,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,SAIM,CAAC,UAAAuF,GAAG,EAAI;MACV,OAAO9M,eAAe,CAACgL,KAAK,EAAE,CACzB7H,IAAI,CAAC;QAAA,OAAMsB,OAAO,CAACsI,MAAM,CAACD,GAAG,CAAC;MAAA,EAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASE,cAAc,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAY9N,gBAAgB;AAC1C"} \ No newline at end of file diff --git a/dist/es/rx-database-internal-store.js b/dist/es/rx-database-internal-store.js index 583ac05ccf9..d8ce8f1bb91 100644 --- a/dist/es/rx-database-internal-store.js +++ b/dist/es/rx-database-internal-store.js @@ -1,307 +1,9 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { isBulkWriteConflictError, newRxError } from './rx-error'; import { fillWithDefaultSettings, getComposedPrimaryKeyOfDocumentData } from './rx-schema-helper'; import { getSingleDocument, writeSingle } from './rx-storage-helper'; -import { clone, ensureNotFalsy, fastUnsecureHash, getDefaultRevision, getDefaultRxDocumentMeta, randomCouchString } from './util'; -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} /** - * returns the primary for a given collection-data - * used in the internal store of a RxDatabase - */ -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -export var addConnectedStorageToCollection = function addConnectedStorageToCollection(collection, storageCollectionName, schema) { - try { - var _exit = false; - var collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema); - var collectionDocId = getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION); - return Promise.resolve(_for(function () { - return !_exit; - }, void 0, function () { - return Promise.resolve(getSingleDocument(collection.database.internalStore, collectionDocId)).then(function (collectionDoc) { - var saveData = clone(ensureNotFalsy(collectionDoc)); - /** - * Add array if not exist for backwards compatibility - * TODO remove this in 2023 - */ - if (!saveData.data.connectedStorages) { - saveData.data.connectedStorages = []; - } - - // do nothing if already in array - var alreadyThere = saveData.data.connectedStorages.find(function (row) { - return row.collectionName === storageCollectionName && row.schema.version === schema.version; - }); - if (alreadyThere) { - _exit = true; - return; - } - - // otherwise add to array and save - saveData.data.connectedStorages.push({ - collectionName: storageCollectionName, - schema: schema - }); - return _catch(function () { - return Promise.resolve(writeSingle(collection.database.internalStore, { - previous: ensureNotFalsy(collectionDoc), - document: saveData - }, 'add-connected-storage-to-collection')).then(function () {}); - }, function (err) { - if (!isBulkWriteConflictError(err)) { - throw err; - } - }); - }); - })); - } catch (e) { - return Promise.reject(e); - } -}; -export var ensureStorageTokenDocumentExists = function ensureStorageTokenDocumentExists(rxDatabase) { - try { - /** - * To have less read-write cycles, - * we just try to insert a new document - * and only fetch the existing one if a conflict happened. - */ - var storageToken = randomCouchString(10); - var passwordHash = rxDatabase.password ? fastUnsecureHash(rxDatabase.password) : undefined; - var docData = { - id: STORAGE_TOKEN_DOCUMENT_ID, - context: INTERNAL_CONTEXT_STORAGE_TOKEN, - key: STORAGE_TOKEN_DOCUMENT_KEY, - data: { - token: storageToken, - /** - * We add the instance token here - * to be able to detect if a given RxDatabase instance - * is the first instance that was ever created - * or if databases have existed earlier on that storage - * with the same database name. - */ - instanceToken: rxDatabase.token, - passwordHash: passwordHash - }, - _deleted: false, - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision(), - _attachments: {} - }; - return Promise.resolve(rxDatabase.internalStore.bulkWrite([{ - document: docData - }], 'internal-add-storage-token')).then(function (writeResult) { - if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) { - return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]; - } - - /** - * If we get a 409 error, - * it means another instance already inserted the storage token. - * So we get that token from the database and return that one. - */ - var error = ensureNotFalsy(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]); - if (error.isError && error.status === 409) { - var conflictError = error; - if (passwordHash && passwordHash !== ensureNotFalsy(conflictError.documentInDb).data.passwordHash) { - throw newRxError('DB1', { - passwordHash: passwordHash, - existingPasswordHash: ensureNotFalsy(conflictError.documentInDb).data.passwordHash - }); - } - var storageTokenDocInDb = conflictError.documentInDb; - return ensureNotFalsy(storageTokenDocInDb); - } - throw error; - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Returns all internal documents - * with context 'collection' - */ -export var getAllCollectionDocuments = function getAllCollectionDocuments(storageStatics, storageInstance) { - try { - var getAllQueryPrepared = storageStatics.prepareQuery(storageInstance.schema, { - selector: { - context: INTERNAL_CONTEXT_COLLECTION - }, - sort: [{ - id: 'asc' - }], - skip: 0 - }); - return Promise.resolve(storageInstance.query(getAllQueryPrepared)).then(function (queryResult) { - var allDocs = queryResult.documents; - return allDocs; - }); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * to not confuse multiInstance-messages with other databases that have the same - * name and adapter, but do not share state with this one (for example in-memory-instances), - * we set a storage-token and use it in the broadcast-channel - */ +import { clone, ensureNotFalsy, fastUnsecureHash, getDefaultRevision, getDefaultRxDocumentMeta, randomCouchString } from './plugins/utils'; export var INTERNAL_CONTEXT_COLLECTION = 'collection'; export var INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token'; @@ -361,8 +63,209 @@ export function getPrimaryKeyOfInternalDocument(key, context) { context: context }); } + +/** + * Returns all internal documents + * with context 'collection' + */ +export function getAllCollectionDocuments(_x, _x2) { + return _getAllCollectionDocuments.apply(this, arguments); +} + +/** + * to not confuse multiInstance-messages with other databases that have the same + * name and adapter, but do not share state with this one (for example in-memory-instances), + * we set a storage-token and use it in the broadcast-channel + */ +function _getAllCollectionDocuments() { + _getAllCollectionDocuments = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(storageStatics, storageInstance) { + var getAllQueryPrepared, queryResult, allDocs; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + getAllQueryPrepared = storageStatics.prepareQuery(storageInstance.schema, { + selector: { + context: INTERNAL_CONTEXT_COLLECTION + }, + sort: [{ + id: 'asc' + }], + skip: 0 + }); + _context.next = 3; + return storageInstance.query(getAllQueryPrepared); + case 3: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getAllCollectionDocuments.apply(this, arguments); +} export var STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken'; export var STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(STORAGE_TOKEN_DOCUMENT_KEY, INTERNAL_CONTEXT_STORAGE_TOKEN); +export function ensureStorageTokenDocumentExists(_x3) { + return _ensureStorageTokenDocumentExists.apply(this, arguments); +} +function _ensureStorageTokenDocumentExists() { + _ensureStorageTokenDocumentExists = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rxDatabase) { + var storageToken, passwordHash, docData, writeResult, error, conflictError, storageTokenDocInDb; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + /** + * To have less read-write cycles, + * we just try to insert a new document + * and only fetch the existing one if a conflict happened. + */ + storageToken = randomCouchString(10); + passwordHash = rxDatabase.password ? fastUnsecureHash(rxDatabase.password) : undefined; + docData = { + id: STORAGE_TOKEN_DOCUMENT_ID, + context: INTERNAL_CONTEXT_STORAGE_TOKEN, + key: STORAGE_TOKEN_DOCUMENT_KEY, + data: { + token: storageToken, + /** + * We add the instance token here + * to be able to detect if a given RxDatabase instance + * is the first instance that was ever created + * or if databases have existed earlier on that storage + * with the same database name. + */ + instanceToken: rxDatabase.token, + passwordHash: passwordHash + }, + _deleted: false, + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision(), + _attachments: {} + }; + _context2.next = 5; + return rxDatabase.internalStore.bulkWrite([{ + document: docData + }], 'internal-add-storage-token'); + case 5: + writeResult = _context2.sent; + if (!writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) { + _context2.next = 8; + break; + } + return _context2.abrupt("return", writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]); + case 8: + /** + * If we get a 409 error, + * it means another instance already inserted the storage token. + * So we get that token from the database and return that one. + */ + error = ensureNotFalsy(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]); + if (!(error.isError && error.status === 409)) { + _context2.next = 15; + break; + } + conflictError = error; + if (!(passwordHash && passwordHash !== conflictError.documentInDb.data.passwordHash)) { + _context2.next = 13; + break; + } + throw newRxError('DB1', { + passwordHash: passwordHash, + existingPasswordHash: conflictError.documentInDb.data.passwordHash + }); + case 13: + storageTokenDocInDb = conflictError.documentInDb; + return _context2.abrupt("return", ensureNotFalsy(storageTokenDocInDb)); + case 15: + throw error; + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _ensureStorageTokenDocumentExists.apply(this, arguments); +} +export function addConnectedStorageToCollection(_x4, _x5, _x6) { + return _addConnectedStorageToCollection.apply(this, arguments); +} + +/** + * returns the primary for a given collection-data + * used in the internal store of a RxDatabase + */ +function _addConnectedStorageToCollection() { + _addConnectedStorageToCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(collection, storageCollectionName, schema) { + var collectionNameWithVersion, collectionDocId, collectionDoc, saveData, alreadyThere; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema); + collectionDocId = getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION); + case 2: + if (!true) { + _context3.next = 23; + break; + } + _context3.next = 5; + return getSingleDocument(collection.database.internalStore, collectionDocId); + case 5: + collectionDoc = _context3.sent; + saveData = clone(ensureNotFalsy(collectionDoc)); + /** + * Add array if not exist for backwards compatibility + * TODO remove this in 2023 + */ + if (!saveData.data.connectedStorages) { + saveData.data.connectedStorages = []; + } + + // do nothing if already in array + alreadyThere = saveData.data.connectedStorages.find(function (row) { + return row.collectionName === storageCollectionName && row.schema.version === schema.version; + }); + if (!alreadyThere) { + _context3.next = 11; + break; + } + return _context3.abrupt("return"); + case 11: + // otherwise add to array and save + saveData.data.connectedStorages.push({ + collectionName: storageCollectionName, + schema: schema + }); + _context3.prev = 12; + _context3.next = 15; + return writeSingle(collection.database.internalStore, { + previous: ensureNotFalsy(collectionDoc), + document: saveData + }, 'add-connected-storage-to-collection'); + case 15: + _context3.next = 21; + break; + case 17: + _context3.prev = 17; + _context3.t0 = _context3["catch"](12); + if (isBulkWriteConflictError(_context3.t0)) { + _context3.next = 21; + break; + } + throw _context3.t0; + case 21: + _context3.next = 2; + break; + case 23: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[12, 17]]); + })); + return _addConnectedStorageToCollection.apply(this, arguments); +} export function _collectionNamePrimary(name, schema) { return name + '-' + schema.version; } diff --git a/dist/es/rx-database-internal-store.js.map b/dist/es/rx-database-internal-store.js.map index 58428868aa3..babdfd95003 100644 --- a/dist/es/rx-database-internal-store.js.map +++ b/dist/es/rx-database-internal-store.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database-internal-store.js","names":["isBulkWriteConflictError","newRxError","fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","getSingleDocument","writeSingle","clone","ensureNotFalsy","fastUnsecureHash","getDefaultRevision","getDefaultRxDocumentMeta","randomCouchString","body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","addConnectedStorageToCollection","collection","storageCollectionName","schema","collectionNameWithVersion","_collectionNamePrimary","name","jsonSchema","collectionDocId","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","database","internalStore","collectionDoc","saveData","data","connectedStorages","alreadyThere","find","row","collectionName","version","push","previous","document","err","ensureStorageTokenDocumentExists","rxDatabase","storageToken","passwordHash","password","undefined","docData","id","STORAGE_TOKEN_DOCUMENT_ID","context","INTERNAL_CONTEXT_STORAGE_TOKEN","key","STORAGE_TOKEN_DOCUMENT_KEY","token","instanceToken","_deleted","_meta","_rev","_attachments","bulkWrite","writeResult","success","error","isError","status","conflictError","documentInDb","existingPasswordHash","storageTokenDocInDb","getAllCollectionDocuments","storageStatics","storageInstance","getAllQueryPrepared","prepareQuery","selector","sort","skip","query","queryResult","allDocs","documents","INTERNAL_STORE_SCHEMA_TITLE","INTERNAL_STORE_SCHEMA","title","primaryKey","fields","separator","type","properties","maxLength","additionalProperties","indexes","required","sharding","shards","mode"],"sources":["../../src/rx-database-internal-store.ts"],"sourcesContent":["import { isBulkWriteConflictError, newRxError } from './rx-error';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from './rx-schema-helper';\nimport { getSingleDocument, writeSingle } from './rx-storage-helper';\nimport type {\n CollectionsOfDatabase,\n InternalStoreCollectionDocType,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorageBulkWriteError,\n RxStorageInstance,\n RxStorageStatics\n} from './types';\nimport {\n clone,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n randomCouchString\n} from './util';\n\nexport const INTERNAL_CONTEXT_COLLECTION = 'collection';\nexport const INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token';\n\n/**\n * Do not change the title,\n * we have to flag the internal schema so that\n * some RxStorage implementations are able\n * to detect if the created RxStorageInstance\n * is from the internals or not,\n * to do some optimizations in some cases.\n */\nexport const INTERNAL_STORE_SCHEMA_TITLE = 'RxInternalDocument';\n\nexport const INTERNAL_STORE_SCHEMA: RxJsonSchema>> = fillWithDefaultSettings({\n version: 0,\n title: INTERNAL_STORE_SCHEMA_TITLE,\n primaryKey: {\n key: 'id',\n fields: [\n 'context',\n 'key'\n ],\n separator: '|'\n },\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 200\n },\n key: {\n type: 'string'\n },\n context: {\n type: 'string',\n enum: [\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_CONTEXT_STORAGE_TOKEN,\n 'OTHER'\n ]\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n indexes: [],\n required: [\n 'key',\n 'context',\n 'data'\n ],\n additionalProperties: false,\n /**\n * If the sharding plugin is used,\n * it must not shard on the internal RxStorageInstance\n * because that one anyway has only a small amount of documents\n * and also its creation is in the hot path of the initial page load,\n * so we should spend less time creating multiple RxStorageInstances.\n */\n sharding: {\n shards: 1,\n mode: 'collection'\n }\n});\n\n\nexport function getPrimaryKeyOfInternalDocument(\n key: string,\n context: string\n): string {\n return getComposedPrimaryKeyOfDocumentData(\n INTERNAL_STORE_SCHEMA,\n {\n key,\n context\n }\n );\n}\n\n/**\n * Returns all internal documents\n * with context 'collection'\n */\nexport async function getAllCollectionDocuments(\n storageStatics: RxStorageStatics,\n storageInstance: RxStorageInstance, any, any>\n): Promise[]> {\n const getAllQueryPrepared = storageStatics.prepareQuery(\n storageInstance.schema,\n {\n selector: {\n context: INTERNAL_CONTEXT_COLLECTION\n },\n sort: [{ id: 'asc' }],\n skip: 0\n }\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n}\n\n/**\n * to not confuse multiInstance-messages with other databases that have the same\n * name and adapter, but do not share state with this one (for example in-memory-instances),\n * we set a storage-token and use it in the broadcast-channel\n */\nexport const STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken';\n\nexport const STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(\n STORAGE_TOKEN_DOCUMENT_KEY,\n INTERNAL_CONTEXT_STORAGE_TOKEN\n);\n\nexport async function ensureStorageTokenDocumentExists(\n rxDatabase: RxDatabase\n): Promise> {\n\n /**\n * To have less read-write cycles,\n * we just try to insert a new document\n * and only fetch the existing one if a conflict happened.\n */\n const storageToken = randomCouchString(10);\n\n const passwordHash = rxDatabase.password ? fastUnsecureHash(rxDatabase.password) : undefined;\n\n const docData: RxDocumentData = {\n id: STORAGE_TOKEN_DOCUMENT_ID,\n context: INTERNAL_CONTEXT_STORAGE_TOKEN,\n key: STORAGE_TOKEN_DOCUMENT_KEY,\n data: {\n token: storageToken,\n /**\n * We add the instance token here\n * to be able to detect if a given RxDatabase instance\n * is the first instance that was ever created\n * or if databases have existed earlier on that storage\n * with the same database name.\n */\n instanceToken: rxDatabase.token,\n passwordHash\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n const writeResult = await rxDatabase.internalStore.bulkWrite(\n [{ document: docData }],\n 'internal-add-storage-token'\n );\n if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) {\n return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID];\n }\n\n /**\n * If we get a 409 error,\n * it means another instance already inserted the storage token.\n * So we get that token from the database and return that one.\n */\n const error = ensureNotFalsy(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]);\n if (\n error.isError &&\n (error as RxStorageBulkWriteError).status === 409\n ) {\n const conflictError = (error as RxStorageBulkWriteError);\n\n\n if (\n passwordHash &&\n passwordHash !== ensureNotFalsy(conflictError.documentInDb).data.passwordHash\n ) {\n throw newRxError('DB1', {\n passwordHash,\n existingPasswordHash: ensureNotFalsy(conflictError.documentInDb).data.passwordHash\n });\n }\n\n const storageTokenDocInDb = conflictError.documentInDb;\n return ensureNotFalsy(storageTokenDocInDb);\n }\n throw error;\n}\n\n\n\n\n\nexport async function addConnectedStorageToCollection(\n collection: RxCollection,\n storageCollectionName: string,\n schema: RxJsonSchema\n) {\n const collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema);\n const collectionDocId = getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n );\n\n while (true) {\n const collectionDoc = await getSingleDocument(\n collection.database.internalStore,\n collectionDocId\n );\n const saveData: RxDocumentData = clone(ensureNotFalsy(collectionDoc));\n /**\n * Add array if not exist for backwards compatibility\n * TODO remove this in 2023\n */\n if (!saveData.data.connectedStorages) {\n saveData.data.connectedStorages = [];\n }\n\n // do nothing if already in array\n const alreadyThere = saveData.data.connectedStorages\n .find(row => row.collectionName === storageCollectionName && row.schema.version === schema.version);\n if (alreadyThere) {\n return;\n }\n\n // otherwise add to array and save\n saveData.data.connectedStorages.push({\n collectionName: storageCollectionName,\n schema\n });\n try {\n await writeSingle(\n collection.database.internalStore,\n {\n previous: ensureNotFalsy(collectionDoc),\n document: saveData\n },\n 'add-connected-storage-to-collection'\n );\n } catch (err) {\n if (!isBulkWriteConflictError(err)) {\n throw err;\n }\n // retry on conflict\n }\n }\n}\n\n\n/**\n * returns the primary for a given collection-data\n * used in the internal store of a RxDatabase\n */\nexport function _collectionNamePrimary(name: string, schema: RxJsonSchema) {\n return name + '-' + schema.version;\n}\n"],"mappings":"AAAA,SAASA,wBAAwB,EAAEC,UAAU,QAAQ,YAAY;AACjE,SACIC,uBAAuB,EACvBC,mCAAmC,QAChC,oBAAoB;AAC3B,SAASC,iBAAiB,EAAEC,WAAW,QAAQ,qBAAqB;AAcpE,SACIC,KAAK,EACLC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,QACd,QAAQ;AAwhBR,gBAAgBC,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd,CAAC,CAzSD;AACA;AACA;AACA;AA/OO,iBAAiBG,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACH,IAAI,EAAE;MAC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AoB,EAAE;IAC1B;EACJ,CAAC;EACDC,OAAO,EAAE,EAAE;EACXC,QAAQ,EAAE,CACN,KAAK,EACL,SAAS,EACT,MAAM,CACT;EACDF,oBAAoB,EAAE,KAAK;EAC3B;AACJ;AACA;AACA;AACA;AACA;AACA;EACIG,QAAQ,EAAE;IACNC,MAAM,EAAE,CAAC;IACTC,IAAI,EAAE;EACV;AACJ,CAAC,CAAC;AAGF,OAAO,SAASxE,+BAA+B,CAC3C4B,GAAW,EACXF,OAAe,EACT;EACN,OAAOxE,mCAAmC,CACtCyG,qBAAqB,EACrB;IACI/B,GAAG,EAAHA,GAAG;IACHF,OAAO,EAAPA;EACJ,CAAC,CACJ;AACL;AA8BA,OAAO,IAAMG,0BAA0B,GAAG,cAAc;AAExD,OAAO,IAAMJ,yBAAyB,GAAGzB,+BAA+B,CACpE6B,0BAA0B,EAC1BF,8BAA8B,CACjC;AA0ID,OAAO,SAAS/B,sBAAsB,CAACC,IAAY,EAAEH,MAAyB,EAAE;EAC5E,OAAOG,IAAI,GAAG,GAAG,GAAGH,MAAM,CAACkB,OAAO;AACtC"} \ No newline at end of file +{"version":3,"file":"rx-database-internal-store.js","names":["isBulkWriteConflictError","newRxError","fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","getSingleDocument","writeSingle","clone","ensureNotFalsy","fastUnsecureHash","getDefaultRevision","getDefaultRxDocumentMeta","randomCouchString","INTERNAL_CONTEXT_COLLECTION","INTERNAL_CONTEXT_STORAGE_TOKEN","INTERNAL_STORE_SCHEMA_TITLE","INTERNAL_STORE_SCHEMA","version","title","primaryKey","key","fields","separator","type","properties","id","maxLength","context","data","additionalProperties","indexes","required","sharding","shards","mode","getPrimaryKeyOfInternalDocument","getAllCollectionDocuments","storageStatics","storageInstance","getAllQueryPrepared","prepareQuery","schema","selector","sort","skip","query","queryResult","allDocs","documents","STORAGE_TOKEN_DOCUMENT_KEY","STORAGE_TOKEN_DOCUMENT_ID","ensureStorageTokenDocumentExists","rxDatabase","storageToken","passwordHash","password","undefined","docData","token","instanceToken","_deleted","_meta","_rev","_attachments","internalStore","bulkWrite","document","writeResult","success","error","isError","status","conflictError","documentInDb","existingPasswordHash","storageTokenDocInDb","addConnectedStorageToCollection","collection","storageCollectionName","collectionNameWithVersion","_collectionNamePrimary","name","jsonSchema","collectionDocId","database","collectionDoc","saveData","connectedStorages","alreadyThere","find","row","collectionName","push","previous"],"sources":["../../src/rx-database-internal-store.ts"],"sourcesContent":["import {\n isBulkWriteConflictError,\n newRxError\n} from './rx-error';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from './rx-schema-helper';\nimport { getSingleDocument, writeSingle } from './rx-storage-helper';\nimport type {\n CollectionsOfDatabase,\n InternalStoreCollectionDocType,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageInstance,\n RxStorageStatics,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n clone,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n randomCouchString\n} from './plugins/utils';\n\nexport const INTERNAL_CONTEXT_COLLECTION = 'collection';\nexport const INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token';\n\n/**\n * Do not change the title,\n * we have to flag the internal schema so that\n * some RxStorage implementations are able\n * to detect if the created RxStorageInstance\n * is from the internals or not,\n * to do some optimizations in some cases.\n */\nexport const INTERNAL_STORE_SCHEMA_TITLE = 'RxInternalDocument';\n\nexport const INTERNAL_STORE_SCHEMA: RxJsonSchema>> = fillWithDefaultSettings({\n version: 0,\n title: INTERNAL_STORE_SCHEMA_TITLE,\n primaryKey: {\n key: 'id',\n fields: [\n 'context',\n 'key'\n ],\n separator: '|'\n },\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 200\n },\n key: {\n type: 'string'\n },\n context: {\n type: 'string',\n enum: [\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_CONTEXT_STORAGE_TOKEN,\n 'OTHER'\n ]\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n indexes: [],\n required: [\n 'key',\n 'context',\n 'data'\n ],\n additionalProperties: false,\n /**\n * If the sharding plugin is used,\n * it must not shard on the internal RxStorageInstance\n * because that one anyway has only a small amount of documents\n * and also its creation is in the hot path of the initial page load,\n * so we should spend less time creating multiple RxStorageInstances.\n */\n sharding: {\n shards: 1,\n mode: 'collection'\n }\n});\n\n\nexport function getPrimaryKeyOfInternalDocument(\n key: string,\n context: string\n): string {\n return getComposedPrimaryKeyOfDocumentData(\n INTERNAL_STORE_SCHEMA,\n {\n key,\n context\n }\n );\n}\n\n/**\n * Returns all internal documents\n * with context 'collection'\n */\nexport async function getAllCollectionDocuments(\n storageStatics: RxStorageStatics,\n storageInstance: RxStorageInstance, any, any>\n): Promise[]> {\n const getAllQueryPrepared = storageStatics.prepareQuery(\n storageInstance.schema,\n {\n selector: {\n context: INTERNAL_CONTEXT_COLLECTION\n },\n sort: [{ id: 'asc' }],\n skip: 0\n }\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n}\n\n/**\n * to not confuse multiInstance-messages with other databases that have the same\n * name and adapter, but do not share state with this one (for example in-memory-instances),\n * we set a storage-token and use it in the broadcast-channel\n */\nexport const STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken';\n\nexport const STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(\n STORAGE_TOKEN_DOCUMENT_KEY,\n INTERNAL_CONTEXT_STORAGE_TOKEN\n);\n\nexport async function ensureStorageTokenDocumentExists(\n rxDatabase: RxDatabase\n): Promise> {\n\n /**\n * To have less read-write cycles,\n * we just try to insert a new document\n * and only fetch the existing one if a conflict happened.\n */\n const storageToken = randomCouchString(10);\n\n const passwordHash = rxDatabase.password ? fastUnsecureHash(rxDatabase.password) : undefined;\n\n const docData: RxDocumentData = {\n id: STORAGE_TOKEN_DOCUMENT_ID,\n context: INTERNAL_CONTEXT_STORAGE_TOKEN,\n key: STORAGE_TOKEN_DOCUMENT_KEY,\n data: {\n token: storageToken,\n /**\n * We add the instance token here\n * to be able to detect if a given RxDatabase instance\n * is the first instance that was ever created\n * or if databases have existed earlier on that storage\n * with the same database name.\n */\n instanceToken: rxDatabase.token,\n passwordHash\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n const writeResult = await rxDatabase.internalStore.bulkWrite(\n [{ document: docData }],\n 'internal-add-storage-token'\n );\n if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) {\n return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID];\n }\n\n /**\n * If we get a 409 error,\n * it means another instance already inserted the storage token.\n * So we get that token from the database and return that one.\n */\n const error = ensureNotFalsy(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]);\n if (\n error.isError &&\n (error as RxStorageWriteError).status === 409\n ) {\n const conflictError = (error as RxStorageWriteErrorConflict);\n\n\n if (\n passwordHash &&\n passwordHash !== conflictError.documentInDb.data.passwordHash\n ) {\n throw newRxError('DB1', {\n passwordHash,\n existingPasswordHash: conflictError.documentInDb.data.passwordHash\n });\n }\n\n const storageTokenDocInDb = conflictError.documentInDb;\n return ensureNotFalsy(storageTokenDocInDb);\n }\n throw error;\n}\n\n\n\n\n\nexport async function addConnectedStorageToCollection(\n collection: RxCollection,\n storageCollectionName: string,\n schema: RxJsonSchema\n) {\n const collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema);\n const collectionDocId = getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n );\n\n while (true) {\n const collectionDoc = await getSingleDocument(\n collection.database.internalStore,\n collectionDocId\n );\n const saveData: RxDocumentData = clone(ensureNotFalsy(collectionDoc));\n /**\n * Add array if not exist for backwards compatibility\n * TODO remove this in 2023\n */\n if (!saveData.data.connectedStorages) {\n saveData.data.connectedStorages = [];\n }\n\n // do nothing if already in array\n const alreadyThere = saveData.data.connectedStorages\n .find(row => row.collectionName === storageCollectionName && row.schema.version === schema.version);\n if (alreadyThere) {\n return;\n }\n\n // otherwise add to array and save\n saveData.data.connectedStorages.push({\n collectionName: storageCollectionName,\n schema\n });\n try {\n await writeSingle(\n collection.database.internalStore,\n {\n previous: ensureNotFalsy(collectionDoc),\n document: saveData\n },\n 'add-connected-storage-to-collection'\n );\n } catch (err) {\n if (!isBulkWriteConflictError(err)) {\n throw err;\n }\n // retry on conflict\n }\n }\n}\n\n\n/**\n * returns the primary for a given collection-data\n * used in the internal store of a RxDatabase\n */\nexport function _collectionNamePrimary(name: string, schema: RxJsonSchema) {\n return name + '-' + schema.version;\n}\n"],"mappings":";;AAAA,SACIA,wBAAwB,EACxBC,UAAU,QACP,YAAY;AACnB,SACIC,uBAAuB,EACvBC,mCAAmC,QAChC,oBAAoB;AAC3B,SAASC,iBAAiB,EAAEC,WAAW,QAAQ,qBAAqB;AAepE,SACIC,KAAK,EACLC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,QACd,iBAAiB;AAExB,OAAO,IAAMC,2BAA2B,GAAG,YAAY;AACvD,OAAO,IAAMC,8BAA8B,GAAG,eAAe;;AAE7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,2BAA2B,GAAG,oBAAoB;AAE/D,OAAO,IAAMC,qBAA8E,GAAGb,uBAAuB,CAAC;EAClHc,OAAO,EAAE,CAAC;EACVC,KAAK,EAAEH,2BAA2B;EAClCI,UAAU,EAAE;IACRC,GAAG,EAAE,IAAI;IACTC,MAAM,EAAE,CACJ,SAAS,EACT,KAAK,CACR;IACDC,SAAS,EAAE;EACf,CAAC;EACDC,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRC,EAAE,EAAE;MACAF,IAAI,EAAE,QAAQ;MACdG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,CAAC1D,IAAI,CAAC2D,iBAAiB,CAC/CE,IAAI,CAAC,UAAAC,GAAG;YAAA,OAAIA,GAAG,CAACC,cAAc,KAAKb,qBAAqB,IAAIY,GAAG,CAACjD,MAAM,CAACxB,OAAO,KAAKwB,MAAM,CAACxB,OAAO;UAAA,EAAC;UAAA,KACnGuE,YAAY;YAAA;YAAA;UAAA;UAAA;QAAA;UAIhB;UACAF,QAAQ,CAAC1D,IAAI,CAAC2D,iBAAiB,CAACK,IAAI,CAAC;YACjCD,cAAc,EAAEb,qBAAqB;YACrCrC,MAAM,EAANA;UACJ,CAAC,CAAC;UAAC;UAAA;UAAA,OAEOnC,WAAW,CACbuE,UAAU,CAACO,QAAQ,CAACpB,aAAa,EACjC;YACI6B,QAAQ,EAAErF,cAAc,CAAC6E,aAAa,CAAC;YACvCnB,QAAQ,EAAEoB;UACd,CAAC,EACD,qCAAqC,CACxC;QAAA;UAAA;UAAA;QAAA;UAAA;UAAA;UAAA,IAEIrF,wBAAwB,cAAK;YAAA;YAAA;UAAA;UAAA;QAAA;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAM7C;EAAA;AAAA;AAOD,OAAO,SAAS+E,sBAAsB,CAACC,IAAY,EAAExC,MAAyB,EAAE;EAC5E,OAAOwC,IAAI,GAAG,GAAG,GAAGxC,MAAM,CAACxB,OAAO;AACtC"} \ No newline at end of file diff --git a/dist/es/rx-database.js b/dist/es/rx-database.js index de8f378f47c..0a86a99c91a 100644 --- a/dist/es/rx-database.js +++ b/dist/es/rx-database.js @@ -1,6 +1,8 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _createClass from "@babel/runtime/helpers/createClass"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { IdleQueue } from 'custom-idle-queue'; -import { pluginMissing, flatClone, PROMISE_RESOLVE_FALSE, randomCouchString, ensureNotFalsy, getDefaultRevision, getDefaultRxDocumentMeta, defaultHashFunction } from './util'; +import { pluginMissing, flatClone, PROMISE_RESOLVE_FALSE, randomCouchString, ensureNotFalsy, getDefaultRevision, getDefaultRxDocumentMeta, defaultHashFunction } from './plugins/utils'; import { newRxError } from './rx-error'; import { createRxSchema } from './rx-schema'; import { runPluginHooks, runAsyncPluginHooks } from './hooks'; @@ -16,93 +18,6 @@ import { removeCollectionStorages } from './rx-collection-helper'; * stores the used database names * so we can throw when the same database is created more then once. */ - -/** - * For better performance some tasks run async - * and are awaited later. - * But we still have to ensure that there have been no errors - * on database creation. - */ -export var ensureNoStartupErrors = function ensureNoStartupErrors(rxDatabase) { - try { - return Promise.resolve(rxDatabase.storageToken).then(function () { - if (rxDatabase.startupErrors[0]) { - throw rxDatabase.startupErrors[0]; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Returns true if the given RxDatabase was the first - * instance that was created on the storage with this name. - * - * Can be used for some optimizations because on the first instantiation, - * we can assume that no data was written before. - */ -export var isRxDatabaseFirstTimeInstantiated = function isRxDatabaseFirstTimeInstantiated(database) { - try { - return Promise.resolve(database.storageTokenDocument).then(function (tokenDoc) { - return tokenDoc.data.instanceToken === database.token; - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Removes the database and all its known data - * with all known collections and all internal meta data. - * - * Returns the names of the removed collections. - */ -export var removeRxDatabase = function removeRxDatabase(databaseName, storage) { - try { - var databaseInstanceToken = randomCouchString(10); - return Promise.resolve(createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, {}, false)).then(function (dbInternalsStorageInstance) { - return Promise.resolve(getAllCollectionDocuments(storage.statics, dbInternalsStorageInstance)).then(function (collectionDocs) { - var collectionNames = new Set(); - collectionDocs.forEach(function (doc) { - return collectionNames.add(doc.data.name); - }); - var removedCollectionNames = Array.from(collectionNames); - return Promise.resolve(Promise.all(removedCollectionNames.map(function (collectionName) { - return removeCollectionStorages(storage, dbInternalsStorageInstance, databaseInstanceToken, databaseName, collectionName); - }))).then(function () { - return Promise.resolve(runAsyncPluginHooks('postRemoveRxDatabase', { - databaseName: databaseName, - storage: storage - })).then(function () { - return Promise.resolve(dbInternalsStorageInstance.remove()).then(function () { - return removedCollectionNames; - }); - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Creates the storage instances that are used internally in the database - * to store schemas and other configuration stuff. - */ -export var createRxDatabaseStorageInstance = function createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, options, multiInstance, password) { - try { - return Promise.resolve(storage.createStorageInstance({ - databaseInstanceToken: databaseInstanceToken, - databaseName: databaseName, - collectionName: INTERNAL_STORAGE_NAME, - schema: INTERNAL_STORE_SCHEMA, - options: options, - multiInstance: multiInstance, - password: password - })); - } catch (e) { - return Promise.reject(e); - } -}; var USED_DATABASE_NAMES = new Set(); var DB_COUNT = 0; export var RxDatabaseBase = /*#__PURE__*/function () { @@ -207,27 +122,45 @@ export var RxDatabaseBase = /*#__PURE__*/function () { /** * removes the collection-doc from the internalStore */; - _proto.removeCollectionDoc = function removeCollectionDoc(name, schema) { - try { - var _this2 = this; - return Promise.resolve(getSingleDocument(_this2.internalStore, getPrimaryKeyOfInternalDocument(_collectionNamePrimary(name, schema), INTERNAL_CONTEXT_COLLECTION))).then(function (doc) { - if (!doc) { - throw newRxError('SNH', { - name: name, - schema: schema - }); + _proto.removeCollectionDoc = + /*#__PURE__*/ + function () { + var _removeCollectionDoc = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(name, schema) { + var doc, writeDoc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return getSingleDocument(this.internalStore, getPrimaryKeyOfInternalDocument(_collectionNamePrimary(name, schema), INTERNAL_CONTEXT_COLLECTION)); + case 2: + doc = _context.sent; + if (doc) { + _context.next = 5; + break; + } + throw newRxError('SNH', { + name: name, + schema: schema + }); + case 5: + writeDoc = flatCloneDocWithMeta(doc); + writeDoc._deleted = true; + _context.next = 9; + return this.internalStore.bulkWrite([{ + document: writeDoc, + previous: doc + }], 'rx-database-remove-collection'); + case 9: + case "end": + return _context.stop(); } - var writeDoc = flatCloneDocWithMeta(doc); - writeDoc._deleted = true; - return Promise.resolve(_this2.internalStore.bulkWrite([{ - document: writeDoc, - previous: doc - }], 'rx-database-remove-collection')).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + }, _callee, this); + })); + function removeCollectionDoc(_x, _x2) { + return _removeCollectionDoc.apply(this, arguments); } - } + return removeCollectionDoc; + }() /** * creates multiple RxCollections at once * to be much faster by saving db txs and doing stuff in bulk-operations @@ -235,111 +168,146 @@ export var RxDatabaseBase = /*#__PURE__*/function () { * So it must be as fast as possible. */ ; - _proto.addCollections = function addCollections(collectionCreators) { - try { - var _this3 = this; - var jsonSchemas = {}; - var schemas = {}; - var bulkPutDocs = []; - var useArgsByCollectionName = {}; - Object.entries(collectionCreators).forEach(function (_ref) { - var name = _ref[0], - args = _ref[1]; - var collectionName = name; - var rxJsonSchema = args.schema; - jsonSchemas[collectionName] = rxJsonSchema; - var schema = createRxSchema(rxJsonSchema); - schemas[collectionName] = schema; - - // collection already exists - if (_this3.collections[name]) { - throw newRxError('DB3', { - name: name - }); - } - var collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema); - var collectionDocData = { - id: getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION), - key: collectionNameWithVersion, - context: INTERNAL_CONTEXT_COLLECTION, - data: { - name: collectionName, - schemaHash: schema.hash, - schema: schema.jsonSchema, - version: schema.version, - connectedStorages: [] - }, - _deleted: false, - _meta: getDefaultRxDocumentMeta(), - _rev: getDefaultRevision(), - _attachments: {} - }; - bulkPutDocs.push({ - document: collectionDocData - }); - var useArgs = Object.assign({}, args, { - name: collectionName, - schema: schema, - database: _this3 - }); + _proto.addCollections = + /*#__PURE__*/ + function () { + var _addCollections = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(collectionCreators) { + var _this2 = this; + var jsonSchemas, schemas, bulkPutDocs, useArgsByCollectionName, putDocsResult, ret; + return _regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + jsonSchemas = {}; + schemas = {}; + bulkPutDocs = []; + useArgsByCollectionName = {}; + Object.entries(collectionCreators).forEach(function (_ref) { + var name = _ref[0], + args = _ref[1]; + var collectionName = name; + var rxJsonSchema = args.schema; + jsonSchemas[collectionName] = rxJsonSchema; + var schema = createRxSchema(rxJsonSchema); + schemas[collectionName] = schema; - // run hooks - var hookData = flatClone(args); - hookData.database = _this3; - hookData.name = name; - runPluginHooks('preCreateRxCollection', hookData); - useArgs.conflictHandler = hookData.conflictHandler; - useArgsByCollectionName[collectionName] = useArgs; - }); - return Promise.resolve(_this3.internalStore.bulkWrite(bulkPutDocs, 'rx-database-add-collection')).then(function (putDocsResult) { - return Promise.resolve(ensureNoStartupErrors(_this3)).then(function () { - Object.entries(putDocsResult.error).forEach(function (_ref2) { - var _id = _ref2[0], - error = _ref2[1]; - var docInDb = ensureNotFalsy(error.documentInDb); - var collectionName = docInDb.data.name; - var schema = schemas[collectionName]; - // collection already exists but has different schema - if (docInDb.data.schemaHash !== schema.hash) { - throw newRxError('DB6', { - database: _this3.name, - collection: collectionName, - previousSchemaHash: docInDb.data.schemaHash, - schemaHash: schema.hash, - previousSchema: docInDb.data.schema, - schema: ensureNotFalsy(jsonSchemas[collectionName]) + // collection already exists + if (_this2.collections[name]) { + throw newRxError('DB3', { + name: name + }); + } + var collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema); + var collectionDocData = { + id: getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION), + key: collectionNameWithVersion, + context: INTERNAL_CONTEXT_COLLECTION, + data: { + name: collectionName, + schemaHash: schema.hash, + schema: schema.jsonSchema, + version: schema.version, + connectedStorages: [] + }, + _deleted: false, + _meta: getDefaultRxDocumentMeta(), + _rev: getDefaultRevision(), + _attachments: {} + }; + bulkPutDocs.push({ + document: collectionDocData }); - } - }); - var ret = {}; - return Promise.resolve(Promise.all(Object.keys(collectionCreators).map(function (collectionName) { - try { - var useArgs = useArgsByCollectionName[collectionName]; - return Promise.resolve(createRxCollection(useArgs)).then(function (collection) { - ret[collectionName] = collection; - - // set as getter to the database - _this3.collections[collectionName] = collection; - if (!_this3[collectionName]) { - Object.defineProperty(_this3, collectionName, { - get: function get() { - return _this3.collections[collectionName]; - } - }); - } + var useArgs = Object.assign({}, args, { + name: collectionName, + schema: schema, + database: _this2 }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + + // run hooks + var hookData = flatClone(args); + hookData.database = _this2; + hookData.name = name; + runPluginHooks('preCreateRxCollection', hookData); + useArgs.conflictHandler = hookData.conflictHandler; + useArgsByCollectionName[collectionName] = useArgs; + }); + _context3.next = 7; + return this.internalStore.bulkWrite(bulkPutDocs, 'rx-database-add-collection'); + case 7: + putDocsResult = _context3.sent; + _context3.next = 10; + return ensureNoStartupErrors(this); + case 10: + Object.entries(putDocsResult.error).forEach(function (_ref2) { + var _id = _ref2[0], + error = _ref2[1]; + if (error.status !== 409) { + throw newRxError('DB12', { + database: _this2.name, + writeError: error + }); + } + var docInDb = ensureNotFalsy(error.documentInDb); + var collectionName = docInDb.data.name; + var schema = schemas[collectionName]; + // collection already exists but has different schema + if (docInDb.data.schemaHash !== schema.hash) { + throw newRxError('DB6', { + database: _this2.name, + collection: collectionName, + previousSchemaHash: docInDb.data.schemaHash, + schemaHash: schema.hash, + previousSchema: docInDb.data.schema, + schema: ensureNotFalsy(jsonSchemas[collectionName]) + }); + } + }); + ret = {}; + _context3.next = 14; + return Promise.all(Object.keys(collectionCreators).map( /*#__PURE__*/function () { + var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(collectionName) { + var useArgs, collection; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + useArgs = useArgsByCollectionName[collectionName]; + _context2.next = 3; + return createRxCollection(useArgs); + case 3: + collection = _context2.sent; + ret[collectionName] = collection; + + // set as getter to the database + _this2.collections[collectionName] = collection; + if (!_this2[collectionName]) { + Object.defineProperty(_this2, collectionName, { + get: function get() { + return _this2.collections[collectionName]; + } + }); + } + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 14: + return _context3.abrupt("return", ret); + case 15: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function addCollections(_x3) { + return _addCollections.apply(this, arguments); } - } + return addCollections; + }() /** * runs the given function between idleQueue-locking */ @@ -367,9 +335,6 @@ export var RxDatabaseBase = /*#__PURE__*/function () { _proto.importJSON = function importJSON(_exportedJSON) { throw pluginMissing('json-dump'); }; - _proto.serverCouchDB = function serverCouchDB(_options) { - throw pluginMissing('server-couchdb'); - }; _proto.backup = function backup(_options) { throw pluginMissing('backup'); }; @@ -392,69 +357,90 @@ export var RxDatabaseBase = /*#__PURE__*/function () { /** * destroys the database-instance and all collections */; - _proto.destroy = function destroy() { - try { - var _this4 = this; - if (_this4.destroyed) { - return Promise.resolve(PROMISE_RESOLVE_FALSE); - } - - // settings destroyed = true must be the first thing to do. - _this4.destroyed = true; - return Promise.resolve(runAsyncPluginHooks('preDestroyRxDatabase', _this4)).then(function () { - /** - * Complete the event stream - * to stop all subscribers who forgot to unsubscribe. - */ - _this4.eventBulks$.complete(); - DB_COUNT--; - _this4._subs.map(function (sub) { - return sub.unsubscribe(); - }); + _proto.destroy = + /*#__PURE__*/ + function () { + var _destroy = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() { + var _this3 = this; + return _regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!this.destroyed) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", PROMISE_RESOLVE_FALSE); + case 2: + // settings destroyed = true must be the first thing to do. + this.destroyed = true; + _context4.next = 5; + return runAsyncPluginHooks('preDestroyRxDatabase', this); + case 5: + /** + * Complete the event stream + * to stop all subscribers who forgot to unsubscribe. + */ + this.eventBulks$.complete(); + DB_COUNT--; + this._subs.map(function (sub) { + return sub.unsubscribe(); + }); - /** - * Destroying the pseudo instance will throw - * because stulff is missing - * TODO we should not need the pseudo instance on runtime. - * we should generate the property list on build time. - */ - return _this4.name === 'pseudoInstance' ? PROMISE_RESOLVE_FALSE : _this4.requestIdlePromise().then(function () { - return Promise.all(_this4.onDestroy.map(function (fn) { - return fn(); - })); - }) - // destroy all collections - .then(function () { - return Promise.all(Object.keys(_this4.collections).map(function (key) { - return _this4.collections[key]; - }).map(function (col) { - return col.destroy(); - })); - }) - // destroy internal storage instances - .then(function () { - return _this4.internalStore.close(); - }) - // remove combination from USED_COMBINATIONS-map - .then(function () { - return USED_DATABASE_NAMES["delete"](_this4.name); - }).then(function () { - return true; - }); - }); - } catch (e) { - return Promise.reject(e); + /** + * Destroying the pseudo instance will throw + * because stulff is missing + * TODO we should not need the pseudo instance on runtime. + * we should generate the property list on build time. + */ + if (!(this.name === 'pseudoInstance')) { + _context4.next = 10; + break; + } + return _context4.abrupt("return", PROMISE_RESOLVE_FALSE); + case 10: + return _context4.abrupt("return", this.requestIdlePromise().then(function () { + return Promise.all(_this3.onDestroy.map(function (fn) { + return fn(); + })); + }) + // destroy all collections + .then(function () { + return Promise.all(Object.keys(_this3.collections).map(function (key) { + return _this3.collections[key]; + }).map(function (col) { + return col.destroy(); + })); + }) + // destroy internal storage instances + .then(function () { + return _this3.internalStore.close(); + }) + // remove combination from USED_COMBINATIONS-map + .then(function () { + return USED_DATABASE_NAMES["delete"](_this3.name); + }).then(function () { + return true; + })); + case 11: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function destroy() { + return _destroy.apply(this, arguments); } - } + return destroy; + }() /** * deletes the database and its stored data. * Returns the names of all removed collections. */ ; _proto.remove = function remove() { - var _this5 = this; + var _this4 = this; return this.destroy().then(function () { - return removeRxDatabase(_this5.name, _this5.storage); + return removeRxDatabase(_this4.name, _this4.storage); }); }; _createClass(RxDatabaseBase, [{ @@ -485,26 +471,61 @@ function throwIfDatabaseNameUsed(name) { }); } } -export function createRxDatabase(_ref3) { - var storage = _ref3.storage, - instanceCreationOptions = _ref3.instanceCreationOptions, - name = _ref3.name, - password = _ref3.password, - _ref3$multiInstance = _ref3.multiInstance, - multiInstance = _ref3$multiInstance === void 0 ? true : _ref3$multiInstance, - _ref3$eventReduce = _ref3.eventReduce, - eventReduce = _ref3$eventReduce === void 0 ? false : _ref3$eventReduce, - _ref3$ignoreDuplicate = _ref3.ignoreDuplicate, - ignoreDuplicate = _ref3$ignoreDuplicate === void 0 ? false : _ref3$ignoreDuplicate, - _ref3$options = _ref3.options, - options = _ref3$options === void 0 ? {} : _ref3$options, - cleanupPolicy = _ref3.cleanupPolicy, - _ref3$allowSlowCount = _ref3.allowSlowCount, - allowSlowCount = _ref3$allowSlowCount === void 0 ? false : _ref3$allowSlowCount, - _ref3$localDocuments = _ref3.localDocuments, - localDocuments = _ref3$localDocuments === void 0 ? false : _ref3$localDocuments, - _ref3$hashFunction = _ref3.hashFunction, - hashFunction = _ref3$hashFunction === void 0 ? defaultHashFunction : _ref3$hashFunction; + +/** + * Creates the storage instances that are used internally in the database + * to store schemas and other configuration stuff. + */ +export function createRxDatabaseStorageInstance(_x5, _x6, _x7, _x8, _x9, _x10) { + return _createRxDatabaseStorageInstance.apply(this, arguments); +} +function _createRxDatabaseStorageInstance() { + _createRxDatabaseStorageInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(databaseInstanceToken, storage, databaseName, options, multiInstance, password) { + var internalStore; + return _regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return storage.createStorageInstance({ + databaseInstanceToken: databaseInstanceToken, + databaseName: databaseName, + collectionName: INTERNAL_STORAGE_NAME, + schema: INTERNAL_STORE_SCHEMA, + options: options, + multiInstance: multiInstance, + password: password + }); + case 2: + internalStore = _context5.sent; + return _context5.abrupt("return", internalStore); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _createRxDatabaseStorageInstance.apply(this, arguments); +} +export function createRxDatabase(_ref4) { + var storage = _ref4.storage, + instanceCreationOptions = _ref4.instanceCreationOptions, + name = _ref4.name, + password = _ref4.password, + _ref4$multiInstance = _ref4.multiInstance, + multiInstance = _ref4$multiInstance === void 0 ? true : _ref4$multiInstance, + _ref4$eventReduce = _ref4.eventReduce, + eventReduce = _ref4$eventReduce === void 0 ? false : _ref4$eventReduce, + _ref4$ignoreDuplicate = _ref4.ignoreDuplicate, + ignoreDuplicate = _ref4$ignoreDuplicate === void 0 ? false : _ref4$ignoreDuplicate, + _ref4$options = _ref4.options, + options = _ref4$options === void 0 ? {} : _ref4$options, + cleanupPolicy = _ref4.cleanupPolicy, + _ref4$allowSlowCount = _ref4.allowSlowCount, + allowSlowCount = _ref4$allowSlowCount === void 0 ? false : _ref4$allowSlowCount, + _ref4$localDocuments = _ref4.localDocuments, + localDocuments = _ref4$localDocuments === void 0 ? false : _ref4$localDocuments, + _ref4$hashFunction = _ref4.hashFunction, + hashFunction = _ref4$hashFunction === void 0 ? defaultHashFunction : _ref4$hashFunction; runPluginHooks('preCreateRxDatabase', { storage: storage, instanceCreationOptions: instanceCreationOptions, @@ -551,10 +572,124 @@ export function createRxDatabase(_ref3) { }); }); } + +/** + * Removes the database and all its known data + * with all known collections and all internal meta data. + * + * Returns the names of the removed collections. + */ +export function removeRxDatabase(_x11, _x12) { + return _removeRxDatabase.apply(this, arguments); +} +function _removeRxDatabase() { + _removeRxDatabase = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(databaseName, storage) { + var databaseInstanceToken, dbInternalsStorageInstance, collectionDocs, collectionNames, removedCollectionNames; + return _regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + databaseInstanceToken = randomCouchString(10); + _context6.next = 3; + return createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, {}, false); + case 3: + dbInternalsStorageInstance = _context6.sent; + _context6.next = 6; + return getAllCollectionDocuments(storage.statics, dbInternalsStorageInstance); + case 6: + collectionDocs = _context6.sent; + collectionNames = new Set(); + collectionDocs.forEach(function (doc) { + return collectionNames.add(doc.data.name); + }); + removedCollectionNames = Array.from(collectionNames); + _context6.next = 12; + return Promise.all(removedCollectionNames.map(function (collectionName) { + return removeCollectionStorages(storage, dbInternalsStorageInstance, databaseInstanceToken, databaseName, collectionName); + })); + case 12: + _context6.next = 14; + return runAsyncPluginHooks('postRemoveRxDatabase', { + databaseName: databaseName, + storage: storage + }); + case 14: + _context6.next = 16; + return dbInternalsStorageInstance.remove(); + case 16: + return _context6.abrupt("return", removedCollectionNames); + case 17: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _removeRxDatabase.apply(this, arguments); +} export function isRxDatabase(obj) { return obj instanceof RxDatabaseBase; } export function dbCount() { return DB_COUNT; } + +/** + * Returns true if the given RxDatabase was the first + * instance that was created on the storage with this name. + * + * Can be used for some optimizations because on the first instantiation, + * we can assume that no data was written before. + */ +export function isRxDatabaseFirstTimeInstantiated(_x13) { + return _isRxDatabaseFirstTimeInstantiated.apply(this, arguments); +} + +/** + * For better performance some tasks run async + * and are awaited later. + * But we still have to ensure that there have been no errors + * on database creation. + */ +function _isRxDatabaseFirstTimeInstantiated() { + _isRxDatabaseFirstTimeInstantiated = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(database) { + var tokenDoc; + return _regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return database.storageTokenDocument; + case 2: + tokenDoc = _context7.sent; + return _context7.abrupt("return", tokenDoc.data.instanceToken === database.token); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return _isRxDatabaseFirstTimeInstantiated.apply(this, arguments); +} +export function ensureNoStartupErrors(_x14) { + return _ensureNoStartupErrors.apply(this, arguments); +} +function _ensureNoStartupErrors() { + _ensureNoStartupErrors = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(rxDatabase) { + return _regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return rxDatabase.storageToken; + case 2: + if (!rxDatabase.startupErrors[0]) { + _context8.next = 4; + break; + } + throw rxDatabase.startupErrors[0]; + case 4: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + return _ensureNoStartupErrors.apply(this, arguments); +} //# sourceMappingURL=rx-database.js.map \ No newline at end of file diff --git a/dist/es/rx-database.js.map b/dist/es/rx-database.js.map index e5f0035b505..cdd2defab5c 100644 --- a/dist/es/rx-database.js.map +++ b/dist/es/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashFunction","newRxError","createRxSchema","runPluginHooks","runAsyncPluginHooks","Subject","mergeMap","createRxCollection","flatCloneDocWithMeta","getSingleDocument","getWrappedStorageInstance","INTERNAL_STORAGE_NAME","ObliviousSet","ensureStorageTokenDocumentExists","getAllCollectionDocuments","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","INTERNAL_STORE_SCHEMA","_collectionNamePrimary","removeCollectionStorages","ensureNoStartupErrors","rxDatabase","storageToken","startupErrors","isRxDatabaseFirstTimeInstantiated","database","storageTokenDocument","tokenDoc","data","instanceToken","token","removeRxDatabase","databaseName","storage","databaseInstanceToken","createRxDatabaseStorageInstance","dbInternalsStorageInstance","statics","collectionDocs","collectionNames","Set","forEach","doc","add","name","removedCollectionNames","Array","from","Promise","all","map","collectionName","remove","options","multiInstance","password","createStorageInstance","schema","USED_DATABASE_NAMES","DB_COUNT","RxDatabaseBase","instanceCreationOptions","eventReduce","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","_subs","onDestroy","destroyed","collections","eventBulks$","observable$","pipe","changeEventBulk","events","emittedEventBulkIds","asRxDatabase","err","push","then","$emit","has","id","next","removeCollectionDoc","writeDoc","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","args","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","hookData","conflictHandler","putDocsResult","error","_id","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","importJSON","_exportedJSON","serverCouchDB","_options","backup","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","complete","sub","unsubscribe","col","close","throwIfDatabaseNameUsed","link","createRxDatabase","ignoreDuplicate","localDocuments","storageInstance","creator","isRxDatabase","obj","dbCount"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n CouchDBServerOptions,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n AllMigrationStates,\n CouchDBServerResponse,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashFunction\n} from './util';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store';\nimport { removeCollectionStorages } from './rx-collection-helper';\n\n/**\n * stores the used database names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Beceause having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n Object.entries(collectionCreators).forEach(([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this,\n\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n });\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, error]) => {\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n });\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n serverCouchDB(_options?: CouchDBServerOptions): Promise {\n throw pluginMissing('server-couchdb');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stulff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashFunction\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n > {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name);\n }\n USED_DATABASE_NAMES.add(name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";AAAA,SAASA,SAAS,QAAQ,mBAAmB;AAiC7C,SACIC,aAAa,EACbC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,mBAAmB,QAChB,QAAQ;AACf,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QAEX,aAAa;AACpB,SACIC,cAAc,EACdC,mBAAmB,QAChB,SAAS;AAChB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,iBAAiB;AACxB,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAClB,qBAAqB;AAE5B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,E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AAc,EAAdA;MACJ;IACJ,CAAC,CAAC,CAAC1E,IAAI,CAAC;MAAA,OAAM5D,UAAU;IAAA,EAAC;EAC7B,CAAC,CAAC;AACV;AAiDA,OAAO,SAASyI,YAAY,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYnG,cAAc;AACxC;AAEA,OAAO,SAASoG,OAAO,GAAW;EAC9B,OAAOrG,QAAQ;AACnB"} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashFunction","newRxError","createRxSchema","runPluginHooks","runAsyncPluginHooks","Subject","mergeMap","createRxCollection","flatCloneDocWithMeta","getSingleDocument","getWrappedStorageInstance","INTERNAL_STORAGE_NAME","ObliviousSet","ensureStorageTokenDocumentExists","getAllCollectionDocuments","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","INTERNAL_STORE_SCHEMA","_collectionNamePrimary","removeCollectionStorages","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","_subs","startupErrors","onDestroy","destroyed","collections","eventBulks$","observable$","pipe","changeEventBulk","events","storageToken","storageTokenDocument","emittedEventBulkIds","asRxDatabase","err","push","then","doc","data","$emit","has","id","add","next","removeCollectionDoc","schema","writeDoc","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","forEach","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","database","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","_id","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","Promise","all","keys","map","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","complete","sub","unsubscribe","col","close","remove","removeRxDatabase","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","createRxDatabase","ignoreDuplicate","localDocuments","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","statics","collectionDocs","collectionNames","removedCollectionNames","Array","from","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n AllMigrationStates,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashFunction\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store';\nimport { removeCollectionStorages } from './rx-collection-helper';\n\n/**\n * stores the used database names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Beceause having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n Object.entries(collectionCreators).forEach(([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n });\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, error]) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n });\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stulff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashFunction\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n> {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name);\n }\n USED_DATABASE_NAMES.add(name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";;;AAAA,SAASA,SAAS,QAAQ,mBAAmB;AA+B7C,SACIC,aAAa,EACbC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,mBAAmB,QAChB,iBAAiB;AACxB,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QAEX,aAAa;AACpB,SACIC,cAAc,EACdC,mBAAmB,QAChB,SAAS;AAChB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,iBAAiB;AACxB,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAClB,qBAAqB;AAE5B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,EACzBC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,qBAAqB,EACrBC,sBAAsB,QACnB,8BAA8B;AACrC,SAASC,wBAAwB,QAAQ,wBAAwB;;AAEjE;AACA;AACA;AACA;AACA,IAAMC,mBAAgC,GAAG,IAAIC,GAAG,EAAE;AAElD,IAAIC,QAAQ,GAAG,CAAC;AAEhB,WAAaC,cAAc;EAQvB,wBACoBC,IAAY;EAC5B;AACR;AACA;AACA;EACwBC,KAAa,EACbC,OAAsD,EACtDC,uBAAgD,EAChDC,QAAa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AAOA,GAAG,YAAYtI,cAAc;AACxC;AAEA,OAAO,SAASuI,OAAO,GAAW;EAC9B,OAAOxI,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAsByI,iCAAiC;EAAA;AAAA;;AAQvD;AACA;AACA;AACA;AACA;AACA;AALA;EAAA,8FARO,kBACHjE,QAAoB;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEGA,QAAQ,CAAC9C,oBAAoB;QAAA;UAA9CgH,QAAQ;UAAA,kCACPA,QAAQ,CAACzG,IAAI,CAAC0G,aAAa,KAAKnE,QAAQ,CAACrE,KAAK;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACxD;EAAA;AAAA;AASD,gBAAsByE,qBAAqB;EAAA;AAAA;AAO1C;EAAA,kFAPM,kBACHiD,UAAyC;IAAA;MAAA;QAAA;UAAA;UAAA,OAEnCA,UAAU,CAACpG,YAAY;QAAA;UAAA,KACzBoG,UAAU,CAAC7G,aAAa,CAAC,CAAC,CAAC;YAAA;YAAA;UAAA;UAAA,MACrB6G,UAAU,CAAC7G,aAAa,CAAC,CAAC,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAExC;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/es/rx-document-prototype-merge.js b/dist/es/rx-document-prototype-merge.js index cd0aa1cbb6c..deeeeae93d2 100644 --- a/dist/es/rx-document-prototype-merge.js +++ b/dist/es/rx-document-prototype-merge.js @@ -10,47 +10,41 @@ import { createRxDocumentConstructor, basePrototype, createWithConstructor as createRxDocumentWithConstructor } from './rx-document'; import { runPluginHooks } from './hooks'; import { overwritable } from './overwritable'; - -// caches -var protoForCollection = new WeakMap(); var constructorForCollection = new WeakMap(); export function getDocumentPrototype(rxCollection) { - if (!protoForCollection.has(rxCollection)) { - var schemaProto = rxCollection.schema.getDocumentPrototype(); - var ormProto = getDocumentOrmPrototype(rxCollection); - var baseProto = basePrototype; - var proto = {}; - [schemaProto, ormProto, baseProto].forEach(function (obj) { - var props = Object.getOwnPropertyNames(obj); - props.forEach(function (key) { - var desc = Object.getOwnPropertyDescriptor(obj, key); + var schemaProto = rxCollection.schema.getDocumentPrototype(); + var ormProto = getDocumentOrmPrototype(rxCollection); + var baseProto = basePrototype; + var proto = {}; + [schemaProto, ormProto, baseProto].forEach(function (obj) { + var props = Object.getOwnPropertyNames(obj); + props.forEach(function (key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); - /** - * When enumerable is true, it will show on console.dir(instance) - * To not pollute the output, only getters and methods are enumerable - */ - var enumerable = true; - if (key.startsWith('_') || key.endsWith('_') || key.startsWith('$') || key.endsWith('$')) enumerable = false; - if (typeof desc.value === 'function') { - // when getting a function, we automatically do a .bind(this) - Object.defineProperty(proto, key, { - get: function get() { - return desc.value.bind(this); - }, - enumerable: enumerable, - configurable: false - }); - } else { - desc.enumerable = enumerable; - desc.configurable = false; - if (desc.writable) desc.writable = false; - Object.defineProperty(proto, key, desc); - } - }); + /** + * When enumerable is true, it will show on console.dir(instance) + * To not pollute the output, only getters and methods are enumerable + */ + var enumerable = true; + if (key.startsWith('_') || key.endsWith('_') || key.startsWith('$') || key.endsWith('$')) enumerable = false; + if (typeof desc.value === 'function') { + // when getting a function, we automatically do a .bind(this) + Object.defineProperty(proto, key, { + get: function get() { + return desc.value.bind(this); + }, + enumerable: enumerable, + configurable: false + }); + } else { + desc.enumerable = enumerable; + desc.configurable = false; + if (desc.writable) desc.writable = false; + Object.defineProperty(proto, key, desc); + } }); - protoForCollection.set(rxCollection, proto); - } - return protoForCollection.get(rxCollection); + }); + return proto; } export function getRxDocumentConstructor(rxCollection) { if (!constructorForCollection.has(rxCollection)) { @@ -63,33 +57,16 @@ export function getRxDocumentConstructor(rxCollection) { /** * Create a RxDocument-instance from the jsonData * and the prototype merge. - * If the document already exists in the _docCache, - * return that instead to ensure we have no duplicates. + * You should never call this method directly, + * instead you should get the document from collection._docCache.getCachedRxDocument(). */ -export function createRxDocument(rxCollection, docData) { - var primary = docData[rxCollection.schema.primaryPath]; - - // return from cache if exists - var cacheDoc = rxCollection._docCache.get(primary); - if (cacheDoc) { - return cacheDoc; - } +export function createNewRxDocument(rxCollection, docData) { var doc = createRxDocumentWithConstructor(getRxDocumentConstructor(rxCollection), rxCollection, overwritable.deepFreezeWhenDevMode(docData)); - rxCollection._docCache.set(primary, doc); rxCollection._runHooksSync('post', 'create', docData, doc); runPluginHooks('postCreateRxDocument', doc); return doc; } -/** - * create RxDocument from the docs-array - */ -export function createRxDocuments(rxCollection, docsJSON) { - return docsJSON.map(function (json) { - return createRxDocument(rxCollection, json); - }); -} - /** * returns the prototype-object * that contains the orm-methods, diff --git a/dist/es/rx-document-prototype-merge.js.map b/dist/es/rx-document-prototype-merge.js.map index e55b684e8ba..d2064d711c7 100644 --- a/dist/es/rx-document-prototype-merge.js.map +++ b/dist/es/rx-document-prototype-merge.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-document-prototype-merge.js","names":["createRxDocumentConstructor","basePrototype","createWithConstructor","createRxDocumentWithConstructor","runPluginHooks","overwritable","protoForCollection","WeakMap","constructorForCollection","getDocumentPrototype","rxCollection","has","schemaProto","schema","ormProto","getDocumentOrmPrototype","baseProto","proto","forEach","obj","props","Object","getOwnPropertyNames","key","desc","getOwnPropertyDescriptor","enumerable","startsWith","endsWith","value","defineProperty","get","bind","configurable","writable","set","getRxDocumentConstructor","ret","createRxDocument","docData","primary","primaryPath","cacheDoc","_docCache","doc","deepFreezeWhenDevMode","_runHooksSync","createRxDocuments","docsJSON","map","json","entries","methods","k","v"],"sources":["../../src/rx-document-prototype-merge.ts"],"sourcesContent":["/**\n * For the ORM capabilities,\n * we have to merge the document prototype\n * with the ORM functions and the data\n * We do this iterating over the properties and\n * adding them to a new object.\n * In the future we should do this by chaining the __proto__ objects\n */\n\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n createRxDocumentConstructor,\n basePrototype,\n createWithConstructor as createRxDocumentWithConstructor\n} from './rx-document';\nimport {\n runPluginHooks\n} from './hooks';\nimport { overwritable } from './overwritable';\n\n// caches\nconst protoForCollection: WeakMap = new WeakMap();\nconst constructorForCollection: WeakMap = new WeakMap();\n\nexport function getDocumentPrototype(\n rxCollection: RxCollection\n): any {\n if (!protoForCollection.has(rxCollection)) {\n const schemaProto = rxCollection.schema.getDocumentPrototype();\n const ormProto = getDocumentOrmPrototype(rxCollection);\n const baseProto = basePrototype;\n const proto = {};\n [\n schemaProto,\n ormProto,\n baseProto\n ].forEach(obj => {\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(key => {\n const desc: any = Object.getOwnPropertyDescriptor(obj, key);\n\n\n /**\n * When enumerable is true, it will show on console.dir(instance)\n * To not pollute the output, only getters and methods are enumerable\n */\n let enumerable = true;\n if (\n key.startsWith('_') ||\n key.endsWith('_') ||\n key.startsWith('$') ||\n key.endsWith('$')\n ) enumerable = false;\n\n if (typeof desc.value === 'function') {\n // when getting a function, we automatically do a .bind(this)\n Object.defineProperty(proto, key, {\n get() {\n return desc.value.bind(this);\n },\n enumerable,\n configurable: false\n });\n\n } else {\n desc.enumerable = enumerable;\n desc.configurable = false;\n if (desc.writable)\n desc.writable = false;\n Object.defineProperty(proto, key, desc);\n }\n });\n });\n protoForCollection.set(rxCollection, proto);\n\n }\n return protoForCollection.get(rxCollection);\n}\n\nexport function getRxDocumentConstructor(\n rxCollection: RxCollection\n) {\n if (!constructorForCollection.has(rxCollection)) {\n const ret = createRxDocumentConstructor(\n getDocumentPrototype(rxCollection)\n );\n constructorForCollection.set(rxCollection, ret);\n }\n return constructorForCollection.get(rxCollection);\n}\n\n/**\n * Create a RxDocument-instance from the jsonData\n * and the prototype merge.\n * If the document already exists in the _docCache,\n * return that instead to ensure we have no duplicates.\n */\nexport function createRxDocument(\n rxCollection: RxCollection,\n docData: RxDocumentData\n): RxDocument {\n const primary: string = docData[rxCollection.schema.primaryPath] as any;\n\n // return from cache if exists\n const cacheDoc = rxCollection._docCache.get(primary);\n if (cacheDoc) {\n return cacheDoc as any;\n }\n\n const doc = createRxDocumentWithConstructor(\n getRxDocumentConstructor(rxCollection as any),\n rxCollection as any,\n overwritable.deepFreezeWhenDevMode(docData as any)\n );\n\n rxCollection._docCache.set(primary, doc as any);\n rxCollection._runHooksSync('post', 'create', docData, doc);\n runPluginHooks('postCreateRxDocument', doc);\n return doc as any;\n}\n\n/**\n * create RxDocument from the docs-array\n */\nexport function createRxDocuments(\n rxCollection: RxCollection,\n docsJSON: any[]\n): RxDocument[] {\n return docsJSON.map(\n json => createRxDocument(rxCollection as any, json)\n );\n}\n\n/**\n * returns the prototype-object\n * that contains the orm-methods,\n * used in the proto-merge\n */\nexport function getDocumentOrmPrototype(rxCollection: RxCollection): any {\n const proto: any = {};\n Object\n .entries(rxCollection.methods)\n .forEach(([k, v]) => {\n proto[k] = v;\n });\n return proto;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SACIA,2BAA2B,EAC3BC,aAAa,EACbC,qBAAqB,IAAIC,+BAA+B,QACrD,eAAe;AACtB,SACIC,cAAc,QACX,SAAS;AAChB,SAASC,YAAY,QAAQ,gBAAgB;;AAE7C;AACA,IAAMC,kBAA8C,GAAG,IAAIC,OAAO,EAAE;AACpE,IAAMC,wBAAoD,GAAG,IAAID,OAAO,EAAE;AAE1E,OAAO,SAASE,oBAAoB,CAChCC,YAA0B,EACvB;EACH,IAAI,CAACJ,kBAAkB,CAACK,GAAG,CAACD,YAAY,CAAC,EAAE;IACvC,IAAME,WAAW,GAAGF,YAAY,CAACG,MAAM,CAACJ,oBAAoB,EAAE;IAC9D,IAAMK,QAAQ,GAAGC,uBAAuB,CAACL,YAAY,CAAC;IACtD,IAAMM,SAAS,GAAGf,aAAa;IAC/B,IAAMgB,KAAK,GAAG,CAAC,CAAC;IAChB,CACIL,WAAW,EACXE,QAAQ,EACRE,SAAS,CACZ,CAACE,OAAO,CAAC,UAAAC,GAAG,EAAI;MACb,IAAMC,KA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D8B,OAAO,CAACzC,YAAY,CAAC0C,OAAO,CAAC,CAC7BlC,OAAO,CAAC,gBAAY;IAAA,IAAVmC,CAAC;MAAEC,CAAC;IACXrC,KAAK,CAACoC,CAAC,CAAC,GAAGC,CAAC;EAChB,CAAC,CAAC;EACN,OAAOrC,KAAK;AAChB"} \ No newline at end of file +{"version":3,"file":"rx-document-prototype-merge.js","names":["createRxDocumentConstructor","basePrototype","createWithConstructor","createRxDocumentWithConstructor","runPluginHooks","overwritable","constructorForCollection","WeakMap","getDocumentPrototype","rxCollection","schemaProto","schema","ormProto","getDocumentOrmPrototype","baseProto","proto","forEach","obj","props","Object","getOwnPropertyNames","key","desc","getOwnPropertyDescriptor","enumerable","startsWith","endsWith","value","defineProperty","get","bind","configurable","writable","getRxDocumentConstructor","has","ret","set","createNewRxDocument","docData","doc","deepFreezeWhenDevMode","_runHooksSync","entries","methods","k","v"],"sources":["../../src/rx-document-prototype-merge.ts"],"sourcesContent":["/**\n * For the ORM capabilities,\n * we have to merge the document prototype\n * with the ORM functions and the data\n * We do this iterating over the properties and\n * adding them to a new object.\n * In the future we should do this by chaining the __proto__ objects\n */\n\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n createRxDocumentConstructor,\n basePrototype,\n createWithConstructor as createRxDocumentWithConstructor\n} from './rx-document';\nimport {\n runPluginHooks\n} from './hooks';\nimport { overwritable } from './overwritable';\n\nconst constructorForCollection = new WeakMap();\n\nexport function getDocumentPrototype(\n rxCollection: RxCollection\n): any {\n const schemaProto = rxCollection.schema.getDocumentPrototype();\n const ormProto = getDocumentOrmPrototype(rxCollection);\n const baseProto = basePrototype;\n const proto = {};\n [\n schemaProto,\n ormProto,\n baseProto\n ].forEach(obj => {\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(key => {\n const desc: any = Object.getOwnPropertyDescriptor(obj, key);\n\n\n /**\n * When enumerable is true, it will show on console.dir(instance)\n * To not pollute the output, only getters and methods are enumerable\n */\n let enumerable = true;\n if (\n key.startsWith('_') ||\n key.endsWith('_') ||\n key.startsWith('$') ||\n key.endsWith('$')\n ) enumerable = false;\n\n if (typeof desc.value === 'function') {\n // when getting a function, we automatically do a .bind(this)\n Object.defineProperty(proto, key, {\n get() {\n return desc.value.bind(this);\n },\n enumerable,\n configurable: false\n });\n\n } else {\n desc.enumerable = enumerable;\n desc.configurable = false;\n if (desc.writable)\n desc.writable = false;\n Object.defineProperty(proto, key, desc);\n }\n });\n });\n return proto;\n}\n\nexport function getRxDocumentConstructor(\n rxCollection: RxCollection\n) {\n if (!constructorForCollection.has(rxCollection)) {\n const ret = createRxDocumentConstructor(\n getDocumentPrototype(rxCollection)\n );\n constructorForCollection.set(rxCollection, ret);\n }\n return constructorForCollection.get(rxCollection);\n}\n\n/**\n * Create a RxDocument-instance from the jsonData\n * and the prototype merge.\n * You should never call this method directly,\n * instead you should get the document from collection._docCache.getCachedRxDocument().\n */\nexport function createNewRxDocument(\n rxCollection: RxCollection,\n docData: RxDocumentData\n): RxDocument {\n const doc = createRxDocumentWithConstructor(\n getRxDocumentConstructor(rxCollection),\n rxCollection as any,\n overwritable.deepFreezeWhenDevMode(docData as any)\n );\n rxCollection._runHooksSync('post', 'create', docData, doc);\n runPluginHooks('postCreateRxDocument', doc);\n return doc as any;\n}\n\n\n/**\n * returns the prototype-object\n * that contains the orm-methods,\n * used in the proto-merge\n */\nexport function getDocumentOrmPrototype(rxCollection: RxCollection): any {\n const proto: any = {};\n Object\n .entries(rxCollection.methods)\n .forEach(([k, v]) => {\n proto[k] = v;\n });\n return proto;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SACIA,2BAA2B,EAC3BC,aAAa,EACbC,qBAAqB,IAAIC,+BAA+B,QACrD,eAAe;AACtB,SACIC,cAAc,QACX,SAAS;AAChB,SAASC,YAAY,QAAQ,gBAAgB;AAE7C,IAAMC,wBAAwB,GAAG,IAAIC,OAAO,EAAE;AAE9C,OAAO,SAASC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,KAAK,EAAEM,GAAG,EAAEC,IAAI,CAAC;MAC3C;IACJ,CAAC,CAAC;EACN,CAAC,CAAC;EACF,OAAOP,KAAK;AAChB;AAEA,OAAO,SAASkB,wBAAwB,CACpCxB,YAA0C,EAC5C;EACE,IAAI,CAACH,wBAAwB,CAAC4B,GAAG,CAACzB,YAAY,CAAC,EAAE;IAC7C,IAAM0B,GAAG,GAAGnC,2BAA2B,CACnCQ,oBAAoB,CAACC,YAAY,CAAC,CACrC;IACDH,wBAAwB,CAAC8B,GAAG,CAAC3B,YAAY,EAAE0B,GAAG,CAAC;EACnD;EACA,OAAO7B,wBAAwB,CAACuB,GAAG,CAACpB,YAAY,CAAC;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS4B,mBAAmB,CAC/B5B,YAA0C,EAC1C6B,OAAkC,EACR;EAC1B,IAAMC,GAAG,GAAGpC,+BAA+B,CACvC8B,wBAAwB,CAACxB,YAAY,CAAC,EACtCA,YAAY,EACZJ,YAAY,CAACmC,qBAAqB,CAACF,OAAO,CAAQ,CACrD;EACD7B,YAAY,CAACgC,aAAa,CAAC,MAAM,EAAE,QAAQ,EAAEH,OAAO,EAAEC,GAAG,CAAC;EAC1DnC,cAAc,CAAC,sBAAsB,EAAEmC,GAAG,CAAC;EAC3C,OAAOA,GAAG;AACd;;AAGA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS1B,uBAAuB,CAACJ,YAA0B,EAAO;EACrE,IAAMM,KAAU,GAAG,CAAC,CAAC;EACrBI,MAAM,CACDuB,OAAO,CAACjC,YAAY,CAACkC,OAAO,CAAC,CAC7B3B,OAAO,CAAC,gBAAY;IAAA,IAAV4B,CAAC;MAAEC,CAAC;IACX9B,KAAK,CAAC6B,CAAC,CAAC,GAAGC,CAAC;EAChB,CAAC,CAAC;EACN,OAAO9B,KAAK;AAChB"} \ No newline at end of file diff --git a/dist/es/rx-document.js b/dist/es/rx-document.js index 1fa75691240..1d2ff384a8c 100644 --- a/dist/es/rx-document.js +++ b/dist/es/rx-document.js @@ -1,190 +1,16 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import objectPath from 'object-path'; -import { BehaviorSubject } from 'rxjs'; -import { distinctUntilChanged, map } from 'rxjs/operators'; -import { clone, trimDots, getHeightOfRevision, pluginMissing, flatClone, PROMISE_RESOLVE_NULL, PROMISE_RESOLVE_VOID, ensureNotFalsy } from './util'; -import { newRxError, isBulkWriteConflictError } from './rx-error'; +import { distinctUntilChanged, filter, map, shareReplay, startWith } from 'rxjs/operators'; +import { clone, trimDots, pluginMissing, flatClone, PROMISE_RESOLVE_NULL, RXJS_SHARE_REPLAY_DEFAULTS, getFromObjectOrThrow } from './plugins/utils'; +import { newRxError } from './rx-error'; import { runPluginHooks } from './hooks'; import { getDocumentDataOfRxChangeEvent } from './rx-change-event'; import { overwritable } from './overwritable'; import { getSchemaByObjectPath } from './rx-schema-helper'; import { throwIfIsStorageWriteError } from './rx-storage-helper'; -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} +import { modifierFromPublicToInternal } from './incremental-write'; export var basePrototype = { - /** - * TODO - * instead of appliying the _this-hack - * we should make these accessors functions instead of getters. - */ - get _data() { - var _this = this; - /** - * Might be undefined when vuejs-devtools are used - * @link https://github.com/pubkey/rxdb/issues/1126 - */ - if (!_this.isInstanceOfRxDocument) { - return undefined; - } - return _this._dataSync$.getValue(); - }, get primaryPath() { var _this = this; if (!_this.isInstanceOfRxDocument) { @@ -211,7 +37,7 @@ export var basePrototype = { if (!_this.isInstanceOfRxDocument) { return undefined; } - return _this._dataSync$.pipe(map(function (d) { + return _this.$.pipe(map(function (d) { return d._deleted; })); }, @@ -222,62 +48,54 @@ export var basePrototype = { } return _this._data._deleted; }, + getLatest: function getLatest() { + var latestDocData = this.collection._docCache.getLatestDocumentData(this.primary); + return this.collection._docCache.getCachedRxDocument(latestDocData); + }, /** * returns the observable which emits the plain-data of this document */ get $() { + var _this2 = this; var _this = this; - return _this._dataSync$.asObservable().pipe(map(function (docData) { - return overwritable.deepFreezeWhenDevMode(docData); - })); - }, - _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) { - return; - } - - // ensure that new _rev is higher then current - var docData = getDocumentDataOfRxChangeEvent(changeEvent); - var newRevNr = getHeightOfRevision(docData._rev); - var currentRevNr = getHeightOfRevision(this._data._rev); - if (currentRevNr > newRevNr) return; - switch (changeEvent.operation) { - case 'INSERT': - break; - case 'UPDATE': - this._dataSync$.next(changeEvent.documentData); - break; - case 'DELETE': - // remove from docCache to assure new upserted RxDocuments will be a new instance - this.collection._docCache["delete"](this.primary); - this._dataSync$.next(changeEvent.documentData); - break; - } + return _this.collection.$.pipe(filter(function (changeEvent) { + return !changeEvent.isLocal; + }), filter(function (changeEvent) { + return changeEvent.documentId === _this2.primary; + }), map(function (changeEvent) { + return getDocumentDataOfRxChangeEvent(changeEvent); + }), startWith(_this.collection._docCache.getLatestDocumentData(this.primary)), distinctUntilChanged(function (prev, curr) { + return prev._rev === curr._rev; + }), shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)); }, /** * returns observable of the value of the given path */ get$: function get$(path) { - if (path.includes('.item.')) { - throw newRxError('DOC1', { - path: path - }); - } - if (path === this.primaryPath) throw newRxError('DOC2'); + if (overwritable.isDevMode()) { + if (path.includes('.item.')) { + throw newRxError('DOC1', { + path: path + }); + } + if (path === this.primaryPath) { + throw newRxError('DOC2'); + } - // final fields cannot be modified and so also not observed - if (this.collection.schema.finalFields.includes(path)) { - throw newRxError('DOC3', { - path: path - }); - } - var schemaObj = getSchemaByObjectPath(this.collection.schema.jsonSchema, path); - if (!schemaObj) { - throw newRxError('DOC4', { - path: path - }); + // final fields cannot be modified and so also not observed + if (this.collection.schema.finalFields.includes(path)) { + throw newRxError('DOC3', { + path: path + }); + } + var schemaObj = getSchemaByObjectPath(this.collection.schema.jsonSchema, path); + if (!schemaObj) { + throw newRxError('DOC4', { + path: path + }); + } } - return this._dataSync$.pipe(map(function (data) { + return this.$.pipe(map(function (data) { return objectPath.get(data, path); }), distinctUntilChanged()); }, @@ -310,7 +128,7 @@ export var basePrototype = { }); } if (schemaObj.type === 'array') { - return refCollection.findByIds(value).then(function (res) { + return refCollection.findByIds(value).exec().then(function (res) { var valuesIterator = res.values(); return Array.from(valuesIterator); }); @@ -363,6 +181,9 @@ export var basePrototype = { update: function update(_updateObj) { throw pluginMissing('update'); }, + incrementalUpdate: function incrementalUpdate(_updateObj) { + throw pluginMissing('update'); + }, updateCRDT: function updateCRDT(_updateObj) { throw pluginMissing('crdt'); }, @@ -378,82 +199,61 @@ export var basePrototype = { get allAttachments$() { throw pluginMissing('attachments'); }, + modify: function () { + var _modify = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(mutationFunction, + // used by some plugins that wrap the method + _context) { + var oldData, newData; + return _regeneratorRuntime.wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + oldData = this._data; + _context2.next = 3; + return modifierFromPublicToInternal(mutationFunction)(oldData); + case 3: + newData = _context2.sent; + return _context2.abrupt("return", this._saveData(newData, oldData)); + case 5: + case "end": + return _context2.stop(); + } + }, _callee, this); + })); + function modify(_x, _x2) { + return _modify.apply(this, arguments); + } + return modify; + }(), /** - * runs an atomic update over the document + * runs an incremental update over the document * @param function that takes the document-data and returns a new data-object */ - atomicUpdate: function atomicUpdate(mutationFunction, + incrementalModify: function incrementalModify(mutationFunction, // used by some plugins that wrap the method _context) { - var _this2 = this; - return new Promise(function (res, rej) { - _this2._atomicQueue = _this2._atomicQueue.then(function () { - try { - var _temp5 = function _temp5(_result3) { - if (_exit) return _result3; - res(_this2); - }; - var _exit = false; - var done = false; - // we need a hacky while loop to stay incide the chain-link of _atomicQueue - // while still having the option to run a retry on conflicts - var _temp4 = _for(function () { - return !_exit && !done; - }, void 0, function () { - function _temp3(_result) { - if (_exit) return _result; - var _temp = _catch(function () { - return Promise.resolve(_this2._saveData(newData, oldData)).then(function () { - done = true; - }); - }, function (err) { - var useError = err.parameters && err.parameters.error ? err.parameters.error : err; - /** - * conflicts cannot happen by just using RxDB in one process - * There are two ways they still can appear which is - * replication and multi-tab usage - * Because atomicUpdate has a mutation function, - * we can just re-run the mutation until there is no conflict - */ - var isConflict = isBulkWriteConflictError(useError); - if (isConflict) {} else { - rej(useError); - _exit = true; - } - }); - if (_temp && _temp.then) return _temp.then(function () {}); - } - var oldData = _this2._dataSync$.getValue(); - // always await because mutationFunction might be async - var newData; - var _temp2 = _catch(function () { - return Promise.resolve(mutationFunction(clone(oldData), _this2)).then(function (_mutationFunction) { - newData = _mutationFunction; - if (_this2.collection) { - newData = _this2.collection.schema.fillObjectWithDefaults(newData); - } - }); - }, function (err) { - rej(err); - _exit = true; - }); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }); + var _this3 = this; + return this.collection.incrementalWriteQueue.addWrite(this._data, modifierFromPublicToInternal(mutationFunction)).then(function (result) { + return _this3.collection._docCache.getCachedRxDocument(result); }); }, + patch: function patch(_patch) { + var oldData = this._data; + var newData = clone(oldData); + Object.entries(_patch).forEach(function (_ref) { + var k = _ref[0], + v = _ref[1]; + newData[k] = v; + }); + return this._saveData(newData, oldData); + }, /** * patches the given properties */ - atomicPatch: function atomicPatch(patch) { - return this.atomicUpdate(function (docData) { - Object.entries(patch).forEach(function (_ref) { - var k = _ref[0], - v = _ref[1]; + incrementalPatch: function incrementalPatch(patch) { + return this.incrementalModify(function (docData) { + Object.entries(patch).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; docData[k] = v; }); return docData; @@ -463,49 +263,55 @@ export var basePrototype = { * saves the new document-data * and handles the events */ - _saveData: function _saveData(newData, oldData) { - try { - var _this3 = this; - newData = flatClone(newData); + _saveData: function () { + var _saveData2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(newData, oldData) { + var writeResult, isError; + return _regeneratorRuntime.wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + newData = flatClone(newData); - // deleted documents cannot be changed - if (_this3._data._deleted) { - throw newRxError('DOC11', { - id: _this3.primary, - document: _this3 - }); - } - - /** - * Meta values must always be merged - * instead of overwritten. - * This ensures that different plugins do not overwrite - * each others meta properties. - */ - newData._meta = Object.assign({}, oldData._meta, newData._meta); - - // ensure modifications are ok - if (overwritable.isDevMode()) { - _this3.collection.schema.validateChange(oldData, newData); - } - return Promise.resolve(_this3.collection._runHooks('pre', 'save', newData, _this3)).then(function () { - return Promise.resolve(_this3.collection.storageInstance.bulkWrite([{ - previous: oldData, - document: newData - }], 'rx-document-save-data')).then(function (writeResult) { - var isError = writeResult.error[_this3.primary]; - throwIfIsStorageWriteError(_this3.collection, _this3.primary, newData, isError); - return _this3.collection._runHooks('post', 'save', newData, _this3); - }); - }); - } catch (e) { - return Promise.reject(e); + // deleted documents cannot be changed + if (!this._data._deleted) { + _context3.next = 3; + break; + } + throw newRxError('DOC11', { + id: this.primary, + document: this + }); + case 3: + _context3.next = 5; + return beforeDocumentUpdateWrite(this.collection, newData, oldData); + case 5: + _context3.next = 7; + return this.collection.storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }], 'rx-document-save-data'); + case 7: + writeResult = _context3.sent; + isError = writeResult.error[this.primary]; + throwIfIsStorageWriteError(this.collection, this.primary, newData, isError); + _context3.next = 12; + return this.collection._runHooks('post', 'save', newData, this); + case 12: + return _context3.abrupt("return", this.collection._docCache.getCachedRxDocument(getFromObjectOrThrow(writeResult.success, this.primary))); + case 13: + case "end": + return _context3.stop(); + } + }, _callee2, this); + })); + function _saveData(_x3, _x4) { + return _saveData2.apply(this, arguments); } - }, + return _saveData; + }(), /** - * remove the document, - * this not not equal to a pouchdb.remove(), - * instead we keep the values and only set _deleted: true + * Remove the document. + * Notice that there is no hard delete, + * instead deleted documents get flagged with _deleted=true. */ remove: function remove() { var _this4 = this; @@ -517,38 +323,87 @@ export var basePrototype = { })); } var deletedData = flatClone(this._data); - return collection._runHooks('pre', 'remove', deletedData, this).then(function () { - try { - deletedData._deleted = true; - return Promise.resolve(collection.storageInstance.bulkWrite([{ - previous: _this4._data, - document: deletedData - }], 'rx-document-remove')).then(function (writeResult) { - var isError = writeResult.error[_this4.primary]; - throwIfIsStorageWriteError(collection, _this4.primary, deletedData, isError); - return ensureNotFalsy(writeResult.success[_this4.primary]); - }); - } catch (e) { - return Promise.reject(e); - } - }).then(function () { + var removedDocData; + return collection._runHooks('pre', 'remove', deletedData, this).then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() { + var writeResult, isError; + return _regeneratorRuntime.wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + deletedData._deleted = true; + _context4.next = 3; + return collection.storageInstance.bulkWrite([{ + previous: _this4._data, + document: deletedData + }], 'rx-document-remove'); + case 3: + writeResult = _context4.sent; + isError = writeResult.error[_this4.primary]; + throwIfIsStorageWriteError(collection, _this4.primary, deletedData, isError); + return _context4.abrupt("return", getFromObjectOrThrow(writeResult.success, _this4.primary)); + case 7: + case "end": + return _context4.stop(); + } + }, _callee3); + }))).then(function (removed) { + removedDocData = removed; return _this4.collection._runHooks('post', 'remove', deletedData, _this4); }).then(function () { - return _this4; + return _this4.collection._docCache.getCachedRxDocument(removedDocData); }); }, + incrementalRemove: function incrementalRemove() { + var _this5 = this; + return this.incrementalModify( /*#__PURE__*/function () { + var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(docData) { + return _regeneratorRuntime.wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5.collection._runHooks('pre', 'remove', docData, _this5); + case 2: + docData._deleted = true; + return _context5.abrupt("return", docData); + case 4: + case "end": + return _context5.stop(); + } + }, _callee4); + })); + return function (_x5) { + return _ref4.apply(this, arguments); + }; + }()).then( /*#__PURE__*/function () { + var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(newDoc) { + return _regeneratorRuntime.wrap(function _callee5$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return _this5.collection._runHooks('post', 'remove', newDoc._data, newDoc); + case 2: + return _context6.abrupt("return", newDoc); + case 3: + case "end": + return _context6.stop(); + } + }, _callee5); + })); + return function (_x6) { + return _ref5.apply(this, arguments); + }; + }()); + }, destroy: function destroy() { throw newRxError('DOC14'); } }; export function createRxDocumentConstructor() { var proto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : basePrototype; - var constructor = function RxDocumentConstructor(collection, jsonData) { + var constructor = function RxDocumentConstructor(collection, docData) { this.collection = collection; // assume that this is always equal to the doc-data in the database - this._dataSync$ = new BehaviorSubject(jsonData); - this._atomicQueue = PROMISE_RESOLVE_VOID; + this._data = docData; /** * because of the prototype-merge, @@ -609,10 +464,6 @@ export function defineGetterSetter(schema, valueObj) { }); } export function createWithConstructor(constructor, collection, jsonData) { - var primary = jsonData[collection.schema.primaryPath]; - if (primary && primary.startsWith('_design')) { - return null; - } var doc = new constructor(collection, jsonData); runPluginHooks('createRxDocument', doc); return doc; @@ -621,4 +472,19 @@ export function isRxDocument(obj) { if (typeof obj === 'undefined') return false; return !!obj.isInstanceOfRxDocument; } +export function beforeDocumentUpdateWrite(collection, newData, oldData) { + /** + * Meta values must always be merged + * instead of overwritten. + * This ensures that different plugins do not overwrite + * each others meta properties. + */ + newData._meta = Object.assign({}, oldData._meta, newData._meta); + + // ensure modifications are ok + if (overwritable.isDevMode()) { + collection.schema.validateChange(oldData, newData); + } + return collection._runHooks('pre', 'save', newData); +} //# sourceMappingURL=rx-document.js.map \ No newline at end of file diff --git a/dist/es/rx-document.js.map b/dist/es/rx-document.js.map index 65c581f916d..9415ed62eb5 100644 --- a/dist/es/rx-document.js.map +++ b/dist/es/rx-document.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-document.js","names":["objectPath","BehaviorSubject","distinctUntilChanged","map","clone","trimDots","getHeightOfRevision","pluginMissing","flatClone","PROMISE_RESOLVE_NULL","PROMISE_RESOLVE_VOID","ensureNotFalsy","newRxError","isBulkWriteConflictError","runPluginHooks","getDocumentDataOfRxChangeEvent","overwritable","getSchemaByObjectPath","throwIfIsStorageWriteError","body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","basePrototype","_data","isInstanceOfRxDocument","undefined","_dataSync$","getValue","primaryPath","collection","schema","primary","revision","_rev","deleted$","pipe","d","_deleted","deleted","$","asObservable","docData","deepFreezeWhenDevMode","_handleChangeEvent","changeEvent","documentId","newRevNr","currentRevNr","operation","next","documentData","_docCache","get$","path","includes","finalFields","schemaObj","jsonSchema","data","get","populate","ref","refCollection","database","collections","type","findByIds","res","valuesIterator","values","Array","from","findOne","exec","objPath","valueObj","isArray","defineGetterSetter","toJSON","withMetaFields","_attachments","_meta","toMutableJSON","_updateObj","updateCRDT","putAttachment","getAttachment","allAttachments","allAttachments$","atomicUpdate","mutationFunction","_context","Promise","rej","_atomicQueue","done","_saveData","newData","oldData","err","useError","parameters","error","isConflict","fillObjectWithDefaults","atomicPatch","patch","Object","entries","forEach","k","id","document","assign","isDevMode","validateChange","_runHooks","storageInstance","bulkWrite","previous","writeResult","isError","remove","deletedData","success","destroy","createRxDocumentConstructor","proto","constructor","RxDocumentConstructor","jsonData","thisObj","pathProperties","properties","keys","key","fullPath","__defineGetter__","ret","defineProperty","enumerable","configurable","__defineSetter__","val","set","createWithConstructor","startsWith","doc","isRxDocument","obj"],"sources":["../../src/rx-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport {\n Observable,\n BehaviorSubject\n} from 'rxjs';\nimport {\n distinctUntilChanged,\n map\n} from 'rxjs/operators';\nimport {\n clone,\n trimDots,\n getHeightOfRevision,\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_NULL,\n PROMISE_RESOLVE_VOID,\n ensureNotFalsy\n} from './util';\nimport {\n newRxError,\n isBulkWriteConflictError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\n\nimport type {\n RxDocument,\n RxCollection,\n RxDocumentData,\n RxDocumentWriteData,\n RxChangeEvent,\n UpdateQuery,\n CRDTEntry\n} from './types';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\nimport { overwritable } from './overwritable';\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport { throwIfIsStorageWriteError } from './rx-storage-helper';\n\nexport const basePrototype = {\n\n /**\n * TODO\n * instead of appliying the _this-hack\n * we should make these accessors functions instead of getters.\n */\n get _data() {\n const _this: RxDocument = this as any;\n /**\n * Might be undefined when vuejs-devtools are used\n * @link https://github.com/pubkey/rxdb/issues/1126\n */\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n\n return _this._dataSync$.getValue();\n },\n get primaryPath() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this.collection.schema.primaryPath;\n },\n get primary() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return (_this._data as any)[_this.primaryPath];\n },\n get revision() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._rev;\n },\n get deleted$() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._dataSync$.pipe(\n map((d: any) => d._deleted)\n );\n },\n get deleted() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._deleted;\n },\n\n /**\n * returns the observable which emits the plain-data of this document\n */\n get $(): Observable {\n const _this: RxDocument = this as any;\n return _this._dataSync$.asObservable().pipe(\n map(docData => overwritable.deepFreezeWhenDevMode(docData))\n );\n },\n\n _handleChangeEvent(this: RxDocument, changeEvent: RxChangeEvent) {\n if (changeEvent.documentId !== this.primary) {\n return;\n }\n\n // ensure that new _rev is higher then current\n const docData = getDocumentDataOfRxChangeEvent(changeEvent);\n const newRevNr = getHeightOfRevision(docData._rev);\n const currentRevNr = getHeightOfRevision(this._data._rev);\n if (currentRevNr > newRevNr) return;\n\n switch (changeEvent.operation) {\n case 'INSERT':\n break;\n case 'UPDATE':\n this._dataSync$.next(changeEvent.documentData);\n break;\n case 'DELETE':\n // remove from docCache to assure new upserted RxDocuments will be a new instance\n this.collection._docCache.delete(this.primary);\n this._dataSync$.next(changeEvent.documentData);\n break;\n }\n },\n\n /**\n * returns observable of the value of the given path\n */\n get$(this: RxDocument, path: string): Observable {\n if (path.includes('.item.')) {\n throw newRxError('DOC1', {\n path\n });\n }\n\n if (path === this.primaryPath)\n throw newRxError('DOC2');\n\n // final fields cannot be modified and so also not observed\n if (this.collection.schema.finalFields.includes(path)) {\n throw newRxError('DOC3', {\n path\n });\n }\n\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n if (!schemaObj) {\n throw newRxError('DOC4', {\n path\n });\n }\n\n return this._dataSync$\n .pipe(\n map(data => objectPath.get(data, path)),\n distinctUntilChanged()\n );\n },\n\n /**\n * populate the given path\n */\n populate(this: RxDocument, path: string): Promise {\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n const value = this.get(path);\n if (!value) {\n return PROMISE_RESOLVE_NULL;\n }\n if (!schemaObj) {\n throw newRxError('DOC5', {\n path\n });\n }\n if (!schemaObj.ref) {\n throw newRxError('DOC6', {\n path,\n schemaObj\n });\n }\n\n const refCollection: RxCollection = this.collection.database.collections[schemaObj.ref];\n if (!refCollection) {\n throw newRxError('DOC7', {\n ref: schemaObj.ref,\n path,\n schemaObj\n });\n }\n\n if (schemaObj.type === 'array') {\n return refCollection.findByIds(value).then(res => {\n const valuesIterator = res.values();\n return Array.from(valuesIterator) as any;\n });\n } else {\n return refCollection.findOne(value).exec();\n }\n },\n\n /**\n * get data by objectPath\n */\n get(this: RxDocument, objPath: string): any | null {\n if (!this._data) return undefined;\n let valueObj = objectPath.get(this._data, objPath);\n\n // direct return if array or non-object\n if (\n typeof valueObj !== 'object' ||\n Array.isArray(valueObj)\n ) {\n return overwritable.deepFreezeWhenDevMode(valueObj);\n }\n\n /**\n * TODO find a way to deep-freeze together with defineGetterSetter\n * so we do not have to do a deep clone here.\n */\n valueObj = clone(valueObj);\n defineGetterSetter(\n this.collection.schema,\n valueObj,\n objPath,\n this as any\n );\n return valueObj;\n },\n\n toJSON(this: RxDocument, withMetaFields = false) {\n if (!withMetaFields) {\n const data = flatClone(this._data);\n delete (data as any)._rev;\n delete (data as any)._attachments;\n delete (data as any)._deleted;\n delete (data as any)._meta;\n return overwritable.deepFreezeWhenDevMode(data);\n } else {\n return overwritable.deepFreezeWhenDevMode(this._data);\n }\n },\n toMutableJSON(this: RxDocument, withMetaFields = false) {\n return clone(this.toJSON(withMetaFields as any));\n },\n\n /**\n * updates document\n * @overwritten by plugin (optional)\n * @param updateObj mongodb-like syntax\n */\n update(_updateObj: UpdateQuery) {\n throw pluginMissing('update');\n },\n updateCRDT(_updateObj: CRDTEntry | CRDTEntry[]) {\n throw pluginMissing('crdt');\n },\n putAttachment() {\n throw pluginMissing('attachments');\n },\n getAttachment() {\n throw pluginMissing('attachments');\n },\n allAttachments() {\n throw pluginMissing('attachments');\n },\n get allAttachments$() {\n throw pluginMissing('attachments');\n },\n\n\n /**\n * runs an atomic update over the document\n * @param function that takes the document-data and returns a new data-object\n */\n atomicUpdate(\n this: RxDocument,\n mutationFunction: Function,\n // used by some plugins that wrap the method\n _context?: string\n ): Promise {\n return new Promise((res, rej) => {\n this._atomicQueue = this\n ._atomicQueue\n .then(async () => {\n let done = false;\n // we need a hacky while loop to stay incide the chain-link of _atomicQueue\n // while still having the option to run a retry on conflicts\n while (!done) {\n const oldData = this._dataSync$.getValue();\n // always await because mutationFunction might be async\n let newData;\n\n try {\n newData = await mutationFunction(\n clone(oldData),\n this\n );\n if (this.collection) {\n newData = this.collection.schema.fillObjectWithDefaults(newData);\n }\n } catch (err) {\n rej(err);\n return;\n }\n\n try {\n await this._saveData(newData, oldData);\n done = true;\n } catch (err: any) {\n const useError = err.parameters && err.parameters.error ? err.parameters.error : err;\n /**\n * conflicts cannot happen by just using RxDB in one process\n * There are two ways they still can appear which is\n * replication and multi-tab usage\n * Because atomicUpdate has a mutation function,\n * we can just re-run the mutation until there is no conflict\n */\n const isConflict = isBulkWriteConflictError(useError as any);\n if (isConflict) {\n // conflict error -> retrying\n } else {\n rej(useError);\n return;\n }\n }\n }\n res(this);\n });\n });\n },\n\n\n /**\n * patches the given properties\n */\n atomicPatch(\n this: RxDocument,\n patch: Partial\n ): Promise> {\n return this.atomicUpdate((docData: RxDocumentType) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n (docData as any)[k] = v;\n });\n return docData;\n });\n },\n\n /**\n * saves the new document-data\n * and handles the events\n */\n async _saveData(\n this: RxDocument,\n newData: RxDocumentWriteData,\n oldData: RxDocumentData\n ): Promise {\n newData = flatClone(newData);\n\n // deleted documents cannot be changed\n if (this._data._deleted) {\n throw newRxError('DOC11', {\n id: this.primary,\n document: this\n });\n }\n\n /**\n * Meta values must always be merged\n * instead of overwritten.\n * This ensures that different plugins do not overwrite\n * each others meta properties.\n */\n newData._meta = Object.assign(\n {},\n oldData._meta,\n newData._meta\n );\n\n // ensure modifications are ok\n if (overwritable.isDevMode()) {\n this.collection.schema.validateChange(oldData, newData);\n }\n\n await this.collection._runHooks('pre', 'save', newData, this);\n\n const writeResult = await this.collection.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'rx-document-save-data');\n\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(this.collection, this.primary, newData, isError);\n\n return this.collection._runHooks('post', 'save', newData, this);\n },\n\n /**\n * remove the document,\n * this not not equal to a pouchdb.remove(),\n * instead we keep the values and only set _deleted: true\n */\n remove(this: RxDocument): Promise {\n const collection = this.collection;\n if (this.deleted) {\n return Promise.reject(newRxError('DOC13', {\n document: this,\n id: this.primary\n }));\n }\n\n const deletedData = flatClone(this._data);\n return collection._runHooks('pre', 'remove', deletedData, this)\n .then(async () => {\n deletedData._deleted = true;\n\n const writeResult = await collection.storageInstance.bulkWrite([{\n previous: this._data,\n document: deletedData\n }], 'rx-document-remove');\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(collection, this.primary, deletedData, isError);\n return ensureNotFalsy(writeResult.success[this.primary]);\n })\n .then(() => {\n return this.collection._runHooks('post', 'remove', deletedData, this);\n })\n .then(() => this);\n },\n destroy() {\n throw newRxError('DOC14');\n }\n};\n\nexport function createRxDocumentConstructor(proto = basePrototype) {\n const constructor = function RxDocumentConstructor(\n this: RxDocument,\n collection: RxCollection,\n jsonData: any\n ) {\n this.collection = collection;\n\n // assume that this is always equal to the doc-data in the database\n this._dataSync$ = new BehaviorSubject(jsonData);\n\n this._atomicQueue = PROMISE_RESOLVE_VOID;\n\n /**\n * because of the prototype-merge,\n * we can not use the native instanceof operator\n */\n this.isInstanceOfRxDocument = true;\n };\n constructor.prototype = proto;\n return constructor;\n}\n\nexport function defineGetterSetter(\n schema: any,\n valueObj: any,\n objPath = '',\n thisObj = false\n) {\n if (valueObj === null) return;\n\n\n let pathProperties = getSchemaByObjectPath(\n schema.jsonSchema,\n objPath\n );\n\n if (typeof pathProperties === 'undefined') return;\n if (pathProperties.properties) pathProperties = pathProperties.properties;\n\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = trimDots(objPath + '.' + key);\n\n // getter - value\n valueObj.__defineGetter__(\n key,\n function (this: RxDocument) {\n const _this: RxDocument = thisObj ? thisObj : (this as any);\n if (!_this.get || typeof _this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = _this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(valueObj, key + '$', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(valueObj, key + '_', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // setter - value\n valueObj.__defineSetter__(key, function (\n this: RxDocument,\n val: any\n ) {\n const _this: any = thisObj ? thisObj : this;\n return _this.set(fullPath, val);\n });\n });\n}\n\nexport function createWithConstructor(\n constructor: any,\n collection: RxCollection,\n jsonData: RxDocumentData\n): RxDocument | null {\n const primary: string = jsonData[collection.schema.primaryPath] as any;\n if (\n primary &&\n primary.startsWith('_design')\n ) {\n return null;\n }\n\n const doc = new constructor(collection, jsonData);\n runPluginHooks('createRxDocument', doc);\n return doc;\n}\n\nexport function isRxDocument(obj: any): boolean {\n if (typeof obj === 'undefined') return false;\n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 No newline at end of file +{"version":3,"file":"rx-document.js","names":["objectPath","distinctUntilChanged","filter","map","shareReplay","startWith","clone","trimDots","pluginMissing","flatClone","PROMISE_RESOLVE_NULL","RXJS_SHARE_REPLAY_DEFAULTS","getFromObjectOrThrow","newRxError","runPluginHooks","getDocumentDataOfRxChangeEvent","overwritable","getSchemaByObjectPath","throwIfIsStorageWriteError","modifierFromPublicToInternal","basePrototype","primaryPath","_this","isInstanceOfRxDocument","undefined","collection","schema","primary","_data","revision","_rev","deleted$","$","pipe","d","_deleted","deleted","getLatest","latestDocData","_docCache","getLatestDocumentData","getCachedRxDocument","changeEvent","isLocal","documentId","prev","curr","get$","path","isDevMode","includes","finalFields","schemaObj","jsonSchema","data","get","populate","value","ref","refCollection","database","collections","type","findByIds","exec","then","res","valuesIterator","values","Array","from","findOne","objPath","valueObj","isArray","deepFreezeWhenDevMode","defineGetterSetter","toJSON","withMetaFields","_attachments","_meta","toMutableJSON","update","_updateObj","incrementalUpdate","updateCRDT","putAttachment","getAttachment","allAttachments","allAttachments$","modify","mutationFunction","_context","oldData","newData","_saveData","incrementalModify","incrementalWriteQueue","addWrite","result","patch","Object","entries","forEach","k","v","incrementalPatch","docData","id","document","beforeDocumentUpdateWrite","storageInstance","bulkWrite","previous","writeResult","isError","error","_runHooks","success","remove","Promise","reject","deletedData","removedDocData","removed","incrementalRemove","newDoc","destroy","createRxDocumentConstructor","proto","constructor","RxDocumentConstructor","prototype","thisObj","pathProperties","properties","keys","key","fullPath","__defineGetter__","ret","defineProperty","enumerable","configurable","__defineSetter__","val","set","createWithConstructor","jsonData","doc","isRxDocument","obj","assign","validateChange"],"sources":["../../src/rx-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport {\n Observable\n} from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs/operators';\nimport {\n clone,\n trimDots,\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_NULL,\n RXJS_SHARE_REPLAY_DEFAULTS,\n getFromObjectOrThrow\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\n\nimport type {\n RxDocument,\n RxCollection,\n RxDocumentData,\n RxDocumentWriteData,\n UpdateQuery,\n CRDTEntry,\n ModifyFunction\n} from './types';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\nimport { overwritable } from './overwritable';\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport { throwIfIsStorageWriteError } from './rx-storage-helper';\nimport { modifierFromPublicToInternal } from './incremental-write';\n\nexport const basePrototype = {\n get primaryPath() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this.collection.schema.primaryPath;\n },\n get primary() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return (_this._data as any)[_this.primaryPath];\n },\n get revision() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._rev;\n },\n get deleted$() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this.$.pipe(\n map((d: any) => d._deleted)\n );\n },\n get deleted() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._deleted;\n },\n\n getLatest(this: RxDocument): RxDocument {\n const latestDocData = this.collection._docCache.getLatestDocumentData(this.primary);\n return this.collection._docCache.getCachedRxDocument(latestDocData);\n },\n\n /**\n * returns the observable which emits the plain-data of this document\n */\n get $(): Observable> {\n const _this: RxDocument = this as any;\n return _this.collection.$.pipe(\n filter(changeEvent => !changeEvent.isLocal),\n filter(changeEvent => changeEvent.documentId === this.primary),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(_this.collection._docCache.getLatestDocumentData(this.primary)),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n },\n\n /**\n * returns observable of the value of the given path\n */\n get$(this: RxDocument, path: string): Observable {\n if (overwritable.isDevMode()) {\n if (path.includes('.item.')) {\n throw newRxError('DOC1', {\n path\n });\n }\n\n if (path === this.primaryPath) {\n throw newRxError('DOC2');\n }\n\n // final fields cannot be modified and so also not observed\n if (this.collection.schema.finalFields.includes(path)) {\n throw newRxError('DOC3', {\n path\n });\n }\n\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n if (!schemaObj) {\n throw newRxError('DOC4', {\n path\n });\n }\n }\n\n return this.$\n .pipe(\n map(data => objectPath.get(data, path)),\n distinctUntilChanged()\n );\n },\n\n /**\n * populate the given path\n */\n populate(this: RxDocument, path: string): Promise {\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n const value = this.get(path);\n if (!value) {\n return PROMISE_RESOLVE_NULL;\n }\n if (!schemaObj) {\n throw newRxError('DOC5', {\n path\n });\n }\n if (!schemaObj.ref) {\n throw newRxError('DOC6', {\n path,\n schemaObj\n });\n }\n\n const refCollection: RxCollection = this.collection.database.collections[schemaObj.ref];\n if (!refCollection) {\n throw newRxError('DOC7', {\n ref: schemaObj.ref,\n path,\n schemaObj\n });\n }\n\n if (schemaObj.type === 'array') {\n return refCollection.findByIds(value).exec().then(res => {\n const valuesIterator = res.values();\n return Array.from(valuesIterator) as any;\n });\n } else {\n return refCollection.findOne(value).exec();\n }\n },\n\n /**\n * get data by objectPath\n */\n get(this: RxDocument, objPath: string): any | null {\n if (!this._data) return undefined;\n let valueObj = objectPath.get(this._data, objPath);\n\n // direct return if array or non-object\n if (\n typeof valueObj !== 'object' ||\n Array.isArray(valueObj)\n ) {\n return overwritable.deepFreezeWhenDevMode(valueObj);\n }\n\n /**\n * TODO find a way to deep-freeze together with defineGetterSetter\n * so we do not have to do a deep clone here.\n */\n valueObj = clone(valueObj);\n defineGetterSetter(\n this.collection.schema,\n valueObj,\n objPath,\n this as any\n );\n return valueObj;\n },\n\n toJSON(this: RxDocument, withMetaFields = false) {\n if (!withMetaFields) {\n const data = flatClone(this._data);\n delete (data as any)._rev;\n delete (data as any)._attachments;\n delete (data as any)._deleted;\n delete (data as any)._meta;\n return overwritable.deepFreezeWhenDevMode(data);\n } else {\n return overwritable.deepFreezeWhenDevMode(this._data);\n }\n },\n toMutableJSON(this: RxDocument, withMetaFields = false) {\n return clone(this.toJSON(withMetaFields as any));\n },\n\n /**\n * updates document\n * @overwritten by plugin (optional)\n * @param updateObj mongodb-like syntax\n */\n update(_updateObj: UpdateQuery) {\n throw pluginMissing('update');\n },\n incrementalUpdate(_updateObj: UpdateQuery) {\n throw pluginMissing('update');\n },\n updateCRDT(_updateObj: CRDTEntry | CRDTEntry[]) {\n throw pluginMissing('crdt');\n },\n putAttachment() {\n throw pluginMissing('attachments');\n },\n getAttachment() {\n throw pluginMissing('attachments');\n },\n allAttachments() {\n throw pluginMissing('attachments');\n },\n get allAttachments$() {\n throw pluginMissing('attachments');\n },\n\n async modify(\n this: RxDocument,\n mutationFunction: ModifyFunction,\n // used by some plugins that wrap the method\n _context?: string\n ): Promise {\n const oldData = this._data;\n const newData: RxDocumentData = await modifierFromPublicToInternal(mutationFunction)(oldData) as any;\n return this._saveData(newData, oldData) as any;\n },\n\n /**\n * runs an incremental update over the document\n * @param function that takes the document-data and returns a new data-object\n */\n incrementalModify(\n this: RxDocument,\n mutationFunction: ModifyFunction,\n // used by some plugins that wrap the method\n _context?: string\n ): Promise {\n return this.collection.incrementalWriteQueue.addWrite(\n this._data,\n modifierFromPublicToInternal(mutationFunction)\n ).then(result => this.collection._docCache.getCachedRxDocument(result));\n },\n\n patch(\n this: RxDocument,\n patch: Partial\n ) {\n const oldData = this._data;\n const newData = clone(oldData);\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n (newData as any)[k] = v;\n });\n return this._saveData(newData, oldData);\n },\n\n /**\n * patches the given properties\n */\n incrementalPatch(\n this: RxDocument,\n patch: Partial\n ): Promise> {\n return this.incrementalModify((docData) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n (docData as any)[k] = v;\n });\n return docData;\n });\n },\n\n /**\n * saves the new document-data\n * and handles the events\n */\n async _saveData(\n this: RxDocument,\n newData: RxDocumentWriteData,\n oldData: RxDocumentData\n ): Promise> {\n newData = flatClone(newData);\n\n // deleted documents cannot be changed\n if (this._data._deleted) {\n throw newRxError('DOC11', {\n id: this.primary,\n document: this\n });\n }\n await beforeDocumentUpdateWrite(this.collection, newData, oldData);\n const writeResult = await this.collection.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'rx-document-save-data');\n\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(this.collection, this.primary, newData, isError);\n\n await this.collection._runHooks('post', 'save', newData, this);\n return this.collection._docCache.getCachedRxDocument(\n getFromObjectOrThrow(writeResult.success, this.primary)\n );\n },\n\n /**\n * Remove the document.\n * Notice that there is no hard delete,\n * instead deleted documents get flagged with _deleted=true.\n */\n remove(this: RxDocument): Promise {\n const collection = this.collection;\n if (this.deleted) {\n return Promise.reject(newRxError('DOC13', {\n document: this,\n id: this.primary\n }));\n }\n\n const deletedData = flatClone(this._data);\n let removedDocData: RxDocumentData;\n return collection._runHooks('pre', 'remove', deletedData, this)\n .then(async () => {\n deletedData._deleted = true;\n const writeResult = await collection.storageInstance.bulkWrite([{\n previous: this._data,\n document: deletedData\n }], 'rx-document-remove');\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(collection, this.primary, deletedData, isError);\n return getFromObjectOrThrow(writeResult.success, this.primary);\n })\n .then((removed) => {\n removedDocData = removed;\n return this.collection._runHooks('post', 'remove', deletedData, this);\n })\n .then(() => {\n return this.collection._docCache.getCachedRxDocument(removedDocData);\n });\n },\n incrementalRemove(this: RxDocument): Promise {\n return this.incrementalModify(async (docData) => {\n await this.collection._runHooks('pre', 'remove', docData, this);\n docData._deleted = true;\n return docData;\n }).then(async (newDoc) => {\n await this.collection._runHooks('post', 'remove', newDoc._data, newDoc);\n return newDoc;\n });\n },\n destroy() {\n throw newRxError('DOC14');\n }\n};\n\nexport function createRxDocumentConstructor(proto = basePrototype) {\n const constructor = function RxDocumentConstructor(\n this: RxDocument,\n collection: RxCollection,\n docData: RxDocumentData\n ) {\n this.collection = collection;\n\n // assume that this is always equal to the doc-data in the database\n this._data = docData;\n\n /**\n * because of the prototype-merge,\n * we can not use the native instanceof operator\n */\n this.isInstanceOfRxDocument = true;\n };\n constructor.prototype = proto;\n return constructor;\n}\n\nexport function defineGetterSetter(\n schema: any,\n valueObj: any,\n objPath = '',\n thisObj = false\n) {\n if (valueObj === null) return;\n\n\n let pathProperties = getSchemaByObjectPath(\n schema.jsonSchema,\n objPath\n );\n\n if (typeof pathProperties === 'undefined') return;\n if (pathProperties.properties) pathProperties = pathProperties.properties;\n\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = trimDots(objPath + '.' + key);\n\n // getter - value\n valueObj.__defineGetter__(\n key,\n function (this: RxDocument) {\n const _this: RxDocument = thisObj ? thisObj : (this as any);\n if (!_this.get || typeof _this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = _this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(valueObj, key + '$', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(valueObj, key + '_', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // setter - value\n valueObj.__defineSetter__(key, function (\n this: RxDocument,\n val: any\n ) {\n const _this: any = thisObj ? thisObj : this;\n return _this.set(fullPath, val);\n });\n });\n}\n\nexport function createWithConstructor(\n constructor: any,\n collection: RxCollection,\n jsonData: RxDocumentData\n): RxDocument | null {\n const doc = new constructor(collection, jsonData);\n runPluginHooks('createRxDocument', doc);\n return doc;\n}\n\nexport function isRxDocument(obj: any): boolean {\n if (typeof obj === 'undefined') return false;\n return !!obj.isInstanceOfRxDocument;\n}\n\n\nexport function beforeDocumentUpdateWrite(\n collection: RxCollection,\n newData: RxDocumentWriteData,\n oldData: RxDocumentData\n): Promise {\n /**\n * Meta values must always be merged\n * instead of overwritten.\n * This ensures that different plugins do not overwrite\n * each others meta properties.\n */\n newData._meta = Object.assign(\n {},\n oldData._meta,\n newData._meta\n );\n\n // ensure modifications are ok\n if (overwritable.isDevMode()) {\n collection.schema.validateChange(oldData, newData);\n }\n return collection._runHooks('pre', 'save', newData);\n}\n"],"mappings":";;AAAA,OAAOA,UAAU,MAAM,aAAa;AAIpC,SACIC,oBAAoB,EACpBC,MAAM,EACNC,GAAG,EACHC,WAAW,EACXC,SAAS,QACN,gBAAgB;AACvB,SACIC,KAAK,EACLC,QAAQ,EACRC,aAAa,EACbC,SAAS,EACTC,oBAAoB,EACpBC,0BAA0B,EAC1BC,oBAAoB,QACjB,iBAAiB;AACxB,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QACX,SAAS;AAWhB,SAASC,8BAA8B,QAAQ,mBAAmB;AAClE,SAASC,YAAY,QAAQ,gBAAgB;AAC7C,SAASC,qBAAqB,QAAQ,oBAAoB;AAC1D,SAASC,0BAA0B,QAAQ,qBAAqB;AAChE,SAASC,4BAA4B,QAAQ,qBAAqB;AAElE,OAAO,IAAMC,aAAa,GAAG;EACzB,IAAIC,WAAW,GAAG;IACd,IAAMC,KAAiB,GAAG,IAAW;IACrC,IAAI,CAACA,KAAK,CAACC,sBAAsB,EAAE;MAC/B,OAAOC,SAAS;IACpB;IACA,OAAOF,KAAK,CAACG,UAAU,CAACC,MAAM,CAACL,WAAW;EAC9C,CAAC;EACD,IAAIM,OAAO,GAAG;IACV,IAAML,KAAiB,GAAG,IAAW;IACrC,IAAI,CAACA,KAAK,CAACC,sBAAsB,EAAE;MAC/B,OAA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uI,GAAG,CAAC;EACvC,OAAOA,GAAG;AACd;AAEA,OAAO,SAASC,YAAY,CAACC,GAAQ,EAAW;EAC5C,IAAI,OAAOA,GAAG,KAAK,WAAW,EAAE,OAAO,KAAK;EAC5C,OAAO,CAAC,CAACA,GAAG,CAAChI,sBAAsB;AACvC;AAGA,OAAO,SAASuF,yBAAyB,CACrCrF,UAAmC,EACnCqE,OAAuC,EACvCD,OAAkC,EACtB;EACZ;AACJ;AACA;AACA;AACA;AACA;EACIC,OAAO,CAACd,KAAK,GAAGqB,MAAM,CAACmD,MAAM,CACzB,CAAC,CAAC,EACF3D,OAAO,CAACb,KAAK,EACbc,OAAO,CAACd,KAAK,CAChB;;EAED;EACA,IAAIhE,YAAY,CAACiC,SAAS,EAAE,EAAE;IAC1BxB,UAAU,CAACC,MAAM,CAAC+H,cAAc,CAAC5D,OAAO,EAAEC,OAAO,CAAC;EACtD;EACA,OAAOrE,UAAU,CAAC4F,SAAS,CAAC,KAAK,EAAE,MAAM,EAAEvB,OAAO,CAAC;AACvD"} \ No newline at end of file diff --git a/dist/es/rx-error.js b/dist/es/rx-error.js index c69ac95143a..7adbf234e9f 100644 --- a/dist/es/rx-error.js +++ b/dist/es/rx-error.js @@ -30,6 +30,8 @@ function messageForError(message, code, parameters) { } export var RxError = /*#__PURE__*/function (_Error) { _inheritsLoose(RxError, _Error); + // always true, use this to detect if its an rxdb-error + function RxError(code, message) { var _this; var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -60,6 +62,8 @@ export var RxError = /*#__PURE__*/function (_Error) { }( /*#__PURE__*/_wrapNativeSuper(Error)); export var RxTypeError = /*#__PURE__*/function (_TypeError) { _inheritsLoose(RxTypeError, _TypeError); + // always true, use this to detect if its an rxdb-error + function RxTypeError(code, message) { var _this2; var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -100,10 +104,22 @@ export function newRxTypeError(code, parameters) { * return false if it is another error. */ export function isBulkWriteConflictError(err) { - if (err.status === 409) { + if (err && err.status === 409) { return err; } else { return false; } } +var STORAGE_WRITE_ERROR_CODE_TO_MESSAGE = { + 409: 'document write conflict', + 422: 'schema validation error', + 510: 'attachment data missing' +}; +export function rxStorageWriteErrorToRxError(err) { + return newRxError('COL20', { + name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status], + document: err.documentId, + writeError: err + }); +} //# sourceMappingURL=rx-error.js.map \ No newline at end of file diff --git a/dist/es/rx-error.js.map b/dist/es/rx-error.js.map index 3cd7e393bcc..fd62b3528c4 100644 --- a/dist/es/rx-error.js.map +++ b/dist/es/rx-error.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.js","names":["overwritable","parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","JSON","stringify","_k","v","undefined","e","join","messageForError","message","code","RxError","mes","rxdb","toString","Error","RxTypeError","TypeError","newRxError","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","err","status"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageBulkWriteError\n} from './types';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n paramStr = JSON.stringify(\n parameters[k],\n (_k, v) => v === undefined ? null : v,\n 2\n );\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err: RxStorageBulkWriteError | any\n): RxStorageBulkWriteError | false {\n if (\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n"],"mappings":";;;AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,gBAAgB;AAO7C;AACA;AACA;AACA,SAASC,kBAAkB,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GA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able","parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","JSON","stringify","_k","v","undefined","e","join","messageForError","message","code","RxError","mes","rxdb","toString","Error","RxTypeError","TypeError","newRxError","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","err","status","STORAGE_WRITE_ERROR_CODE_TO_MESSAGE","rxStorageWriteErrorToRxError","name","document","documentId","writeError"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageWriteError,\n RxStorageWriteErrorConflict\n} from './types';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n paramStr = JSON.stringify(\n parameters[k],\n (_k, v) => v === undefined ? null : v,\n 2\n );\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err?: RxStorageWriteError | any\n): RxStorageWriteErrorConflict | false {\n if (\n err &&\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n\n\nconst STORAGE_WRITE_ERROR_CODE_TO_MESSAGE: { [k: number]: string; } = {\n 409: 'document write conflict',\n 422: 'schema validation error',\n 510: 'attachment data missing'\n};\n\nexport function rxStorageWriteErrorToRxError(err: RxStorageWriteError): RxError {\n return newRxError('COL20', {\n name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status],\n document: err.documentId,\n writeError: err\n });\n}\n"],"mappings":";;;AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,gBAAgB;AAQ7C;AACA;AACA;AACA,SAASC,kBAAkB,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GAAG,CAAC,UAAAC,CAAC,EAAI;IACN,IAAIC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AC9B,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE;AACT,CAAC;AAED,OAAO,SAASC,4BAA4B,CAACH,GAA6B,EAAW;EACjF,OAAOJ,UAAU,CAAC,OAAO,EAAE;IACvBQ,IAAI,EAAEF,mCAAmC,CAACF,GAAG,CAACC,MAAM,CAAC;IACrDI,QAAQ,EAAEL,GAAG,CAACM,UAAU;IACxBC,UAAU,EAAEP;EAChB,CAAC,CAAC;AACN"} \ No newline at end of file diff --git a/dist/es/rx-query-helper.js b/dist/es/rx-query-helper.js index eae9973c153..263c2f69b49 100644 --- a/dist/es/rx-query-helper.js +++ b/dist/es/rx-query-helper.js @@ -1,6 +1,6 @@ import { LOGICAL_OPERATORS } from './query-planner'; import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper'; -import { clone, firstPropertyNameOfObject, isMaybeReadonlyArray } from './util'; +import { clone, firstPropertyNameOfObject, toArray, isMaybeReadonlyArray } from './plugins/utils'; /** * Normalize the query to ensure we have all fields set @@ -47,7 +47,7 @@ export function normalizeMangoQuery(schema, mangoQuery) { * the primaryKey is inside of it. */ if (normalizedMangoQuery.index) { - var indexAr = Array.isArray(normalizedMangoQuery.index) ? normalizedMangoQuery.index.slice(0) : [normalizedMangoQuery.index]; + var indexAr = toArray(normalizedMangoQuery.index); if (!indexAr.includes(primaryKey)) { indexAr.push(primaryKey); } diff --git a/dist/es/rx-query-helper.js.map b/dist/es/rx-query-helper.js.map index fe633efc80c..f7d2c09c24d 100644 --- a/dist/es/rx-query-helper.js.map +++ b/dist/es/rx-query-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query-helper.js","names":["LOGICAL_OPERATORS","getPrimaryFieldOfPrimaryKey","clone","firstPropertyNameOfObject","isMaybeReadonlyArray","normalizeMangoQuery","schema","mangoQuery","primaryKey","normalizedMangoQuery","skip","selector","Object","entries","forEach","field","matcher","$eq","index","indexAr","Array","isArray","slice","includes","push","sort","map","indexes","fieldsWithLogicalOperator","Set","hasLogical","keys","find","operator","has","add","currentFieldsAmount","currentBestIndexForSort","useIndex","firstWrongIndex","findIndex","indexField","isPrimaryInSort","p"],"sources":["../../src/rx-query-helper.ts"],"sourcesContent":["import { LOGICAL_OPERATORS } from './query-planner';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n clone,\n firstPropertyNameOfObject,\n isMaybeReadonlyArray\n} from './util';\n\n/**\n * Normalize the query to ensure we have all fields set\n * and queries that represent the same query logic are detected as equal by the caching.\n */\nexport function normalizeMangoQuery(\n schema: RxJsonSchema>,\n mangoQuery: MangoQuery\n): FilledMangoQuery {\n const primaryKey: string = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const normalizedMangoQuery: FilledMangoQuery = clone(mangoQuery) as any;\n\n if (typeof normalizedMangoQuery.skip !== 'number') {\n normalizedMangoQuery.skip = 0;\n }\n\n if (!normalizedMangoQuery.selector) {\n normalizedMangoQuery.selector = {};\n } else {\n normalizedMangoQuery.selector = normalizedMangoQuery.selector;\n /**\n * In mango query, it is possible to have an\n * equals comparison by directly assigning a value\n * to a property, without the '$eq' operator.\n * Like:\n * selector: {\n * foo: 'bar'\n * }\n * For normalization, we have to normalize this\n * so our checks can perform properly.\n *\n *\n * TODO this must work recursive with nested queries that\n * contain multiple selectors via $and or $or etc.\n */\n Object\n .entries(normalizedMangoQuery.selector)\n .forEach(([field, matcher]) => {\n if (typeof matcher !== 'object' || matcher === null) {\n normalizedMangoQuery.selector[field] = {\n $eq: matcher\n };\n }\n });\n }\n\n /**\n * Ensure that if an index is specified,\n * the primaryKey is inside of it.\n */\n if (normalizedMangoQuery.index) {\n const indexAr = Array.isArray(normalizedMangoQuery.index) ? normalizedMangoQuery.index.slice(0) : [normalizedMangoQuery.index];\n if (!indexAr.includes(primaryKey)) {\n indexAr.push(primaryKey);\n }\n normalizedMangoQuery.index = indexAr;\n }\n\n /**\n * To ensure a deterministic sorting,\n * we have to ensure the primary key is always part\n * of the sort query.\n * Primary sorting is added as last sort parameter,\n * similar to how we add the primary key to indexes that do not have it.\n *\n */\n if (!normalizedMangoQuery.sort) {\n /**\n * If no sort is given at all,\n * we can assume that the user does not care about sort order at al.\n *\n * we cannot just use the primary key as sort parameter\n * because it would likely cause the query to run over the primary key index\n * which has a bad performance in most cases.\n */\n if (normalizedMangoQuery.index) {\n normalizedMangoQuery.sort = normalizedMangoQuery.index.map((field: string) => ({ [field as any]: 'asc' } as any));\n } else {\n /**\n * Find the index that best matches the fields with the logical operators\n */\n if (schema.indexes) {\n const fieldsWithLogicalOperator: Set = new Set();\n Object.entries(normalizedMangoQuery.selector).forEach(([field, matcher]) => {\n let hasLogical = false;\n if (typeof matcher === 'object' && matcher !== null) {\n hasLogical = !!Object.keys(matcher).find(operator => LOGICAL_OPERATORS.has(operator));\n } else {\n hasLogical = true;\n }\n if (hasLogical) {\n fieldsWithLogicalOperator.add(field);\n }\n });\n\n\n let currentFieldsAmount = -1;\n let currentBestIndexForSort: string[] | readonly string[] | undefined;\n schema.indexes.forEach(index => {\n const useIndex = isMaybeReadonlyArray(index) ? index : [index];\n const firstWrongIndex = useIndex.findIndex(indexField => !fieldsWithLogicalOperator.has(indexField));\n if (\n firstWrongIndex > 0 &&\n firstWrongIndex > currentFieldsAmount\n ) {\n currentFieldsAmount = firstWrongIndex;\n currentBestIndexForSort = useIndex;\n }\n });\n if (currentBestIndexForSort) {\n normalizedMangoQuery.sort = currentBestIndexForSort.map((field: string) => ({ [field as any]: 'asc' } as any));\n }\n\n }\n\n /**\n * Fall back to the primary key as sort order\n * if no better one has been found\n */\n if (!normalizedMangoQuery.sort) {\n normalizedMangoQuery.sort = [{ [primaryKey]: 'asc' }] as any;\n }\n }\n } else {\n const isPrimaryInSort = normalizedMangoQuery.sort\n .find(p => firstPropertyNameOfObject(p) === primaryKey);\n if (!isPrimaryInSort) {\n normalizedMangoQuery.sort = normalizedMangoQuery.sort.slice(0);\n normalizedMangoQuery.sort.push({ [primaryKey]: 'asc' } as any);\n }\n }\n\n return normalizedMangoQuery;\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,iBAAiB;AACnD,SAASC,2BAA2B,QAAQ,oBAAoB;AAOhE,SACIC,KAAK,EACLC,yBAAyB,EACzBC,oBAAoB,QACjB,QAAQ;;AAEf;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmB,CAC/BC,MAA+C,EAC/CC,UAAiC,EACN;EAC3B,IAAMC,UAAkB,GAAGP,2BAA2B,CAACK,MAAM,CAACE,UAAU,CAAC;EACzE,IAAMC,oBAAiD,GAAGP,KAAK,CAACK,UAAU,CAAQ;EAElF,IAAI,OAAOE,oBAAoB,CAACC,IAAI,KAAK,QAAQ,EAAE;IAC/CD,oBAAoB,CAACC,IAAI,GAAG,CAAC;EACjC;EAEA,IAAI,CAACD,oBAAoB,CAACE,QAAQ,EAAE;IAChCF,oBAAoB,CAACE,QAAQ,GAAG,CAAC,CAAC;EACtC,CAAC,MAAM;IACHF,oBAAoB,CAACE,QAAQ,GAAGF,oBAAoB,CAACE,QAAQ;IAC7D;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;IACQC,MAAM,CACDC,OAAO,CAACJ,oBAAoB,CAACE,QAAQ,CAAC,CACtCG,OAAO,CAAC,gBAAsB;MAAA,IAApBC,KAAK;QAAEC,OAAO;MACrB,IAAI,OAAOA,OAAO,KAAK,QAAQ,IAAIA,OAAO,KAAK,IAAI,EAAE;QACjDP,oBAAoB,CAACE,QAAQ,CAACI,KAAK,CAAC,GAAG;UACnCE,GAAG,EAAED;QACT,CAAC;MACL;IACJ,CAAC,CAAC;EACV;;EAEA;AACJ;AACA;AACA;EACI,IAAIP,oBAAoB,CAACS,KAAK,EAAE;IAC5B,IAAMC,OAAO,GAAGC,KAAK,CAACC,OAAO,CAACZ,oBAAoB,CAACS,KAAK,CAAC,GAAGT,oBAAoB,C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end of file +{"version":3,"file":"rx-query-helper.js","names":["LOGICAL_OPERATORS","getPrimaryFieldOfPrimaryKey","clone","firstPropertyNameOfObject","toArray","isMaybeReadonlyArray","normalizeMangoQuery","schema","mangoQuery","primaryKey","normalizedMangoQuery","skip","selector","Object","entries","forEach","field","matcher","$eq","index","indexAr","includes","push","sort","map","indexes","fieldsWithLogicalOperator","Set","hasLogical","keys","find","operator","has","add","currentFieldsAmount","currentBestIndexForSort","useIndex","firstWrongIndex","findIndex","indexField","isPrimaryInSort","p","slice"],"sources":["../../src/rx-query-helper.ts"],"sourcesContent":["import { LOGICAL_OPERATORS } from './query-planner';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n clone,\n firstPropertyNameOfObject,\n toArray,\n isMaybeReadonlyArray\n} from './plugins/utils';\n\n/**\n * Normalize the query to ensure we have all fields set\n * and queries that represent the same query logic are detected as equal by the caching.\n */\nexport function normalizeMangoQuery(\n schema: RxJsonSchema>,\n mangoQuery: MangoQuery\n): FilledMangoQuery {\n const primaryKey: string = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const normalizedMangoQuery: FilledMangoQuery = clone(mangoQuery) as any;\n\n if (typeof normalizedMangoQuery.skip !== 'number') {\n normalizedMangoQuery.skip = 0;\n }\n\n if (!normalizedMangoQuery.selector) {\n normalizedMangoQuery.selector = {};\n } else {\n normalizedMangoQuery.selector = normalizedMangoQuery.selector;\n /**\n * In mango query, it is possible to have an\n * equals comparison by directly assigning a value\n * to a property, without the '$eq' operator.\n * Like:\n * selector: {\n * foo: 'bar'\n * }\n * For normalization, we have to normalize this\n * so our checks can perform properly.\n *\n *\n * TODO this must work recursive with nested queries that\n * contain multiple selectors via $and or $or etc.\n */\n Object\n .entries(normalizedMangoQuery.selector)\n .forEach(([field, matcher]) => {\n if (typeof matcher !== 'object' || matcher === null) {\n (normalizedMangoQuery as any).selector[field] = {\n $eq: matcher\n };\n }\n });\n }\n\n /**\n * Ensure that if an index is specified,\n * the primaryKey is inside of it.\n */\n if (normalizedMangoQuery.index) {\n const indexAr = toArray(normalizedMangoQuery.index);\n if (!indexAr.includes(primaryKey)) {\n indexAr.push(primaryKey);\n }\n normalizedMangoQuery.index = indexAr;\n }\n\n /**\n * To ensure a deterministic sorting,\n * we have to ensure the primary key is always part\n * of the sort query.\n * Primary sorting is added as last sort parameter,\n * similar to how we add the primary key to indexes that do not have it.\n *\n */\n if (!normalizedMangoQuery.sort) {\n /**\n * If no sort is given at all,\n * we can assume that the user does not care about sort order at al.\n *\n * we cannot just use the primary key as sort parameter\n * because it would likely cause the query to run over the primary key index\n * which has a bad performance in most cases.\n */\n if (normalizedMangoQuery.index) {\n normalizedMangoQuery.sort = normalizedMangoQuery.index.map((field: string) => ({ [field as any]: 'asc' } as any));\n } else {\n /**\n * Find the index that best matches the fields with the logical operators\n */\n if (schema.indexes) {\n const fieldsWithLogicalOperator: Set = new Set();\n Object.entries(normalizedMangoQuery.selector).forEach(([field, matcher]) => {\n let hasLogical = false;\n if (typeof matcher === 'object' && matcher !== null) {\n hasLogical = !!Object.keys(matcher).find(operator => LOGICAL_OPERATORS.has(operator));\n } else {\n hasLogical = true;\n }\n if (hasLogical) {\n fieldsWithLogicalOperator.add(field);\n }\n });\n\n\n let currentFieldsAmount = -1;\n let currentBestIndexForSort: string[] | readonly string[] | undefined;\n schema.indexes.forEach(index => {\n const useIndex = isMaybeReadonlyArray(index) ? index : [index];\n const firstWrongIndex = useIndex.findIndex(indexField => !fieldsWithLogicalOperator.has(indexField));\n if (\n firstWrongIndex > 0 &&\n firstWrongIndex > currentFieldsAmount\n ) {\n currentFieldsAmount = firstWrongIndex;\n currentBestIndexForSort = useIndex;\n }\n });\n if (currentBestIndexForSort) {\n normalizedMangoQuery.sort = currentBestIndexForSort.map((field: string) => ({ [field as any]: 'asc' } as any));\n }\n\n }\n\n /**\n * Fall back to the primary key as sort order\n * if no better one has been found\n */\n if (!normalizedMangoQuery.sort) {\n normalizedMangoQuery.sort = [{ [primaryKey]: 'asc' }] as any;\n }\n }\n } else {\n const isPrimaryInSort = normalizedMangoQuery.sort\n .find(p => firstPropertyNameOfObject(p) === primaryKey);\n if (!isPrimaryInSort) {\n normalizedMangoQuery.sort = normalizedMangoQuery.sort.slice(0);\n normalizedMangoQuery.sort.push({ [primaryKey]: 'asc' } as any);\n }\n }\n\n return normalizedMangoQuery;\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,iBAAiB;AACnD,SAASC,2BAA2B,QAAQ,oBAAoB;AAOhE,SACIC,KAAK,EACLC,yBAAyB,EACzBC,OAAO,EACPC,oBAAoB,QACjB,iBAAiB;;AAExB;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmB,CAC/BC,MAA+C,EAC/CC,UAAiC,EACN;EAC3B,IAAMC,UAAkB,GAAGR,2BAA2B,CAACM,MAAM,CAACE,UAAU,CAAC;EACzE,IAAMC,oBAAiD,GAAGR,KAAK,CAACM,UAAU,CAAQ;EAElF,IAAI,OAAOE,oBAAoB,CAACC,IAAI,KAAK,QAAQ,EAAE;IAC/CD,oBAAoB,CAACC,IAAI,GAAG,CAAC;EACjC;EAEA,IAAI,CAACD,oBAAoB,CAACE,QAAQ,EAAE;IAChCF,oBAAoB,CAACE,QAAQ,GAAG,CAAC,CAAC;EACtC,CAAC,MAAM;IACHF,oBAAoB,CAACE,QAAQ,GAAGF,oBAAoB,CAACE,QAAQ;IAC7D;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;IACQC,MAAM,CACDC,OAAO,CAACJ,oBAAoB,CAACE,QAAQ,CAAC,CACtCG,OAAO,CAAC,gBAAsB;MAAA,IAApBC,KAAK;QAAEC,OAAO;MACrB,IAAI,OAAOA,OAAO,KAAK,QAAQ,IAAIA,OAAO,KAAK,IAAI,EAAE;QAChDP,oBAAoB,CAASE,QAAQ,CAACI,K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ACa,IAAI,CAACD,IAAI,oDAAIb,UAAU,IAAG,KAAK,yBAAU;IAClE;EACJ;EAEA,OAAOC,oBAAoB;AAC/B"} \ No newline at end of file diff --git a/dist/es/rx-query-mingo.js b/dist/es/rx-query-mingo.js index 50f75efb543..2aad1ffe684 100644 --- a/dist/es/rx-query-mingo.js +++ b/dist/es/rx-query-mingo.js @@ -1,6 +1,7 @@ import { useOperators, OperatorType } from 'mingo/core'; import { Query } from 'mingo/query'; -import { $sort, $project } from 'mingo/operators/pipeline'; +import { $sort } from 'mingo/operators/pipeline/sort'; +import { $project } from 'mingo/operators/pipeline/project'; import { $and, $eq, $elemMatch, $exists, $gt, $gte, $in, $lt, $lte, $ne, $nin, $mod, $nor, $not, $or, $regex, $size, $type } from 'mingo/operators/query'; var mingoInitDone = false; diff --git a/dist/es/rx-query-mingo.js.map b/dist/es/rx-query-mingo.js.map index 51517fbf6f9..7fc23400f15 100644 --- a/dist/es/rx-query-mingo.js.map +++ b/dist/es/rx-query-mingo.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query-mingo.js","names":["useOperators","OperatorType","Query","$sort","$project","$and","$eq","$elemMatch","$exists","$gt","$gte","$in","$lt","$lte","$ne","$nin","$mod","$nor","$not","$or","$regex","$size","$type","mingoInitDone","getMingoQuery","selector","PIPELINE","QUERY"],"sources":["../../src/rx-query-mingo.ts"],"sourcesContent":["import { useOperators, OperatorType } from 'mingo/core';\nimport { Query } from 'mingo/query';\nimport type { MangoQuerySelector } from './types';\n\nimport { $sort, $project } from 'mingo/operators/pipeline';\nimport {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n} from 'mingo/operators/query';\n\nlet mingoInitDone = false;\n\n\n/**\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport function getMingoQuery(\n selector?: MangoQuerySelector\n) {\n if (!mingoInitDone) {\n\n useOperators(OperatorType.PIPELINE, {\n $sort,\n $project\n } as any);\n useOperators(OperatorType.QUERY, {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n } as any);\n mingoInitDone = true;\n }\n return new Query(selector as any);\n}\n"],"mappings":"AAAA,SAASA,YAAY,EAAEC,YAAY,QAAQ,YAAY;AACvD,SAASC,KAAK,QAAQ,aAAa;AAGnC,SAASC,KAAK,EAAEC,QAAQ,QAAQ,0BAA0B;AAC1D,SACIC,IAAI,EACJC,GAAG,EACHC,UAAU,EACVC,OAAO,EACPC,GAAG,EACHC,IAAI,EACJC,GAAG,EACHC,GAAG,EACHC,IAAI,EACJC,GAAG,EACHC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,GAAG,EACHC,MAAM,EACNC,KAAK,EACLC,KAAK,QACF,uBAAuB;AAE9B,IAAIC,aAAa,GAAG,KAAK;;AAGzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAa,CACzBC,QAAwC,EAC1C;EACE,IAAI,CAACF,aAAa,EAAE;IAEhBvB,YAAY,CAACC,YAAY,CAACyB,QAAQ,EAAE;MAChCvB,KAAK,EAALA,KAAK;MACLC,QAAQ,EAARA;IACJ,CAAC,CAAQ;IACTJ,YAAY,CAACC,YAAY,CAAC0B,KAAK,EAAE;MAC7BtB,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,UAAU,EAAVA,UAAU;MACVC,OAAO,EAAPA,OAAO;MACPC,GAAG,EAAHA,GAAG;MACHC,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,GAAG,EAAHA,GAAG;MACHC,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,IAAI,EAAJA,IAAI;MACJC,IAAI,EAAJA,IAAI;MACJC,IAAI,EAAJA,IAAI;MACJC,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,MAAM,EAANA,MAAM;MACNC,KAAK,EAALA,KAAK;MACLC,KAAK,EAALA;IACJ,CAAC,CAAQ;IACTC,aAAa,GAAG,IAAI;EACxB;EACA,OAAO,IAAIrB,KAAK,CAACuB,QAAQ,CAAQ;AACrC"} \ No newline at end of file +{"version":3,"file":"rx-query-mingo.js","names":["useOperators","OperatorType","Query","$sort","$project","$and","$eq","$elemMatch","$exists","$gt","$gte","$in","$lt","$lte","$ne","$nin","$mod","$nor","$not","$or","$regex","$size","$type","mingoInitDone","getMingoQuery","selector","PIPELINE","QUERY"],"sources":["../../src/rx-query-mingo.ts"],"sourcesContent":["import { useOperators, OperatorType } from 'mingo/core';\nimport { Query } from 'mingo/query';\nimport type { MangoQuerySelector } from './types';\n\nimport { $sort } from 'mingo/operators/pipeline/sort';\nimport { $project } from 'mingo/operators/pipeline/project';\nimport {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n} from 'mingo/operators/query';\n\nlet mingoInitDone = false;\n\n\n/**\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport function getMingoQuery(\n selector?: MangoQuerySelector\n) {\n if (!mingoInitDone) {\n\n useOperators(OperatorType.PIPELINE, {\n $sort,\n $project\n } as any);\n useOperators(OperatorType.QUERY, {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n } as any);\n mingoInitDone = true;\n }\n return new Query(selector as any);\n}\n"],"mappings":"AAAA,SAASA,YAAY,EAAEC,YAAY,QAAQ,YAAY;AACvD,SAASC,KAAK,QAAQ,aAAa;AAGnC,SAASC,KAAK,QAAQ,+BAA+B;AACrD,SAASC,QAAQ,QAAQ,kCAAkC;AAC3D,SACIC,IAAI,EACJC,GAAG,EACHC,UAAU,EACVC,OAAO,EACPC,GAAG,EACHC,IAAI,EACJC,GAAG,EACHC,GAAG,EACHC,IAAI,EACJC,GAAG,EACHC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,GAAG,EACHC,MAAM,EACNC,KAAK,EACLC,KAAK,QACF,uBAAuB;AAE9B,IAAIC,aAAa,GAAG,KAAK;;AAGzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,aAAa,CACzBC,QAAwC,EAC1C;EACE,IAAI,CAACF,aAAa,EAAE;IAEhBvB,YAAY,CAACC,YAAY,CAACyB,QAAQ,EAAE;MAChCvB,KAAK,EAALA,KAAK;MACLC,QAAQ,EAARA;IACJ,CAAC,CAAQ;IACTJ,YAAY,CAACC,YAAY,CAAC0B,KAAK,EAAE;MAC7BtB,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,UAAU,EAAVA,UAAU;MACVC,OAAO,EAAPA,OAAO;MACPC,GAAG,EAAHA,GAAG;MACHC,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,GAAG,EAAHA,GAAG;MACHC,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,IAAI,EAAJA,IAAI;MACJC,IAAI,EAAJA,IAAI;MACJC,IAAI,EAAJA,IAAI;MACJC,IAAI,EAAJA,IAAI;MACJC,GAAG,EAAHA,GAAG;MACHC,MAAM,EAANA,MAAM;MACNC,KAAK,EAALA,KAAK;MACLC,KAAK,EAALA;IACJ,CAAC,CAAQ;IACTC,aAAa,GAAG,IAAI;EACxB;EACA,OAAO,IAAIrB,KAAK,CAACuB,QAAQ,CAAQ;AACrC"} \ No newline at end of file diff --git a/dist/es/rx-query.js b/dist/es/rx-query.js index 0567da1aca6..4b54654517f 100644 --- a/dist/es/rx-query.js +++ b/dist/es/rx-query.js @@ -1,62 +1,14 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _createClass from "@babel/runtime/helpers/createClass"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; import { BehaviorSubject, firstValueFrom, merge } from 'rxjs'; import { mergeMap, filter, map, startWith, distinctUntilChanged, shareReplay } from 'rxjs/operators'; -import { sortObject, stringifyFilter, pluginMissing, clone, overwriteGetterForCaching, now, PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS, ensureNotFalsy, areRxDocumentArraysEqual } from './util'; +import { sortObject, stringifyFilter, pluginMissing, clone, overwriteGetterForCaching, now, PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS, ensureNotFalsy, areRxDocumentArraysEqual } from './plugins/utils'; import { newRxError } from './rx-error'; import { runPluginHooks } from './hooks'; -import { createRxDocuments } from './rx-document-prototype-merge'; import { calculateNewResults } from './event-reduce'; import { triggerCacheReplacement } from './query-cache'; import { normalizeMangoQuery } from './rx-query-helper'; -/** - * Runs the query over the storage instance - * of the collection. - * Does some optimizations to ensuer findById is used - * when specific queries are used. - */ -export var queryCollection = function queryCollection(rxQuery) { - try { - var docs = []; - var _collection = rxQuery.collection; - - /** - * Optimizations shortcut. - * If query is find-one-document-by-id, - * then we do not have to use the slow query() method - * but instead can use findDocumentsById() - */ - var _temp = function () { - if (rxQuery.isFindOneByIdQuery) { - var docId = rxQuery.isFindOneByIdQuery; - return Promise.resolve(_collection.storageInstance.findDocumentsById([docId], false)).then(function (docsMap) { - var docData = docsMap[docId]; - if (docData) { - docs.push(docData); - } - }); - } else { - var preparedQuery = rxQuery.getPreparedQuery(); - return Promise.resolve(_collection.storageInstance.query(preparedQuery)).then(function (queryResult) { - docs = queryResult.documents; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return docs; - }) : docs); - } catch (e) { - return Promise.reject(e); - } -}; - -/** - * Returns true if the given query - * selects exactly one document by its id. - * Used to optimize performance because these kind of - * queries do not have to run over an index and can use get-by-id instead. - * Returns false if no query of that kind. - * Returns the document id otherwise. - */ var _queryCount = 0; var newQueryID = function newQueryID() { return ++_queryCount; @@ -101,36 +53,42 @@ export var RxQueryBase = /*#__PURE__*/function () { var _proto = RxQueryBase.prototype; /** * set the new result-data as result-docs of the query - * @param newResultData json-docs that were received from pouchdb + * @param newResultData json-docs that were received from the storage */ _proto._setResultData = function _setResultData(newResultData) { + var _this = this; if (typeof newResultData === 'number') { this._result = { docsData: [], + docsMap: new Map(), docsDataMap: new Map(), count: newResultData, docs: [], time: now() }; return; + } else if (newResultData instanceof Map) { + newResultData = Array.from(newResultData.values()); } - var docs = createRxDocuments(this.collection, newResultData); + var docsDataMap = new Map(); + var docsMap = new Map(); + var docs = newResultData.map(function (docData) { + return _this.collection._docCache.getCachedRxDocument(docData); + }); /** * Instead of using the newResultData in the result cache, * we directly use the objects that are stored in the RxDocument * to ensure we do not store the same data twice and fill up the memory. */ - var primPath = this.collection.schema.primaryPath; - var docsDataMap = new Map(); var docsData = docs.map(function (doc) { - var docData = doc._dataSync$.getValue(); - var id = docData[primPath]; - docsDataMap.set(id, docData); - return docData; + docsDataMap.set(doc.primary, doc._data); + docsMap.set(doc.primary, doc); + return doc._data; }); this._result = { docsData: docsData, + docsMap: docsMap, docsDataMap: docsDataMap, count: docsData.length, docs: docs, @@ -142,37 +100,95 @@ export var RxQueryBase = /*#__PURE__*/function () { * executes the query on the database * @return results-array with document-data */; - _proto._execOverDatabase = function _execOverDatabase() { - var _this = this; - this._execOverDatabaseCount = this._execOverDatabaseCount + 1; - this._lastExecStart = now(); - if (this.op === 'count') { - var preparedQuery = this.getPreparedQuery(); - return this.collection.storageInstance.count(preparedQuery).then(function (result) { - if (result.mode === 'slow' && !_this.collection.database.allowSlowCount) { - throw newRxError('QU14', { - collection: _this.collection, - queryObj: _this.mangoQuery - }); - } else { - return result.count; + _proto._execOverDatabase = + /*#__PURE__*/ + function () { + var _execOverDatabase2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + var _this2 = this; + var preparedQuery, result, ids, ret, mustBeQueried, docs, docsPromise; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + this._execOverDatabaseCount = this._execOverDatabaseCount + 1; + this._lastExecStart = now(); + if (!(this.op === 'count')) { + _context.next = 12; + break; + } + preparedQuery = this.getPreparedQuery(); + _context.next = 6; + return this.collection.storageInstance.count(preparedQuery); + case 6: + result = _context.sent; + if (!(result.mode === 'slow' && !this.collection.database.allowSlowCount)) { + _context.next = 11; + break; + } + throw newRxError('QU14', { + collection: this.collection, + queryObj: this.mangoQuery + }); + case 11: + return _context.abrupt("return", result.count); + case 12: + if (!(this.op === 'findByIds')) { + _context.next = 23; + break; + } + ids = ensureNotFalsy(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in; + ret = new Map(); + mustBeQueried = []; // first try to fill from docCache + ids.forEach(function (id) { + var docData = _this2.collection._docCache.getLatestDocumentDataIfExists(id); + if (docData) { + if (!docData._deleted) { + var doc = _this2.collection._docCache.getCachedRxDocument(docData); + ret.set(id, doc); + } + } else { + mustBeQueried.push(id); + } + }); + // everything which was not in docCache must be fetched from the storage + if (!(mustBeQueried.length > 0)) { + _context.next = 22; + break; + } + _context.next = 20; + return this.collection.storageInstance.findDocumentsById(mustBeQueried, false); + case 20: + docs = _context.sent; + Object.values(docs).forEach(function (docData) { + var doc = _this2.collection._docCache.getCachedRxDocument(docData); + ret.set(doc.primary, doc); + }); + case 22: + return _context.abrupt("return", ret); + case 23: + docsPromise = queryCollection(this); + return _context.abrupt("return", docsPromise.then(function (docs) { + _this2._lastExecEnd = now(); + return docs; + })); + case 25: + case "end": + return _context.stop(); } - }); + }, _callee, this); + })); + function _execOverDatabase() { + return _execOverDatabase2.apply(this, arguments); } - var docsPromise = queryCollection(this); - return docsPromise.then(function (docs) { - _this._lastExecEnd = now(); - return docs; - }); - } - + return _execOverDatabase; + }() /** * Execute the query * To have an easier implementations, * just subscribe and use the first result - */; + */ + ; _proto.exec = function exec(throwIfMissing) { - var _this2 = this; + var _this3 = this; if (throwIfMissing && this.op !== 'findOne') { throw newRxError('QU9', { collection: this.collection.name, @@ -187,13 +203,13 @@ export var RxQueryBase = /*#__PURE__*/function () { * will be thrown at this execution context and not in the background. */ return _ensureEqual(this).then(function () { - return firstValueFrom(_this2.$); + return firstValueFrom(_this3.$); }).then(function (result) { if (!result && throwIfMissing) { throw newRxError('QU10', { - collection: _this2.collection.name, - query: _this2.mangoQuery, - op: _this2.op + collection: _this3.collection.name, + query: _this3.mangoQuery, + op: _this3.op }); } else { return result; @@ -258,9 +274,7 @@ export var RxQueryBase = /*#__PURE__*/function () { * @return promise with deleted documents */; _proto.remove = function remove() { - var ret; return this.exec().then(function (docs) { - ret = docs; if (Array.isArray(docs)) { // TODO use a bulk operation instead of running .remove() on each document return Promise.all(docs.map(function (doc) { @@ -269,8 +283,6 @@ export var RxQueryBase = /*#__PURE__*/function () { } else { return docs.remove(); } - }).then(function () { - return ret; }); } @@ -303,7 +315,7 @@ export var RxQueryBase = /*#__PURE__*/function () { _createClass(RxQueryBase, [{ key: "$", get: function get() { - var _this3 = this; + var _this4 = this; if (!this._$) { var results$ = this.collection.$.pipe( /** @@ -320,11 +332,11 @@ export var RxQueryBase = /*#__PURE__*/function () { startWith(null), // ensure query results are up to date. mergeMap(function () { - return _ensureEqual(_this3); + return _ensureEqual(_this4); }), // use the current result set, written by _ensureEqual(). map(function () { - return _this3._result; + return _this4._result; }), // do not run stuff above for each new subscriber, only once. shareReplay(RXJS_SHARE_REPLAY_DEFAULTS), @@ -344,11 +356,13 @@ export var RxQueryBase = /*#__PURE__*/function () { */ map(function (result) { var useResult = ensureNotFalsy(result); - if (_this3.op === 'count') { + if (_this4.op === 'count') { return useResult.count; - } else if (_this3.op === 'findOne') { + } else if (_this4.op === 'findOne') { // findOne()-queries emit RxDocument or null return useResult.docs.length === 0 ? null : useResult.docs[0]; + } else if (_this4.op === 'findByIds') { + return useResult.docsMap; } else { // find()-queries emit RxDocument[] // Flat copy the array so it won't matter if the user modifies it. @@ -539,12 +553,83 @@ function __ensureEqual(rxQuery) { return Promise.resolve(ret); // true if results have changed } +/** + * Runs the query over the storage instance + * of the collection. + * Does some optimizations to ensuer findById is used + * when specific queries are used. + */ +export function queryCollection(_x) { + return _queryCollection.apply(this, arguments); +} + +/** + * Returns true if the given query + * selects exactly one document by its id. + * Used to optimize performance because these kind of + * queries do not have to run over an index and can use get-by-id instead. + * Returns false if no query of that kind. + * Returns the document id otherwise. + */ +function _queryCollection() { + _queryCollection = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(rxQuery) { + var docs, collection, docId, docData, docsMap, preparedQuery, queryResult; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + docs = []; + collection = rxQuery.collection; + /** + * Optimizations shortcut. + * If query is find-one-document-by-id, + * then we do not have to use the slow query() method + * but instead can use findDocumentsById() + */ + if (!rxQuery.isFindOneByIdQuery) { + _context2.next = 13; + break; + } + docId = rxQuery.isFindOneByIdQuery; // first try to fill from docCache + docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId); + if (docData) { + _context2.next = 10; + break; + } + _context2.next = 8; + return collection.storageInstance.findDocumentsById([docId], false); + case 8: + docsMap = _context2.sent; + docData = docsMap[docId]; + case 10: + if (docData) { + docs.push(docData); + } + _context2.next = 18; + break; + case 13: + preparedQuery = rxQuery.getPreparedQuery(); + _context2.next = 16; + return collection.storageInstance.query(preparedQuery); + case 16: + queryResult = _context2.sent; + docs = queryResult.documents; + case 18: + return _context2.abrupt("return", docs); + case 19: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _queryCollection.apply(this, arguments); +} export function isFindOneByIdQuery(primaryPath, query) { if (!query.skip && query.selector && Object.keys(query.selector).length === 1 && query.selector[primaryPath]) { - if (typeof query.selector[primaryPath] === 'string') { - return query.selector[primaryPath]; - } else if (Object.keys(query.selector[primaryPath]).length === 1 && typeof query.selector[primaryPath].$eq === 'string') { - return query.selector[primaryPath].$eq; + var value = query.selector[primaryPath]; + if (typeof value === 'string') { + return value; + } else if (Object.keys(value).length === 1 && typeof value.$eq === 'string') { + return value.$eq; } } return false; diff --git a/dist/es/rx-query.js.map b/dist/es/rx-query.js.map index fe43b10ae9a..aa23b72eaa5 100644 --- a/dist/es/rx-query.js.map +++ b/dist/es/rx-query.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.js","names":["BehaviorSubject","firstValueFrom","merge","mergeMap","filter","map","startWith","distinctUntilChanged","shareReplay","sortObject","stringifyFilter","pluginMissing","clone","overwriteGetterForCaching","now","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","ensureNotFalsy","areRxDocumentArraysEqual","newRxError","runPluginHooks","createRxDocuments","calculateNewResults","triggerCacheReplacement","normalizeMangoQuery","queryCollection","rxQuery","docs","collection","isFindOneByIdQuery","docId","storageInstance","findDocumentsById","docsMap","docData","push","preparedQuery","getPreparedQuery","query","queryResult","documents","_queryCount","newQueryID","RxQueryBase","op","mangoQuery","id","_execOverDatabaseCount","_creationTime","_lastEnsureEqual","other","uncached","refCount$","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","_getDefaultQuery","schema","primaryPath","_setResultData","newResultData","docsData","docsDataMap","Map","count","time","primPath","doc","_dataSync$","getValue","set","length","_execOverDatabase","then","result","mode","database","allowSlowCount","queryObj","docsPromise","exec","throwIfMissing","name","_ensureEqual","$","toString","stringObj","value","JSON","stringify","hookInput","jsonSchema","storage","statics","prepareQuery","doesDocumentDataMatch","_deleted","queryMatcher","remove","ret","Array","isArray","Promise","all","update","_updateObj","where","_queryObj","sort","_params","skip","_amount","limit","_$","results$","pipe","changeEvent","isLocal","prev","curr","useResult","slice","usePreparedQuery","getQueryMatcher","selector","tunnelQueryCache","_queryCache","getByQuery","createRxQuery","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","forEach","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","runFullQueryAgain","changed","newResults","latestAfter","resolve","Object","keys","$eq","isInstanceOf","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n stringifyFilter,\n pluginMissing,\n clone,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './util';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData\n} from './types';\n\nimport {\n createRxDocuments\n} from './rx-document-prototype-merge';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport type { QueryMatcher } from 'event-reduce-js';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n // used by some plugins\n public other: any = {};\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string;\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docs: RxDocument[];\n count: number;\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n time: number;\n } | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly,\n public collection: RxCollection\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.docs.length === 0 ? null : useResult.docs[0];\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.docs.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from pouchdb\n */\n _setResultData(newResultData: RxDocumentData | number): void {\n\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n }\n\n const docs = createRxDocuments(\n this.collection,\n newResultData\n );\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n */\n const primPath = this.collection.schema.primaryPath;\n const docsDataMap = new Map();\n const docsData = docs.map(doc => {\n const docData: RxDocumentData = doc._dataSync$.getValue() as any;\n const id: string = docData[primPath] as any;\n docsDataMap.set(id, docData);\n return docData;\n });\n\n this._result = {\n docsData,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n return this.collection.storageInstance.count(preparedQuery).then(result => {\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n\n });\n }\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n\n\n /**\n * Instead of calling this.getPreparedQuery(),\n * we have to prepare the query for the query matcher\n * so that it does not contain modifications from the hooks\n * like the key compression.\n */\n const usePreparedQuery = this.collection.database.storage.statics.prepareQuery(\n schema,\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n );\n\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n this.collection.database.storage.statics.getQueryMatcher(\n schema,\n usePreparedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj, stringifyFilter);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n };\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n let ret: any;\n return this\n .exec()\n .then(docs => {\n ret = docs;\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n })\n .then(() => ret);\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection\n });\n\n let ret = new RxQueryBase(op, queryObj, collection);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensuer findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n const docId = rxQuery.isFindOneByIdQuery;\n const docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n const docData = docsMap[docId];\n if (docData) {\n docs.push(docData);\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string {\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n if (typeof query.selector[primaryPath] === 'string') {\n return query.selector[primaryPath];\n } else if (\n Object.keys(query.selector[primaryPath]).length === 1 &&\n typeof query.selector[primaryPath].$eq === 'string'\n ) {\n return query.selector[primaryPath].$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";AAAA,SACIA,eAAe,EACfC,cAAc,EAEdC,KAAK,QACF,MAAM;AACb,SACIC,QAAQ,EACRC,MAAM,EACNC,GAAG,EACHC,SAAS,EACTC,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GAAG;IACd,CAAC,CAAC;EACV;EACA,OAAOG,OAAO,CAACoD,OAAO,CAACvD,GAAG,CAAC,CAAC,CAAC;AACjC;;AA4CA,OAAO,SAASxE,kBAAkB,CAC9B+B,WAAmB,EACnBtB,KAAsB,EACR;EACd,IACI,CAACA,KAAK,CAAC0E,IAAI,IACX1E,KAAK,CAACwF,QAAQ,IACd+B,MAAM,CAACC,IAAI,CAACxH,KAAK,CAACwF,QAAQ,CAAC,CAACrD,MAAM,KAAK,CAAC,IACxCnC,KAAK,CAACwF,QAAQ,CAAClE,WAAW,CAAC,EAC7B;IACE,IAAI,OAAOtB,KAAK,CAACwF,QAAQ,CAAClE,WAAW,CAAC,KAAK,QAAQ,EAAE;MACjD,OAAOtB,KAAK,CAACwF,QAAQ,CAAClE,WAAW,CAAC;IACtC,CAAC,MAAM,IACHiG,MAAM,CAACC,IAAI,CAACxH,KAAK,CAACwF,QAAQ,CAAClE,WAAW,CAAC,CAAC,CAACa,MAAM,KAAK,CAAC,IACrD,OAAOnC,KAAK,CAACwF,QAAQ,CAAClE,WAAW,CAAC,CAACmG,GAAG,KAAK,QAAQ,EACrD;MACE,OAAOzH,KAAK,CAACwF,QAAQ,CAAClE,WAAW,CAAC,CAACmG,GAAG;IAC1C;EACJ;EACA,OAAO,KAAK;AAChB;AAIA,OAAO,SAASC,YAAY,CAACC,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAYtH,WAAW;AACrC"} \ No newline at end of file +{"version":3,"file":"rx-query.js","names":["BehaviorSubject","firstValueFrom","merge","mergeMap","filter","map","startWith","distinctUntilChanged","shareReplay","sortObject","stringifyFilter","pluginMissing","clone","overwriteGetterForCaching","now","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","ensureNotFalsy","areRxDocumentArraysEqual","newRxError","runPluginHooks","calculateNewResults","triggerCacheReplacement","normalizeMangoQuery","_queryCount","newQueryID","RxQueryBase","op","mangoQuery","collection","id","_execOverDatabaseCount","_creationTime","_lastEnsureEqual","other","uncached","refCount$","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","_getDefaultQuery","isFindOneByIdQuery","schema","primaryPath","_setResultData","newResultData","docsData","docsMap","Map","docsDataMap","count","docs","time","Array","from","values","docData","_docCache","getCachedRxDocument","doc","set","primary","_data","length","_execOverDatabase","preparedQuery","getPreparedQuery","storageInstance","result","mode","database","allowSlowCount","queryObj","ids","selector","$in","ret","mustBeQueried","forEach","getLatestDocumentDataIfExists","_deleted","push","findDocumentsById","Object","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","$","toString","stringObj","value","JSON","stringify","hookInput","rxQuery","jsonSchema","storage","statics","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","update","_updateObj","where","_queryObj","sort","_params","skip","_amount","limit","_$","results$","pipe","changeEvent","isLocal","prev","curr","useResult","slice","usePreparedQuery","getQueryMatcher","tunnelQueryCache","_queryCache","getByQuery","createRxQuery","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","runFullQueryAgain","changed","newResults","latestAfter","resolve","docId","queryResult","documents","keys","$eq","isInstanceOf","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n stringifyFilter,\n pluginMissing,\n clone,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData\n} from './types';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport type { QueryMatcher } from 'event-reduce-js';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n // used by some plugins\n public other: any = {};\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string;\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docsMap: Map>;\n docs: RxDocument[];\n count: number;\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n time: number;\n } | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly>,\n public collection: RxCollection\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.docs.length === 0 ? null : useResult.docs[0];\n } else if (this.op === 'findByIds') {\n return useResult.docsMap;\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.docs.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from the storage\n */\n _setResultData(newResultData: RxDocumentData[] | number | Map>): void {\n\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsMap: new Map(),\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const docsDataMap = new Map();\n const docsMap = new Map();\n const docs = newResultData.map(docData => this.collection._docCache.getCachedRxDocument(docData));\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n */\n const docsData = docs.map(doc => {\n docsDataMap.set(doc.primary, doc._data);\n docsMap.set(doc.primary, doc);\n return doc._data;\n });\n\n this._result = {\n docsData,\n docsMap,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n async _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n const result = await this.collection.storageInstance.count(preparedQuery);\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n }\n\n if (this.op === 'findByIds') {\n const ids: string[] = ensureNotFalsy(this.mangoQuery.selector as any)[this.collection.schema.primaryPath].$in;\n const ret = new Map>();\n const mustBeQueried: string[] = [];\n // first try to fill from docCache\n ids.forEach(id => {\n const docData = this.collection._docCache.getLatestDocumentDataIfExists(id);\n if (docData) {\n if (!docData._deleted) {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(id, doc);\n }\n } else {\n mustBeQueried.push(id);\n }\n });\n // everything which was not in docCache must be fetched from the storage\n if (mustBeQueried.length > 0) {\n const docs = await this.collection.storageInstance.findDocumentsById(mustBeQueried, false);\n Object.values(docs).forEach(docData => {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret as any;\n }\n\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n\n\n /**\n * Instead of calling this.getPreparedQuery(),\n * we have to prepare the query for the query matcher\n * so that it does not contain modifications from the hooks\n * like the key compression.\n */\n const usePreparedQuery = this.collection.database.storage.statics.prepareQuery(\n schema,\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n );\n\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n this.collection.database.storage.statics.getQueryMatcher(\n schema,\n usePreparedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj, stringifyFilter);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n };\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n return this\n .exec()\n .then(docs => {\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n });\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection\n });\n\n let ret = new RxQueryBase(op, queryObj, collection);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensuer findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n const docId = rxQuery.isFindOneByIdQuery;\n\n // first try to fill from docCache\n let docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (!docData) {\n // otherwise get from storage\n const docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n docData = docsMap[docId];\n }\n if (docData) {\n docs.push(docData);\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string {\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n const value: any = query.selector[primaryPath];\n if (typeof value === 'string') {\n return value;\n } else if (\n Object.keys(value).length === 1 &&\n typeof value.$eq === 'string'\n ) {\n return value.$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";;;AAAA,SACIA,eAAe,EACfC,cAAc,EAEdC,KAAK,QACF,MAAM;AACb,SACIC,QAAQ,EACRC,MAAM,EACNC,GAAG,EACHC,SAAS,EACTC,oBAAoB,EACpBC,WAAW,QACR,gBAAgB;AACvB,SACIC,UAAU,EACVC,eAAe,EACfC,aAAa,EACbC,KAAK,EACLC,yBAAyB,EACzBC,GAAG,EACHC,qBAAqB,EACrBC,0BAA0B,EAC1BC,cAAc,EACdC,wBAAwB,QACrB,iBAAiB;AACxB,SACIC,UAAU,QACP,YAAY;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O,EAAE;YACTL,IAAI,CAAC8B,IAAI,CAACzB,OAAO,CAAC;UACtB;UAAC;UAAA;QAAA;UAEKS,aAAa,GAAGkC,OAAO,CAACjC,gBAAgB,EAAE;UAAA;UAAA,OACtBvC,UAAU,CAACwC,eAAe,CAACuB,KAAK,CAACzB,aAAa,CAAC;QAAA;UAAnE+F,WAAW;UACjB7G,IAAI,GAAG6G,WAAW,CAACC,SAAS;QAAC;UAAA,kCAE1B9G,IAAI;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAEd;EAAA;AAAA;AAUD,OAAO,SAASV,kBAAkB,CAC9BE,WAAmB,EACnB+C,KAAsB,EACR;EACd,IACI,CAACA,KAAK,CAAC0B,IAAI,IACX1B,KAAK,CAAChB,QAAQ,IACdS,MAAM,CAAC+E,IAAI,CAACxE,KAAK,CAAChB,QAAQ,CAAC,CAACX,MAAM,KAAK,CAAC,IACxC2B,KAAK,CAAChB,QAAQ,CAAC/B,WAAW,CAAC,EAC7B;IACE,IAAMoD,KAAU,GAAGL,KAAK,CAAChB,QAAQ,CAAC/B,WAAW,CAAC;IAC9C,IAAI,OAAOoD,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHZ,MAAM,CAAC+E,IAAI,CAACnE,KAAK,CAAC,CAAChC,MAAM,KAAK,CAAC,IAC/B,OAAOgC,KAAK,CAACoE,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAOpE,KAAK,CAACoE,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIA,OAAO,SAASC,YAAY,CAACC,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAY7I,WAAW;AACrC"} \ No newline at end of file diff --git a/dist/es/rx-schema-helper.js b/dist/es/rx-schema-helper.js index eafa3f73fa8..7e5f3030fc9 100644 --- a/dist/es/rx-schema-helper.js +++ b/dist/es/rx-schema-helper.js @@ -1,6 +1,6 @@ import objectPath from 'object-path'; import { newRxError } from './rx-error'; -import { clone, flatClone, isMaybeReadonlyArray, RX_META_LWT_MINIMUM, sortObject, trimDots } from './util'; +import { flatClone, isMaybeReadonlyArray, RX_META_LWT_MINIMUM, sortObject, trimDots } from './plugins/utils'; /** * Helper function to create a valid RxJsonSchema @@ -92,18 +92,7 @@ export function getComposedPrimaryKeyOfDocumentData(jsonSchema, documentData) { * @return RxJsonSchema - ordered and filled */ export function normalizeRxJsonSchema(jsonSchema) { - // TODO do we need the deep clone() here? - var normalizedSchema = sortObject(clone(jsonSchema)); - - // indexes must NOT be sorted because sort order is important here. - if (jsonSchema.indexes) { - normalizedSchema.indexes = Array.from(jsonSchema.indexes); - } - - // primaryKey.fields must NOT be sorted because sort order is important here. - if (typeof normalizedSchema.primaryKey === 'object' && typeof jsonSchema.primaryKey === 'object') { - normalizedSchema.primaryKey.fields = jsonSchema.primaryKey.fields; - } + var normalizedSchema = sortObject(jsonSchema, true); return normalizedSchema; } diff --git a/dist/es/rx-schema-helper.js.map b/dist/es/rx-schema-helper.js.map index 5bd90d8355d..c4e6eb13d01 100644 --- a/dist/es/rx-schema-helper.js.map +++ b/dist/es/rx-schema-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema-helper.js","names":["objectPath","newRxError","clone","flatClone","isMaybeReadonlyArray","RX_META_LWT_MINIMUM","sortObject","trimDots","getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","ret","get","fillPrimaryKey","primaryPath","jsonSchema","documentData","cloned","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","args","schema","getPrimaryFieldOfPrimaryKey","key","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","indexes","Array","from","schemaObj","additionalProperties","hasOwnProperty","keyCompression","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","concat","filter","includes","elem","pos","arr","indexOf","index","arIndex","modifiedIndex","lwt","minimum","maximum","multipleOf","Object","keys","forEach","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { newRxError } from './rx-error';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types';\nimport { clone, flatClone, isMaybeReadonlyArray, RX_META_LWT_MINIMUM, sortObject, trimDots } from './util';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(/\\./g, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = objectPath.get(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n const cloned = flatClone(documentData);\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (cloned as any)[primaryPath] = newPrimary;\n return cloned;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = objectPath.get(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n // TODO do we need the deep clone() here?\n const normalizedSchema: RxJsonSchema = sortObject(clone(jsonSchema));\n\n // indexes must NOT be sorted because sort order is important here.\n if (jsonSchema.indexes) {\n normalizedSchema.indexes = Array.from(jsonSchema.indexes);\n }\n\n // primaryKey.fields must NOT be sorted because sort order is important here.\n if (\n typeof normalizedSchema.primaryKey === 'object' &&\n typeof jsonSchema.primaryKey === 'object'\n ) {\n normalizedSchema.primaryKey.fields = jsonSchema.primaryKey.fields;\n }\n\n\n\n return normalizedSchema;\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!schemaObj.hasOwnProperty('keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n /**\n * TODO we should not need to add the internal fields to the schema.\n * Better remove the fields before validation.\n */\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n schemaObj.required = schemaObj.required\n .concat(finalFields as any)\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (schemaObj.indexes) {\n schemaObj.indexes = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n if (!arIndex.includes(primaryPath)) {\n const modifiedIndex = arIndex.slice(0);\n modifiedIndex.push(primaryPath);\n return modifiedIndex;\n }\n return arIndex;\n });\n }\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":"AAAA,OAAOA,UAAU,MAAM,aAAa;AACpC,SAASC,UAAU,QAAQ,YAAY;AAWvC,SAASC,KAAK,EAAEC,SAAS,EAAEC,oBAAoB,EAAEC,mBAAmB,EAAEC,UAAU,EAAEC,QAAQ,QAAQ,QAAQ;;AAE1G;AACA;AACA;AACA;AACA,OAAO,SAASC,yBAAyB,CACrCC,OAAe,EACfC,UAAyB,EACM;EAAA;EAC/B,IAAMC,YAA6C,GAAGC,uBAAuB,CAAC;IAC1EH,OAAO,EAAPA,OAAO;IACPI,IAAI,EAAE,QAAQ;IACdH,UAAU,EAAEA,UAAiB;IAC7BI,UAAU,iCACLJ,UAAU,IAAG;MACVG,IAAI,EAAE,QAAQ;MACdE,SAA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CACN,IAAI,EACJ,KAAK,CACR;EACDiC,oBAAoB,EAAE;AAC1B,CAAU"} \ No newline at end of file +{"version":3,"file":"rx-schema-helper.js","names":["objectPath","newRxError","flatClone","isMaybeReadonlyArray","RX_META_LWT_MINIMUM","sortObject","trimDots","getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","ret","get","fillPrimaryKey","primaryPath","jsonSchema","documentData","cloned","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","args","schema","getPrimaryFieldOfPrimaryKey","key","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","schemaObj","additionalProperties","hasOwnProperty","keyCompression","indexes","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","concat","filter","includes","elem","pos","arr","indexOf","index","arIndex","modifiedIndex","lwt","minimum","maximum","multipleOf","Object","keys","forEach","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { newRxError } from './rx-error';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types';\nimport {\n flatClone,\n isMaybeReadonlyArray,\n RX_META_LWT_MINIMUM,\n sortObject,\n trimDots\n} from './plugins/utils';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(/\\./g, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = objectPath.get(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n const cloned = flatClone(documentData);\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (cloned as any)[primaryPath] = newPrimary;\n return cloned;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = objectPath.get(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n const normalizedSchema: RxJsonSchema = sortObject(jsonSchema, true);\n return normalizedSchema;\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!schemaObj.hasOwnProperty('keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n /**\n * TODO we should not need to add the internal fields to the schema.\n * Better remove the fields before validation.\n */\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n schemaObj.required = schemaObj.required\n .concat(finalFields as any)\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (schemaObj.indexes) {\n schemaObj.indexes = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n if (!arIndex.includes(primaryPath)) {\n const modifiedIndex = arIndex.slice(0);\n modifiedIndex.push(primaryPath);\n return modifiedIndex;\n }\n return arIndex;\n });\n }\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":"AAAA,OAAOA,UAAU,MAAM,aAAa;AACpC,SAASC,UAAU,QAAQ,YAAY;AAWvC,SACIC,SAAS,EACTC,oBAAoB,EACpBC,mBAAmB,EACnB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ACR;EACD8B,oBAAoB,EAAE;AAC1B,CAAU"} \ No newline at end of file diff --git a/dist/es/rx-schema.js b/dist/es/rx-schema.js index ebefd557854..55b791e4cdb 100644 --- a/dist/es/rx-schema.js +++ b/dist/es/rx-schema.js @@ -1,6 +1,6 @@ import _createClass from "@babel/runtime/helpers/createClass"; import deepEqual from 'fast-deep-equal'; -import { overwriteGetterForCaching, flatClone, isMaybeReadonlyArray, fastUnsecureHash } from './util'; +import { overwriteGetterForCaching, flatClone, isMaybeReadonlyArray, fastUnsecureHash } from './plugins/utils'; import { newRxError } from './rx-error'; import { runPluginHooks } from './hooks'; import { defineGetterSetter } from './rx-document'; diff --git a/dist/es/rx-schema.js.map b/dist/es/rx-schema.js.map index fddbe2adfc5..9f62ab9570b 100644 --- a/dist/es/rx-schema.js.map +++ b/dist/es/rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema.js","names":["deepEqual","overwriteGetterForCaching","flatClone","isMaybeReadonlyArray","fastUnsecureHash","newRxError","runPluginHooks","defineGetterSetter","fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","getFinalFields","getPrimaryFieldOfPrimaryKey","normalizeRxJsonSchema","overwritable","RxSchema","jsonSchema","indexes","getIndexes","primaryPath","primaryKey","finalFields","validateChange","dataBefore","dataAfter","forEach","fieldName","schema","fillObjectWithDefaults","obj","Object","entries","defaultValues","filter","k","hasOwnProperty","v","getDocumentPrototype","proto","getPrimaryOfDocumentData","documentData","version","values","properties","JSON","stringify","map","index","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","useJsonSchema","deepFreezeWhenDevMode","isInstanceOf","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\n\nimport {\n overwriteGetterForCaching,\n flatClone,\n isMaybeReadonlyArray,\n fastUnsecureHash\n} from './util';\nimport {\n newRxError,\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport {\n defineGetterSetter\n} from './rx-document';\n\nimport type {\n DeepMutable,\n DeepReadonly, MaybeReadonly,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n normalizeRxJsonSchema\n} from './rx-schema-helper';\nimport { overwritable } from './overwritable';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => (v as any).hasOwnProperty('default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n */\n public get hash(): string {\n return overwriteGetterForCaching(\n this,\n 'hash',\n fastUnsecureHash(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * fills all unset fields with default-values if set\n */\n fillObjectWithDefaults(obj: any): any {\n obj = flatClone(obj);\n Object\n .entries(this.defaultValues)\n .filter(([k]) => !obj.hasOwnProperty(k) || typeof obj[k] === 'undefined')\n .forEach(([k, v]) => obj[k] = v);\n return obj;\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto = {};\n defineGetterSetter(this, proto, '');\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";AAAA,OAAOA,SAAS,MAAM,iBAAiB;AAEvC,SACIC,yBAAyB,EACzBC,SAAS,EACTC,oBAAoB,EACpBC,gBAAgB,QACb,QAAQ;AACf,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QACX,SAAS;AAChB,SACIC,kBAAkB,QACf,eAAe;AAStB,S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-schema.js","names":["deepEqual","overwriteGetterForCaching","flatClone","isMaybeReadonlyArray","fastUnsecureHash","newRxError","runPluginHooks","defineGetterSetter","fillWithDefaultSettings","getComposedPrimaryKeyOfDocumentData","getFinalFields","getPrimaryFieldOfPrimaryKey","normalizeRxJsonSchema","overwritable","RxSchema","jsonSchema","indexes","getIndexes","primaryPath","primaryKey","finalFields","validateChange","dataBefore","dataAfter","forEach","fieldName","schema","fillObjectWithDefaults","obj","Object","entries","defaultValues","filter","k","hasOwnProperty","v","getDocumentPrototype","proto","getPrimaryOfDocumentData","documentData","version","values","properties","JSON","stringify","map","index","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","useJsonSchema","deepFreezeWhenDevMode","isInstanceOf","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\n\nimport {\n overwriteGetterForCaching,\n flatClone,\n isMaybeReadonlyArray,\n fastUnsecureHash\n} from './plugins/utils';\nimport {\n newRxError,\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport {\n defineGetterSetter\n} from './rx-document';\n\nimport type {\n DeepMutable,\n DeepReadonly, MaybeReadonly,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n normalizeRxJsonSchema\n} from './rx-schema-helper';\nimport { overwritable } from './overwritable';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => (v as any).hasOwnProperty('default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n */\n public get hash(): string {\n return overwriteGetterForCaching(\n this,\n 'hash',\n fastUnsecureHash(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * fills all unset fields with default-values if set\n */\n fillObjectWithDefaults(obj: any): any {\n obj = flatClone(obj);\n Object\n .entries(this.defaultValues)\n .filter(([k]) => !obj.hasOwnProperty(k) || typeof obj[k] === 'undefined')\n .forEach(([k, v]) => obj[k] = v);\n return obj;\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto = {};\n defineGetterSetter(this, proto, '');\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";AAAA,OAAOA,SAAS,MAAM,iBAAiB;AAEvC,SACIC,yBAAyB,EACzBC,SAAS,EACTC,oBAAoB,EACpBC,gBAAgB,QACb,iBAAiB;AACxB,SACIC,UAAU,QACP,YAAY;AACnB,SACIC,cAAc,QACX,SAAS;AAChB,SACIC,kBAAkB,QACf,eAAe;AAStB,SACIC,uBAAuB,EACvBC,mCAAmC,EACnCC,cAAc,EACdC,2BAA2B,EAC3BC,qBAAqB,QAClB,oBAAoB;AAC3B,SAASC,YAAY,QAAQ,gBAAgB;AAE7C,WAAaC,QAAQ;EAKjB,kBACoBC,UAAmD,EACrE;IAAA,KADkBA,UAAmD,GAAnDA,UAAmD;IAEnE,IAAI,CAACC,OAAO,GAAGC,UAAU,CAAC,IAAI,CAACF,UAAU,CAAC;;IAE1C;IACA,IAAI,CAACG,WAAW,GAAGP,2BAA2B,CAAC,IAAI,CAACI,UAAU,CAACI,UAAU,CAAC;IAE1E,IAAI,CAACC,WAAW,GAAGV,cAAc,CAAC,IAAI,CAACK,UAAU,CAAC;EACtD;EAAC;EA8BD;AACJ;AACA;AACA;AACA;AACA;EALI,OAMAM,cAAc,GAAd,wBAAeC,UAAe,EAAEC,SAAc,EAAQ;IAAA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EAAA,EAAC;AACvB;AAEA,OAAO,SAASG,cAAc,CAC1BpC,UAA2B,EAEhB;EAAA,IADXqC,iBAAiB,uEAAG,IAAI;EAExB,IAAIA,iBAAiB,EAAE;IACnB9C,cAAc,CAAC,mBAAmB,EAAES,UAAU,CAAC;EACnD;EAEA,IAAIsC,aAAa,GAAG7C,uBAAuB,CAACO,UAAU,CAAC;EACvDsC,aAAa,GAAGzC,qBAAqB,CAACyC,aAAa,CAAC;EACpDxC,YAAY,CAACyC,qBAAqB,CAACD,aAAa,CAAC;EAEjD,IAAM3B,MAAM,GAAG,IAAIZ,QAAQ,CAACuC,aAAa,CAAC;EAC1C/C,cAAc,CAAC,gBAAgB,EAAEoB,MAAM,CAAC;EACxC,OAAOA,MAAM;AACjB;AAEA,OAAO,SAAS6B,YAAY,CAAC3B,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAYd,QAAQ;AAClC;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAAS0C,mBAAmB,CAA4C9B,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB"} \ No newline at end of file diff --git a/dist/es/rx-storage-helper.js b/dist/es/rx-storage-helper.js index e1c7050a71c..861d962c7a1 100644 --- a/dist/es/rx-storage-helper.js +++ b/dist/es/rx-storage-helper.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * Helper functions for accessing the RxStorage instances. */ @@ -5,26 +7,46 @@ import { overwritable } from './overwritable'; import { newRxError } from './rx-error'; import { fillPrimaryKey, getPrimaryFieldOfPrimaryKey } from './rx-schema-helper'; -import { createRevision, defaultHashFunction, ensureNotFalsy, firstPropertyValueOfObject, flatClone, getDefaultRevision, getDefaultRxDocumentMeta, now, randomCouchString } from './util'; +import { createRevision, defaultHashFunction, ensureNotFalsy, firstPropertyValueOfObject, flatClone, getDefaultRevision, getDefaultRxDocumentMeta, now, randomCouchString } from './plugins/utils'; +export var INTERNAL_STORAGE_NAME = '_rxdb_internal'; +export var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; +export function getSingleDocument(_x, _x2) { + return _getSingleDocument.apply(this, arguments); +} + /** * Writes a single document, * throws RxStorageBulkWriteError on failure */ -export var writeSingle = function writeSingle(instance, writeRow, context) { - try { - return Promise.resolve(instance.bulkWrite([writeRow], context)).then(function (writeResult) { - if (Object.keys(writeResult.error).length > 0) { - var error = firstPropertyValueOfObject(writeResult.error); - throw error; - } else { - var ret = firstPropertyValueOfObject(writeResult.success); - return ret; +function _getSingleDocument() { + _getSingleDocument = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(storageInstance, documentId) { + var results, doc; + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return storageInstance.findDocumentsById([documentId], false); + case 2: + results = _context.sent; + doc = results[documentId]; + if (!doc) { + _context.next = 8; + break; + } + return _context.abrupt("return", doc); + case 8: + return _context.abrupt("return", null); + case 9: + case "end": + return _context.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; + }, _callee); + })); + return _getSingleDocument.apply(this, arguments); +} +export function writeSingle(_x3, _x4, _x5) { + return _writeSingle.apply(this, arguments); +} /** * Checkpoints must be stackable over another. @@ -32,22 +54,33 @@ export var writeSingle = function writeSingle(instance, writeRow, context) { * like the sharding plugin, where a checkpoint only represents * the document state from some, but not all shards. */ -export var getSingleDocument = function getSingleDocument(storageInstance, documentId) { - try { - return Promise.resolve(storageInstance.findDocumentsById([documentId], false)).then(function (results) { - var doc = results[documentId]; - if (doc) { - return doc; - } else { - return null; +function _writeSingle() { + _writeSingle = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(instance, writeRow, context) { + var writeResult, error, ret; + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return instance.bulkWrite([writeRow], context); + case 2: + writeResult = _context2.sent; + if (!(Object.keys(writeResult.error).length > 0)) { + _context2.next = 8; + break; + } + error = firstPropertyValueOfObject(writeResult.error); + throw error; + case 8: + ret = firstPropertyValueOfObject(writeResult.success); + return _context2.abrupt("return", ret); + case 10: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; -export var INTERNAL_STORAGE_NAME = '_rxdb_internal'; -export var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; + }, _callee2); + })); + return _writeSingle.apply(this, arguments); +} export function stackCheckpoints(checkpoints) { return Object.assign.apply(Object, [{}].concat(checkpoints)); } @@ -70,10 +103,17 @@ export function storageChangeEventToRxChangeEvent(isLocal, rxStorageChangeEvent, export function throwIfIsStorageWriteError(collection, documentId, writeData, error) { if (error) { if (error.status === 409) { - throw newRxError('COL19', { + throw newRxError('CONFLICT', { + collection: collection.name, + id: documentId, + writeError: error, + data: writeData + }); + } else if (error.status === 422) { + throw newRxError('VD2', { collection: collection.name, id: documentId, - error: error, + writeError: error, data: writeData }); } else { @@ -156,7 +196,8 @@ bulkWriteRows, context) { documentId: id, isError: true, status: 510, - writeRow: writeRow + writeRow: writeRow, + attachmentId: attachmentId }; errors[id] = attachmentError; } else { @@ -233,7 +274,8 @@ bulkWriteRows, context) { documentInDb: documentInDb, isError: true, status: 510, - writeRow: writeRow + writeRow: writeRow, + attachmentId: attachmentId }; } return true; @@ -378,7 +420,6 @@ export function getUniqueDeterministicEventKey(storageInstance, primaryPath, wri var eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev; return eventKey; } - /** * Wraps the normal storageInstance of a RxCollection * to ensure that all access is properly using the hooks @@ -452,13 +493,14 @@ rxJsonSchema) { * If you make a plugin that relies on having its own revision * stored into the storage, use this.originalStorageInstance.bulkWrite() instead. */ - data._rev = createRevision(database.hashFunction, data, writeRow.previous); + data._rev = createRevision(database.token, writeRow.previous); return { document: data, previous: writeRow.previous }; } var ret = { + originalStorageInstance: storageInstance, schema: storageInstance.schema, internals: storageInstance.internals, collectionName: storageInstance.collectionName, @@ -495,7 +537,7 @@ rxJsonSchema) { return { previous: error.documentInDb, document: Object.assign({}, error.writeRow.document, { - _rev: createRevision(database.hashFunction, error.writeRow.document, error.documentInDb) + _rev: createRevision(database.token, error.documentInDb) }) }; }); @@ -578,7 +620,6 @@ rxJsonSchema) { }); } }; - ret.originalStorageInstance = storageInstance; return ret; } diff --git a/dist/es/rx-storage-helper.js.map b/dist/es/rx-storage-helper.js.map index 3bf4c88a61f..7fef7694740 100644 --- a/dist/es/rx-storage-helper.js.map +++ b/dist/es/rx-storage-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-helper.js","names":["overwritable","newRxError","fillPrimaryKey","getPrimaryFieldOfPrimaryKey","createRevision","defaultHashFunction","ensureNotFalsy","firstPropertyValueOfObject","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","now","randomCouchString","writeSingle","instance","writeRow","context","bulkWrite","writeResult","Object","keys","error","length","ret","success","getSingleDocument","storageInstance","documentId","findDocumentsById","results","doc","INTERNAL_STORAGE_NAME","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","stackCheckpoints","checkpoints","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","documentData","previousDocumentData","eventId","collectionName","name","undefined","startTime","endTime","operation","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","id","data","getNewestOfDocumentStates","primaryPath","docs","forEach","_meta","lwt","categorizeBulkWriteRows","docsInDb","bulkWriteRows","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","changedDocumentIds","eventBulk","events","checkpoint","attachmentsAdd","attachmentsRemove","attachmentsUpdate","docsByIdIsMap","get","document","documentInDb","attachmentError","insertedIsDeleted","_deleted","entries","_attachments","attachmentId","attachmentData","isError","push","stripAttachmentsDataFromRow","getUniqueDeterministicEventKey","stripAttachmentsDataFromDocument","previous","revInDb","_rev","err","updatedRow","find","previousAttachmentData","newDigest","digest","writeDoc","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","type","useDoc","flatCloneDocWithMeta","docId","binaryValues","binary","map","v","join","eventKey","databaseName","getWrappedStorageInstance","database","rxJsonSchema","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","metaFieldName","hasOwnProperty","dataBefore","dataAfter","hashFunction","internals","options","rows","toStorageWriteRows","row","lockedRun","then","reInsertErrors","values","filter","useWriteResult","reInserts","subResult","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","close","changeStream","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","originalStorageInstance","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","jsonSchema","encrypted"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable';\nimport { newRxError } from './rx-error';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n ById,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageBulkWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys\n} from './types';\nimport {\n createRevision,\n defaultHashFunction,\n ensureNotFalsy,\n firstPropertyValueOfObject,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now,\n randomCouchString\n} from './util';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | null> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[documentId];\n if (doc) {\n return doc;\n } else {\n return null;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (Object.keys(writeResult.error).length > 0) {\n const error = firstPropertyValueOfObject(writeResult.error);\n throw error;\n } else {\n const ret = firstPropertyValueOfObject(writeResult.success);\n return ret;\n }\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n eventId: rxStorageChangeEvent.eventId,\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n startTime: rxStorageChangeEvent.startTime,\n endTime: rxStorageChangeEvent.endTime,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageBulkWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('COL19', {\n collection: collection.name,\n id: documentId,\n error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * From a list of documents,\n * it will return the document that has the 'newest' state\n * which must be used to create the correct checkpoint\n * for the whole list.\n */\nexport function getNewestOfDocumentStates(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData {\n let ret: RxDocumentData | null = null;\n docs.forEach(doc => {\n if (\n !ret ||\n doc._meta.lwt > ret._meta.lwt ||\n (\n doc._meta.lwt === ret._meta.lwt &&\n (doc as any)[primaryPath] > (ret as any)[primaryPath]\n )\n ) {\n ret = doc;\n }\n\n });\n return ensureNotFalsy(ret as any);\n}\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This can be a Map for better performance\n * but it can also be an object because some storages\n * need to work with something that is JSON-stringify-able\n * and we do not want to transform a big object into a Map\n * each time we use it.\n */\n docsInDb:\n Map[StringKeys] | string, RxDocumentData> |\n ById>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: ById> = {};\n const changedDocumentIds: RxDocType[StringKeys][] = [];\n const eventBulk: EventBulk>, any> = {\n id: randomCouchString(10),\n events: [],\n checkpoint: null,\n context\n };\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n\n\n const startTime = now();\n\n const docsByIdIsMap = typeof docsInDb.get === 'function';\n\n bulkWriteRows.forEach(writeRow => {\n const id = writeRow.document[primaryPath];\n const documentInDb = docsByIdIsMap ? (docsInDb as any).get(id) : (docsInDb as any)[id];\n let attachmentError: RxStorageBulkWriteError | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = writeRow.document._deleted ? true : false;\n Object.entries(writeRow.document._attachments).forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n isError: true,\n status: 510,\n writeRow\n };\n errors[id as any] = attachmentError;\n } else {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n }\n });\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n } else {\n bulkInsertDocs.push(writeRow as any);\n }\n }\n\n if (!insertedIsDeleted) {\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n operation: 'INSERT',\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(writeRow.document) : writeRow.document as any,\n previousDocumentData: hasAttachments && writeRow.previous ? stripAttachmentsDataFromDocument(writeRow.previous) : writeRow.previous as any,\n startTime,\n endTime: now()\n });\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !writeRow.previous\n ) ||\n (\n !!writeRow.previous &&\n revInDb !== writeRow.previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageBulkWriteError = {\n isError: true,\n status: 409,\n documentId: id as any,\n writeRow: writeRow,\n documentInDb\n };\n errors[id as any] = err;\n return;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (writeRow.document._deleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (writeRow.previous) {\n Object\n .keys(writeRow.previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: id as any,\n attachmentId\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(writeRow.document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n documentInDb: documentInDb,\n isError: true,\n status: 510,\n writeRow\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(writeRow.document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData\n });\n }\n }\n });\n }\n }\n if (attachmentError) {\n errors[id as any] = attachmentError;\n } else {\n bulkUpdateDocs.push(updatedRow);\n }\n\n const writeDoc = writeRow.document;\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (writeRow.previous && writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n } else if (writeRow.previous && !writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n previousEventDocumentData = writeRow.previous;\n } else if (writeDoc._deleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(writeRow.document) as any;\n previousEventDocumentData = writeRow.previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n documentData: ensureNotFalsy(eventDocumentData),\n previousDocumentData: previousEventDocumentData,\n operation: operation,\n startTime,\n endTime: now()\n });\n }\n });\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n errors,\n changedDocumentIds,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n digest: defaultHashFunction(data),\n length: getAttachmentSize(data),\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\n/**\n * Each event is labeled with the id\n * to make it easy to filter out duplicates.\n */\nexport function getUniqueDeterministicEventKey(\n storageInstance: RxStorageInstance,\n primaryPath: string,\n writeRow: BulkWriteRow\n): string {\n const docId = writeRow.document[primaryPath];\n const binaryValues: boolean[] = [\n !!writeRow.previous,\n (writeRow.previous && writeRow.previous._deleted),\n !!writeRow.document._deleted\n ];\n const binary = binaryValues.map(v => v ? '1' : '0').join('');\n const eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev;\n return eventKey;\n}\n\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): RxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!writeRow.document._meta.hasOwnProperty(metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.hashFunction,\n data,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: RxStorageInstance = {\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const reInsertErrors: RxStorageBulkWriteError[] = Object\n .values(writeResult.error)\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n return false;\n });\n\n if (reInsertErrors.length > 0) {\n const useWriteResult: typeof writeResult = {\n error: flatClone(writeResult.error),\n success: flatClone(writeResult.success)\n };\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n delete useWriteResult.error[error.documentId];\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.hashFunction,\n error.writeRow.document,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n useWriteResult.error = Object.assign(\n useWriteResult.error,\n subResult.error\n );\n useWriteResult.success = Object.assign(\n useWriteResult.success,\n subResult.success\n );\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId)\n );\n },\n getChangedDocumentsSince(limit: number, checkpoint?: any) {\n return database.lockedRun(\n () => storageInstance.getChangedDocumentsSince(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n (ret as any).originalStorageInstance = storageInstance;\n\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,gBAAgB;AAC7C,SAASC,UAAU,QAAQ,YAAY;AACvC,SACIC,cAAc,EACdC,2BAA2B,QACxB,oBAAoB;AAqB3B,SACIC,cAAc,EACdC,mBAAmB,EACnBC,cAAc,EACdC,0BAA0B,EAC1BC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,GAAG,EACHC,iBAAiB,QACd,QAAQ;AAkBf;AACA;AACA;AACA;AACA,WAAsBC,WAAW,YAAXA,WAAW,CAC7BC,QAAgD,EAChDC,QAAiC,EACjCC,OAAe;EAAA,IACmB;IAAA,uBACRF,QAAQ,CAACG,SAAS,CACxC,CAACF,QAAQ,CAAC,EACVC,OAAO,CACV,iBAHKE,WAAW;MAAA,IAIbC,MAAM,CAACC,IAAI,CAACF,WAAW,CAACG,KAAK,CAAC,CAACC,MAAM,GAAG,CAAC;QACzC,IAAMD,KAAK,GAAGd,0BAA0B,CAACW,WAAW,CAACG,KAAK,CAAC;QAC3D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AAE,CAAC,CAAC;EACjD;AACJ;AAEA,OAAO,SAASE,aAAa,CAACC,UAA6B,EAAW;EAClE,IACK,CAAC,CAACA,UAAU,CAACC,SAAS,IAAID,UAAU,CAACC,SAAS,CAACpJ,MAAM,GAAG,CAAC,IACzDmJ,UAAU,CAACtG,WAAW,IAAIsG,UAAU,CAACtG,WAAW,CAACuG,SAAU,EAC9D;IACE,OAAO,IAAI;EACf,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file +{"version":3,"file":"rx-storage-helper.js","names":["overwritable","newRxError","fillPrimaryKey","getPrimaryFieldOfPrimaryKey","createRevision","defaultHashFunction","ensureNotFalsy","firstPropertyValueOfObject","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","now","randomCouchString","INTERNAL_STORAGE_NAME","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","getSingleDocument","storageInstance","documentId","findDocumentsById","results","doc","writeSingle","instance","writeRow","context","bulkWrite","writeResult","Object","keys","error","length","ret","success","stackCheckpoints","checkpoints","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","documentData","previousDocumentData","eventId","collectionName","name","undefined","startTime","endTime","operation","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","id","writeError","data","getNewestOfDocumentStates","primaryPath","docs","forEach","_meta","lwt","categorizeBulkWriteRows","docsInDb","bulkWriteRows","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","changedDocumentIds","eventBulk","events","checkpoint","attachmentsAdd","attachmentsRemove","attachmentsUpdate","docsByIdIsMap","get","document","documentInDb","attachmentError","insertedIsDeleted","_deleted","entries","_attachments","attachmentId","attachmentData","isError","push","stripAttachmentsDataFromRow","getUniqueDeterministicEventKey","stripAttachmentsDataFromDocument","previous","revInDb","_rev","err","updatedRow","find","previousAttachmentData","newDigest","digest","writeDoc","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","type","useDoc","flatCloneDocWithMeta","docId","binaryValues","binary","map","v","join","eventKey","databaseName","getWrappedStorageInstance","database","rxJsonSchema","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","metaFieldName","hasOwnProperty","dataBefore","dataAfter","token","originalStorageInstance","internals","options","rows","toStorageWriteRows","row","lockedRun","then","reInsertErrors","values","filter","useWriteResult","reInserts","subResult","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","close","changeStream","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","jsonSchema","encrypted"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable';\nimport { newRxError } from './rx-error';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n ById,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys,\n RxStorageWriteErrorConflict,\n RxStorageWriteErrorAttachment\n} from './types';\nimport {\n createRevision,\n defaultHashFunction,\n ensureNotFalsy,\n firstPropertyValueOfObject,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now,\n randomCouchString\n} from './plugins/utils';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | null> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[documentId];\n if (doc) {\n return doc;\n } else {\n return null;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (Object.keys(writeResult.error).length > 0) {\n const error = firstPropertyValueOfObject(writeResult.error);\n throw error;\n } else {\n const ret = firstPropertyValueOfObject(writeResult.success);\n return ret;\n }\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n eventId: rxStorageChangeEvent.eventId,\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n startTime: rxStorageChangeEvent.startTime,\n endTime: rxStorageChangeEvent.endTime,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('CONFLICT', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else if (error.status === 422) {\n throw newRxError('VD2', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * From a list of documents,\n * it will return the document that has the 'newest' state\n * which must be used to create the correct checkpoint\n * for the whole list.\n */\nexport function getNewestOfDocumentStates(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData {\n let ret: RxDocumentData | null = null;\n docs.forEach(doc => {\n if (\n !ret ||\n doc._meta.lwt > ret._meta.lwt ||\n (\n doc._meta.lwt === ret._meta.lwt &&\n (doc as any)[primaryPath] > (ret as any)[primaryPath]\n )\n ) {\n ret = doc;\n }\n\n });\n return ensureNotFalsy(ret as any);\n}\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This can be a Map for better performance\n * but it can also be an object because some storages\n * need to work with something that is JSON-stringify-able\n * and we do not want to transform a big object into a Map\n * each time we use it.\n */\n docsInDb:\n Map[StringKeys] | string, RxDocumentData> |\n ById>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: ById> = {};\n const changedDocumentIds: RxDocType[StringKeys][] = [];\n const eventBulk: EventBulk>, any> = {\n id: randomCouchString(10),\n events: [],\n checkpoint: null,\n context\n };\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n\n\n const startTime = now();\n\n const docsByIdIsMap = typeof docsInDb.get === 'function';\n\n bulkWriteRows.forEach(writeRow => {\n const id = writeRow.document[primaryPath];\n const documentInDb = docsByIdIsMap ? (docsInDb as any).get(id) : (docsInDb as any)[id];\n let attachmentError: RxStorageWriteErrorAttachment | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = writeRow.document._deleted ? true : false;\n Object.entries(writeRow.document._attachments).forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n errors[id as any] = attachmentError;\n } else {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n }\n });\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n } else {\n bulkInsertDocs.push(writeRow as any);\n }\n }\n\n if (!insertedIsDeleted) {\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n operation: 'INSERT',\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(writeRow.document) : writeRow.document as any,\n previousDocumentData: hasAttachments && writeRow.previous ? stripAttachmentsDataFromDocument(writeRow.previous) : writeRow.previous as any,\n startTime,\n endTime: now()\n });\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !writeRow.previous\n ) ||\n (\n !!writeRow.previous &&\n revInDb !== writeRow.previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageWriteError = {\n isError: true,\n status: 409,\n documentId: id as any,\n writeRow: writeRow,\n documentInDb\n };\n errors[id as any] = err;\n return;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (writeRow.document._deleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (writeRow.previous) {\n Object\n .keys(writeRow.previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: id as any,\n attachmentId\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(writeRow.document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n documentInDb,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(writeRow.document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData\n });\n }\n }\n });\n }\n }\n if (attachmentError) {\n errors[id as any] = attachmentError;\n } else {\n bulkUpdateDocs.push(updatedRow);\n }\n\n const writeDoc = writeRow.document;\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (writeRow.previous && writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n } else if (writeRow.previous && !writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n previousEventDocumentData = writeRow.previous;\n } else if (writeDoc._deleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(writeRow.document) as any;\n previousEventDocumentData = writeRow.previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n documentData: ensureNotFalsy(eventDocumentData),\n previousDocumentData: previousEventDocumentData,\n operation: operation,\n startTime,\n endTime: now()\n });\n }\n });\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n errors,\n changedDocumentIds,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n digest: defaultHashFunction(data),\n length: getAttachmentSize(data),\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\n/**\n * Each event is labeled with the id\n * to make it easy to filter out duplicates.\n */\nexport function getUniqueDeterministicEventKey(\n storageInstance: RxStorageInstance,\n primaryPath: string,\n writeRow: BulkWriteRow\n): string {\n const docId = writeRow.document[primaryPath];\n const binaryValues: boolean[] = [\n !!writeRow.previous,\n (writeRow.previous && writeRow.previous._deleted),\n !!writeRow.document._deleted\n ];\n const binary = binaryValues.map(v => v ? '1' : '0').join('');\n const eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev;\n return eventKey;\n}\n\n\nexport type WrappedRxStorageInstance = RxStorageInstance & {\n originalStorageInstance: RxStorageInstance;\n};\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): WrappedRxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!writeRow.document._meta.hasOwnProperty(metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.token,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: WrappedRxStorageInstance = {\n originalStorageInstance: storageInstance,\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const reInsertErrors: RxStorageWriteErrorConflict[] = Object\n .values(writeResult.error)\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n return false;\n }) as any;\n\n if (reInsertErrors.length > 0) {\n const useWriteResult: typeof writeResult = {\n error: flatClone(writeResult.error),\n success: flatClone(writeResult.success)\n };\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n delete useWriteResult.error[error.documentId];\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.token,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n useWriteResult.error = Object.assign(\n useWriteResult.error,\n subResult.error\n );\n useWriteResult.success = Object.assign(\n useWriteResult.success,\n subResult.success\n );\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId)\n );\n },\n getChangedDocumentsSince(limit: number, checkpoint?: any) {\n return database.lockedRun(\n () => storageInstance.getChangedDocumentsSince(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n"],"mappings":";;AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,gBAAgB;AAC7C,SAASC,UAAU,QAAQ,YAAY;AACvC,SACIC,cAAc,EACdC,2BAA2B,QACxB,oBAAoB;AAuB3B,SACIC,cAAc,EACdC,mBAAmB,EACnBC,cAAc,EACdC,0BAA0B,EAC1BC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,GAAG,EACHC,iBAAiB,QACd,iBAAiB;AAExB,OAAO,IAAMC,qBAAqB,GAAG,gBAAgB;AACrD,OAAO,IAAMC,mCAAmC,GAAG,0BAA0B;AAE7E,gBAAsBC,iBAAiB;EAAA;AAAA;;AAavC;AACA;AACA;AACA;AAHA;EAAA,8EAbO,iBACHC,eAAuD,EACvDC,UAAkB;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEID,eAAe,CAACE,iBAAiB,CAAC,CAACD,UAAU,CAAC,EAAE,KAAK,CAAC;QAAA;UAAtEE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;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASuI,uCAAuC,CACnDC,MAAiD,EACnD;EACE,IAAIA,MAAM,CAACpG,MAAM,CAACqG,cAAc,EAAE;IAC9B,MAAMvK,UAAU,CAAC,KAAK,EAAE;MAAE0G,IAAI,EAAE;QAAE4D,MAAM,EAANA;MAAO;IAAE,CAAC,CAAC;EACjD;EACA,IAAIE,aAAa,CAACF,MAAM,CAACpG,MAAM,CAAC,EAAE;IAC9B,MAAMlE,UAAU,CAAC,KAAK,EAAE;MAAE0G,IAAI,EAAE;QAAE4D,MAAM,EAANA;MAAO;IAAE,CAAC,CAAC;EACjD;AACJ;AAEA,OAAO,SAASE,aAAa,CAACC,UAA6B,EAAW;EAClE,IACK,CAAC,CAACA,UAAU,CAACC,SAAS,IAAID,UAAU,CAACC,SAAS,CAAC7I,MAAM,GAAG,CAAC,IACzD4I,UAAU,CAACtG,WAAW,IAAIsG,UAAU,CAACtG,WAAW,CAACuG,SAAU,EAC9D;IACE,OAAO,IAAI;EACf,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file diff --git a/dist/es/rx-storage-multiinstance.js b/dist/es/rx-storage-multiinstance.js index 5c6aa2b184a..a624d2f802e 100644 --- a/dist/es/rx-storage-multiinstance.js +++ b/dist/es/rx-storage-multiinstance.js @@ -1,3 +1,5 @@ +import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; +import _regeneratorRuntime from "@babel/runtime/regenerator"; /** * When a persistend RxStorage is used in more the one JavaScript process, * the even stream of the changestream() function must be broadcasted to the other @@ -94,40 +96,48 @@ providedBroadcastChannel) { return changesFromOtherInstances$.asObservable().pipe(mergeWith(oldChangestream$)); }; var oldClose = instance.close.bind(instance); - instance.close = function () { - try { - closed = true; - sub.unsubscribe(); - broadcastChannel.removeEventListener('message', eventListener); - var _temp = function () { - if (!providedBroadcastChannel) { - return Promise.resolve(removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance)).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return oldClose(); - }) : oldClose()); - } catch (e) { - return Promise.reject(e); - } - }; + instance.close = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { + return _regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + closed = true; + sub.unsubscribe(); + broadcastChannel.removeEventListener('message', eventListener); + if (providedBroadcastChannel) { + _context.next = 6; + break; + } + _context.next = 6; + return removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance); + case 6: + return _context.abrupt("return", oldClose()); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); var oldRemove = instance.remove.bind(instance); - instance.remove = function () { - try { - closed = true; - sub.unsubscribe(); - broadcastChannel.removeEventListener('message', eventListener); - var _temp2 = function () { - if (!providedBroadcastChannel) { - return Promise.resolve(removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance)).then(function () {}); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(function () { - return oldRemove(); - }) : oldRemove()); - } catch (e) { - return Promise.reject(e); - } - }; + instance.remove = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() { + return _regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + closed = true; + sub.unsubscribe(); + broadcastChannel.removeEventListener('message', eventListener); + if (providedBroadcastChannel) { + _context2.next = 6; + break; + } + _context2.next = 6; + return removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance); + case 6: + return _context2.abrupt("return", oldRemove()); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); } //# sourceMappingURL=rx-storage-multiinstance.js.map \ No newline at end of file diff --git a/dist/es/rx-storage-multiinstance.js.map b/dist/es/rx-storage-multiinstance.js.map index a96d49a6136..9f2dd82e3ca 100644 --- a/dist/es/rx-storage-multiinstance.js.map +++ b/dist/es/rx-storage-multiinstance.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-multiinstance.js","names":["Subject","mergeWith","BroadcastChannel","BROADCAST_CHANNEL_BY_TOKEN","Map","getBroadcastChannelReference","databaseInstanceToken","databaseName","refObject","state","get","bc","refs","Set","set","add","removeBroadcastChannelReference","size","close","addRxStorageMultiInstanceSupport","storageName","instanceCreationParams","instance","providedBroadcastChannel","multiInstance","broadcastChannel","changesFromOtherInstances$","eventListener","msg","collectionName","version","schema","next","eventBulk","addEventListener","oldChangestream$","changeStream","closed","sub","subscribe","postMessage","asObservable","pipe","oldClose","bind","unsubscribe","removeEventListener","oldRemove","remove"],"sources":["../../src/rx-storage-multiinstance.ts"],"sourcesContent":["/**\n * When a persistend RxStorage is used in more the one JavaScript process,\n * the even stream of the changestream() function must be broadcasted to the other\n * RxStorageInstances of the same databaseName+collectionName.\n *\n * In the past this was done by RxDB but it makes more sense to do this\n * at the RxStorage level so that the broadcasting etc can all happen inside of a WebWorker\n * and not on the main thread.\n * Also it makes it less complex to stack up different RxStorages onto each other\n * like what we do with the in-memory plugin.\n *\n * This is intened to be used inside of createStorageInstance() of a storage.\n * Do not use this if the storage anyway broadcasts the events like when using MongoDB\n * or in the future W3C might introduce a way to listen to IndexedDB changes.\n */\n\nimport { Observable, Subject } from 'rxjs';\nimport { mergeWith } from 'rxjs/operators';\nimport type {\n EventBulk,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\n\nimport {\n BroadcastChannel\n} from 'broadcast-channel';\n\n/**\n * The broadcast-channel is reused by the databaseInstanceToken.\n * This is required so that it is easy to simulate multi-tab usage\n * in the test where different instances of the same RxDatabase must\n * have different broadcast channels.\n * But also it ensures that for each RxDatabase we only create a single\n * broadcast channel that can even be reused in the leader election plugin.\n *\n * TODO at the end of the unit tests,\n * we should ensure that all channels are closed and cleaned up.\n * Otherwise we have forgot something.\n */\nexport const BROADCAST_CHANNEL_BY_TOKEN: Map;\n /**\n * Contains all context objects that currently use the channel.\n * If this becomes empty, we can close the channel\n */\n refs: Set;\n}> = new Map();\n\n\nexport type RxStorageMultiInstanceBroadcastType = {\n storageName: string;\n collectionName: string;\n /**\n * collection.schema.version\n */\n version: number;\n databaseName: string;\n eventBulk: EventBulk;\n};\n\nexport function getBroadcastChannelReference(\n databaseInstanceToken: string,\n databaseName: string,\n refObject: any\n): BroadcastChannel {\n let state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n state = {\n /**\n * We have to use the databaseName instead of the databaseInstanceToken\n * in the BroadcastChannel name because different instances must end with the same\n * channel name to be able to broadcast messages between each other.\n */\n bc: new BroadcastChannel('RxDB:' + databaseName),\n refs: new Set()\n };\n BROADCAST_CHANNEL_BY_TOKEN.set(databaseInstanceToken, state);\n }\n state.refs.add(refObject);\n return state.bc;\n}\n\nexport function removeBroadcastChannelReference(\n databaseInstanceToken: string,\n refObject: any\n) {\n const state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n return;\n }\n state.refs.delete(refObject);\n if (state.refs.size === 0) {\n BROADCAST_CHANNEL_BY_TOKEN.delete(databaseInstanceToken);\n return state.bc.close();\n }\n}\n\n\nexport function addRxStorageMultiInstanceSupport(\n storageName: string,\n instanceCreationParams: RxStorageInstanceCreationParams,\n instance: RxStorageInstance,\n /**\n * If provided, that channel will be used\n * instead of an own one.\n */\n providedBroadcastChannel?: BroadcastChannel\n) {\n if (!instanceCreationParams.multiInstance) {\n return;\n }\n\n type Emit = EventBulk, any>;\n\n const broadcastChannel = providedBroadcastChannel ?\n providedBroadcastChannel :\n getBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance.databaseName,\n instance\n );\n\n const changesFromOtherInstances$: Subject = new Subject();\n\n\n const eventListener = (msg: RxStorageMultiInstanceBroadcastType) => {\n if (\n msg.storageName === storageName &&\n msg.databaseName === instanceCreationParams.databaseName &&\n msg.collectionName === instanceCreationParams.collectionName &&\n msg.version === instanceCreationParams.schema.version\n ) {\n changesFromOtherInstances$.next(msg.eventBulk);\n }\n };\n broadcastChannel.addEventListener('message', eventListener);\n\n const oldChangestream$ = instance.changeStream();\n\n let closed = false;\n const sub = oldChangestream$.subscribe(eventBulk => {\n if (closed) {\n return;\n }\n broadcastChannel.postMessage({\n storageName: storageName,\n databaseName: instanceCreationParams.databaseName,\n collectionName: instanceCreationParams.collectionName,\n version: instanceCreationParams.schema.version,\n eventBulk\n });\n });\n\n instance.changeStream = function (): Observable {\n return changesFromOtherInstances$.asObservable().pipe(\n mergeWith(oldChangestream$)\n );\n };\n\n const oldClose = instance.close.bind(instance);\n instance.close = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldClose();\n };\n\n const oldRemove = instance.remove.bind(instance);\n instance.remove = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldRemove();\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAqBA,OAAO,QAAQ,MAAM;AAC1C,SAASC,SAAS,QAAQ,gBAAgB;AAQ1C,SACIC,gBAAgB,QACb,mBAAmB;;AAE1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,0BAOX,GAAG,IAAIC,GAAG,EAAE;AAcd,OAAO,SAASC,4BAA4B,CACxCC,qBAA6B,EAC7BC,YAAoB,EACpBC,SAAc,EACuC;EACrD,IAAIC,KAAK,GAAGN,0BAA0B,CAACO,GAAG,CAACJ,qBAAqB,CAAC;EACjE,IAAI,CAACG,KAAK,EAAE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A;QAEL,OAAOqB,QAAQ,EAAE;MAAC,KAAXA,QAAQ,EAAE;IACrB,CAAC;MAAA;IAAA;EAAA;EAED,IAAMI,SAAS,GAAGzB,QAAQ,CAAC0B,MAAM,CAACJ,IAAI,CAACtB,QAAQ,CAAC;EAChDA,QAAQ,CAAC0B,MAAM;IAAA,IAAqB;MAChCX,MAAM,GAAG,IAAI;MACbC,GAAG,CAACO,WAAW,EAAE;MACjBpB,gBAAgB,CAACqB,mBAAmB,CAAC,SAAS,EAAEnB,aAAa,CAAC;MAAC;QAAA,IAC3D,CAACJ,wBAAwB;UAAA,uBACnBP,+BAA+B,CACjCK,sBAAsB,CAACf,qBAAqB,EAC5CgB,QAAQ,CACX;QAAA;MAAA;MAAA;QAEL,OAAOyB,SAAS,EAAE;MAAC,KAAZA,SAAS,EAAE;IACtB,CAAC;MAAA;IAAA;EAAA;AACL"} \ No newline at end of file +{"version":3,"file":"rx-storage-multiinstance.js","names":["Subject","mergeWith","BroadcastChannel","BROADCAST_CHANNEL_BY_TOKEN","Map","getBroadcastChannelReference","databaseInstanceToken","databaseName","refObject","state","get","bc","refs","Set","set","add","removeBroadcastChannelReference","size","close","addRxStorageMultiInstanceSupport","storageName","instanceCreationParams","instance","providedBroadcastChannel","multiInstance","broadcastChannel","changesFromOtherInstances$","eventListener","msg","collectionName","version","schema","next","eventBulk","addEventListener","oldChangestream$","changeStream","closed","sub","subscribe","postMessage","asObservable","pipe","oldClose","bind","unsubscribe","removeEventListener","oldRemove","remove"],"sources":["../../src/rx-storage-multiinstance.ts"],"sourcesContent":["/**\n * When a persistend RxStorage is used in more the one JavaScript process,\n * the even stream of the changestream() function must be broadcasted to the other\n * RxStorageInstances of the same databaseName+collectionName.\n *\n * In the past this was done by RxDB but it makes more sense to do this\n * at the RxStorage level so that the broadcasting etc can all happen inside of a WebWorker\n * and not on the main thread.\n * Also it makes it less complex to stack up different RxStorages onto each other\n * like what we do with the in-memory plugin.\n *\n * This is intened to be used inside of createStorageInstance() of a storage.\n * Do not use this if the storage anyway broadcasts the events like when using MongoDB\n * or in the future W3C might introduce a way to listen to IndexedDB changes.\n */\n\nimport { Observable, Subject } from 'rxjs';\nimport { mergeWith } from 'rxjs/operators';\nimport type {\n EventBulk,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\n\nimport {\n BroadcastChannel\n} from 'broadcast-channel';\n\n/**\n * The broadcast-channel is reused by the databaseInstanceToken.\n * This is required so that it is easy to simulate multi-tab usage\n * in the test where different instances of the same RxDatabase must\n * have different broadcast channels.\n * But also it ensures that for each RxDatabase we only create a single\n * broadcast channel that can even be reused in the leader election plugin.\n *\n * TODO at the end of the unit tests,\n * we should ensure that all channels are closed and cleaned up.\n * Otherwise we have forgot something.\n */\nexport const BROADCAST_CHANNEL_BY_TOKEN: Map;\n /**\n * Contains all context objects that currently use the channel.\n * If this becomes empty, we can close the channel\n */\n refs: Set;\n}> = new Map();\n\n\nexport type RxStorageMultiInstanceBroadcastType = {\n storageName: string;\n collectionName: string;\n /**\n * collection.schema.version\n */\n version: number;\n databaseName: string;\n eventBulk: EventBulk;\n};\n\nexport function getBroadcastChannelReference(\n databaseInstanceToken: string,\n databaseName: string,\n refObject: any\n): BroadcastChannel {\n let state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n state = {\n /**\n * We have to use the databaseName instead of the databaseInstanceToken\n * in the BroadcastChannel name because different instances must end with the same\n * channel name to be able to broadcast messages between each other.\n */\n bc: new BroadcastChannel('RxDB:' + databaseName),\n refs: new Set()\n };\n BROADCAST_CHANNEL_BY_TOKEN.set(databaseInstanceToken, state);\n }\n state.refs.add(refObject);\n return state.bc;\n}\n\nexport function removeBroadcastChannelReference(\n databaseInstanceToken: string,\n refObject: any\n) {\n const state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n return;\n }\n state.refs.delete(refObject);\n if (state.refs.size === 0) {\n BROADCAST_CHANNEL_BY_TOKEN.delete(databaseInstanceToken);\n return state.bc.close();\n }\n}\n\n\nexport function addRxStorageMultiInstanceSupport(\n storageName: string,\n instanceCreationParams: RxStorageInstanceCreationParams,\n instance: RxStorageInstance,\n /**\n * If provided, that channel will be used\n * instead of an own one.\n */\n providedBroadcastChannel?: BroadcastChannel\n) {\n if (!instanceCreationParams.multiInstance) {\n return;\n }\n\n type Emit = EventBulk, any>;\n\n const broadcastChannel = providedBroadcastChannel ?\n providedBroadcastChannel :\n getBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance.databaseName,\n instance\n );\n\n const changesFromOtherInstances$: Subject = new Subject();\n\n\n const eventListener = (msg: RxStorageMultiInstanceBroadcastType) => {\n if (\n msg.storageName === storageName &&\n msg.databaseName === instanceCreationParams.databaseName &&\n msg.collectionName === instanceCreationParams.collectionName &&\n msg.version === instanceCreationParams.schema.version\n ) {\n changesFromOtherInstances$.next(msg.eventBulk);\n }\n };\n broadcastChannel.addEventListener('message', eventListener);\n\n const oldChangestream$ = instance.changeStream();\n\n let closed = false;\n const sub = oldChangestream$.subscribe(eventBulk => {\n if (closed) {\n return;\n }\n broadcastChannel.postMessage({\n storageName: storageName,\n databaseName: instanceCreationParams.databaseName,\n collectionName: instanceCreationParams.collectionName,\n version: instanceCreationParams.schema.version,\n eventBulk\n });\n });\n\n instance.changeStream = function (): Observable {\n return changesFromOtherInstances$.asObservable().pipe(\n mergeWith(oldChangestream$)\n );\n };\n\n const oldClose = instance.close.bind(instance);\n instance.close = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldClose();\n };\n\n const oldRemove = instance.remove.bind(instance);\n instance.remove = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldRemove();\n };\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAqBA,OAAO,QAAQ,MAAM;AAC1C,SAASC,SAAS,QAAQ,gBAAgB;AAQ1C,SACIC,gBAAgB,QACb,mBAAmB;;AAE1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMC,0BAOX,GAAG,IAAIC,GAAG,EAAE;AAcd,OAAO,SAASC,4BAA4B,CACxCC,qBAA6B,EAC7BC,YAAoB,EACpBC,SAAc,EACuC;EACrD,IAAIC,KAAK,GAAGN,0BAA0B,CAACO,GAAG,CAACJ,qBAAqB,CAAC;EACjE,IAAI,CAACG,KAAK,EAAE;IACRA,KAAK,GAAG;MACJ;AACZ;AACA;AACA;AACA;MACYE,EAAE,EAAE,IAAIT,gBAAgB,CAAC,OAAO,GAAGK,YAAY,CAAC;MAChDK,IAAI,EAAE,IAAIC,GAAG;IACjB,CAAC;IACDV,0BAA0B,CAACW,GAAG,CAACR,qBAAqB,EAAEG,KAAK,CAAC;EAChE;EACAA,KAAK,CAACG,IAAI,CAACG,GAAG,CAACP,SAAS,CAAC;EACzB,OAAOC,KAAK,CAACE,EAAE;AACnB;AAEA,OAAO,SAASK,+BAA+B,CAC3CV,qBAA6B,EAC7BE,SAAc,EAChB;EACE,IAAMC,KAAK,GAAGN,0BAA0B,CAACO,GAAG,CAACJ,qBAAqB,CAAC;EACnE,IAAI,CAACG,KAAK,EAAE;IACR;EACJ;EACAA,KAAK,CAACG,IAAI,UAAO,CAACJ,SAAS,CAAC;EAC5B,IAAIC,KAAK,CAACG,IAAI,CAACK,IAAI,KAAK,CAAC,EAAE;IACvBd,0BAA0B,UAAO,CAACG,qBAAqB,CAAC;IACxD,OAAOG,KAAK,CAACE,EAAE,CAACO,KAAK,EAAE;EAC3B;AACJ;AAGA,OAAO,SAASC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,QAAQ,CAACc,YAAY,GAAG,YAA8B;IAClD,OAAOV,0BAA0B,CAACe,YAAY,EAAE,CAACC,IAAI,CACjDzC,SAAS,CAACkC,gBAAgB,CAAC,CAC9B;EACL,CAAC;EAED,IAAMQ,QAAQ,GAAGrB,QAAQ,CAACJ,KAAK,CAAC0B,IAAI,CAACtB,QAAQ,CAAC;EAC9CA,QAAQ,CAACJ,KAAK,yEAAG;IAAA;MAAA;QAAA;UACbmB,MAAM,GAAG,IAAI;UACbC,GAAG,CAACO,WAAW,EAAE;UACjBpB,gBAAgB,CAACqB,mBAAmB,CAAC,SAAS,EAAEnB,aAAa,CAAC;UAAC,IAC1DJ,wBAAwB;YAAA;YAAA;UAAA;UAAA;UAAA,OACnBP,+BAA+B,CACjCK,sBAAsB,CAACf,qBAAqB,EAC5CgB,QAAQ,CACX;QAAA;UAAA,iCAEEqB,QAAQ,EAAE;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACpB;EAED,IAAMI,SAAS,GAAGzB,QAAQ,CAAC0B,MAAM,CAACJ,IAAI,CAACtB,QAAQ,CAAC;EAChDA,QAAQ,CAAC0B,MAAM,yEAAG;IAAA;MAAA;QAAA;UACdX,MAAM,GAAG,IAAI;UACbC,GAAG,CAACO,WAAW,EAAE;UACjBpB,gBAAgB,CAACqB,mBAAmB,CAAC,SAAS,EAAEnB,aAAa,CAAC;UAAC,IAC1DJ,wBAAwB;YAAA;YAAA;UAAA;UAAA;UAAA,OACnBP,+BAA+B,CACjCK,sBAAsB,CAACf,qBAAqB,EAC5CgB,QAAQ,CACX;QAAA;UAAA,kCAEEyB,SAAS,EAAE;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACrB;AACL"} \ No newline at end of file diff --git a/dist/es/types/index.d.js b/dist/es/types/index.d.js index dbd001c595c..171c581fa4b 100644 --- a/dist/es/types/index.d.js +++ b/dist/es/types/index.d.js @@ -19,10 +19,8 @@ export * from './util'; // plugins export * from './plugins/replication'; export * from './plugins/replication-graphql'; -export * from './plugins/replication-couchdb'; export * from './plugins/replication'; export * from './plugins/local-documents'; -export * from './plugins/server-couchdb'; export * from './plugins/migration'; export * from './plugins/backup'; export * from './plugins/cleanup'; diff --git a/dist/es/types/index.d.js.map b/dist/es/types/index.d.js.map index 9fd98f836cf..de831d8466d 100644 --- a/dist/es/types/index.d.js.map +++ b/dist/es/types/index.d.js.map @@ -1 +1 @@ -{"version":3,"file":"index.d.js","names":[],"sources":["../../../src/types/index.d.ts"],"sourcesContent":["export * from './pouch';\nexport * from './rx-attachment';\nexport * from './rx-collection';\nexport * from './rx-database';\nexport * from './rx-database-internal-store';\nexport * from './rx-document';\nexport * from './rx-error';\nexport * from './rx-plugin';\nexport * from './rx-query';\nexport * from './rx-schema';\nexport * from './rx-storage';\nexport * from './rx-storage.interface';\nexport * from './replication-protocol';\nexport * from './conflict-handling';\nexport * from './rx-change-event';\nexport * from './query-planner';\nexport * from './util';\n\n// plugins\nexport * from './plugins/replication';\nexport * from './plugins/replication-graphql';\nexport * from './plugins/replication-couchdb';\nexport * from './plugins/replication';\nexport * from './plugins/local-documents';\nexport * from './plugins/server-couchdb';\nexport * from './plugins/migration';\nexport * from './plugins/backup';\nexport * from './plugins/cleanup';\nexport * from './plugins/lokijs';\nexport * from './plugins/dexie';\nexport * from './plugins/update';\nexport * from './plugins/crdt';\n"],"mappings":"AAAA,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,iBAAiB;AAC/B,cAAc,eAAe;AAC7B,cAAc,8BAA8B;AAC5C,cAAc,eAAe;AAC7B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,cAAc;AAC5B,cAAc,wBAAwB;AACtC,cAAc,wBAAwB;AACtC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,iBAAiB;AAC/B,cAAc,QAAQ;;AAEtB;AACA,cAAc,uBAAuB;AACrC,cAAc,+BAA+B;AAC7C,cAAc,+BAA+B;AAC7C,cAAc,uBAAuB;AACrC,cAAc,2BAA2B;AACzC,cAAc,0BAA0B;AACxC,cAAc,qBAAqB;AACnC,cAAc,kBAAkB;AAChC,cAAc,mBAAmB;AACjC,cAAc,kBAAkB;AAChC,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAChC,cAAc,gBAAgB"} \ No newline at end of file +{"version":3,"file":"index.d.js","names":[],"sources":["../../../src/types/index.d.ts"],"sourcesContent":["export * from './pouch';\nexport * from './rx-attachment';\nexport * from './rx-collection';\nexport * from './rx-database';\nexport * from './rx-database-internal-store';\nexport * from './rx-document';\nexport * from './rx-error';\nexport * from './rx-plugin';\nexport * from './rx-query';\nexport * from './rx-schema';\nexport * from './rx-storage';\nexport * from './rx-storage.interface';\nexport * from './replication-protocol';\nexport * from './conflict-handling';\nexport * from './rx-change-event';\nexport * from './query-planner';\nexport * from './util';\n\n// plugins\nexport * from './plugins/replication';\nexport * from './plugins/replication-graphql';\nexport * from './plugins/replication';\nexport * from './plugins/local-documents';\nexport * from './plugins/migration';\nexport * from './plugins/backup';\nexport * from './plugins/cleanup';\nexport * from './plugins/lokijs';\nexport * from './plugins/dexie';\nexport * from './plugins/update';\nexport * from './plugins/crdt';\n"],"mappings":"AAAA,cAAc,SAAS;AACvB,cAAc,iBAAiB;AAC/B,cAAc,iBAAiB;AAC/B,cAAc,eAAe;AAC7B,cAAc,8BAA8B;AAC5C,cAAc,eAAe;AAC7B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,YAAY;AAC1B,cAAc,aAAa;AAC3B,cAAc,cAAc;AAC5B,cAAc,wBAAwB;AACtC,cAAc,wBAAwB;AACtC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,iBAAiB;AAC/B,cAAc,QAAQ;;AAEtB;AACA,cAAc,uBAAuB;AACrC,cAAc,+BAA+B;AAC7C,cAAc,uBAAuB;AACrC,cAAc,2BAA2B;AACzC,cAAc,qBAAqB;AACnC,cAAc,kBAAkB;AAChC,cAAc,mBAAmB;AACjC,cAAc,kBAAkB;AAChC,cAAc,iBAAiB;AAC/B,cAAc,kBAAkB;AAChC,cAAc,gBAAgB"} \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-adapter-http.d.js b/dist/es/types/modules/pouchdb-adapter-http.d.js deleted file mode 100644 index 04ce6b880d0..00000000000 --- a/dist/es/types/modules/pouchdb-adapter-http.d.js +++ /dev/null @@ -1,2 +0,0 @@ - -//# sourceMappingURL=pouchdb-adapter-http.d.js.map \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-adapter-http.d.js.map b/dist/es/types/modules/pouchdb-adapter-http.d.js.map deleted file mode 100644 index 66e5e9cf6c7..00000000000 --- a/dist/es/types/modules/pouchdb-adapter-http.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-adapter-http.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-adapter-http.d.ts"],"sourcesContent":["declare module 'pouchdb-adapter-http';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-md5.d.js b/dist/es/types/modules/pouchdb-md5.d.js deleted file mode 100644 index bad70ac304c..00000000000 --- a/dist/es/types/modules/pouchdb-md5.d.js +++ /dev/null @@ -1,2 +0,0 @@ - -//# sourceMappingURL=pouchdb-md5.d.js.map \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-md5.d.js.map b/dist/es/types/modules/pouchdb-md5.d.js.map deleted file mode 100644 index eb521ef8067..00000000000 --- a/dist/es/types/modules/pouchdb-md5.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-md5.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-md5.d.ts"],"sourcesContent":["declare module 'pouchdb-md5';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-replication.d.js b/dist/es/types/modules/pouchdb-replication.d.js deleted file mode 100644 index 78029b4b93d..00000000000 --- a/dist/es/types/modules/pouchdb-replication.d.js +++ /dev/null @@ -1,2 +0,0 @@ - -//# sourceMappingURL=pouchdb-replication.d.js.map \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-replication.d.js.map b/dist/es/types/modules/pouchdb-replication.d.js.map deleted file mode 100644 index be040bb64ca..00000000000 --- a/dist/es/types/modules/pouchdb-replication.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-replication.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-replication.d.ts"],"sourcesContent":["declare module 'pouchdb-replication';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-utils.d.js b/dist/es/types/modules/pouchdb-utils.d.js deleted file mode 100644 index 71cb8e30c5b..00000000000 --- a/dist/es/types/modules/pouchdb-utils.d.js +++ /dev/null @@ -1,2 +0,0 @@ - -//# sourceMappingURL=pouchdb-utils.d.js.map \ No newline at end of file diff --git a/dist/es/types/modules/pouchdb-utils.d.js.map b/dist/es/types/modules/pouchdb-utils.d.js.map deleted file mode 100644 index e4c0540f1b4..00000000000 --- a/dist/es/types/modules/pouchdb-utils.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-utils.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-utils.d.ts"],"sourcesContent":["declare module 'pouchdb-utils';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/plugins/local-documents.d.js.map b/dist/es/types/plugins/local-documents.d.js.map index c717687767f..16165794bcf 100644 --- a/dist/es/types/plugins/local-documents.d.js.map +++ b/dist/es/types/plugins/local-documents.d.js.map @@ -1 +1 @@ -{"version":3,"file":"local-documents.d.js","names":[],"sources":["../../../../src/types/plugins/local-documents.d.ts"],"sourcesContent":["import { DocCache } from '../../doc-cache';\nimport { RxCollection } from '../rx-collection';\nimport { RxDatabase } from '../rx-database';\nimport { RxDocumentBase } from '../rx-document';\nimport { RxStorageInstance } from '../rx-storage.interface';\nimport { Override } from '../util';\n\nexport type LocalDocumentParent = RxDatabase | RxCollection;\nexport type LocalDocumentState = {\n database: RxDatabase;\n parent: LocalDocumentParent;\n storageInstance: RxStorageInstance;\n docCache: DocCache>;\n};\nexport type RxLocalDocumentData<\n Data = {\n // local documents are schemaless and contain any data\n [key: string]: any;\n }\n> = {\n id: string;\n data: Data;\n};\n\ndeclare type LocalDocumentAtomicUpdateFunction = (\n doc: Data,\n rxLocalDocument: RxLocalDocument\n) => Data | Promise;\n\n\nexport declare type RxLocalDocument = Override<\nRxDocumentBase, {}>,\n{\n readonly parent: Parent;\n isLocal(): true;\n\n /**\n * Because local documents store their relevant data inside of the 'data' property,\n * the atomic mutation methods are changed a bit to only allow to change parts of the data property.\n */\n atomicUpdate(mutationFunction: LocalDocumentAtomicUpdateFunction): Promise>;\n atomicPatch(patch: Partial): Promise>;\n}\n>;\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"local-documents.d.js","names":[],"sources":["../../../../src/types/plugins/local-documents.d.ts"],"sourcesContent":["import { DocumentCache } from '../../doc-cache';\nimport { IncrementalWriteQueue } from '../../incremental-write';\nimport { RxCollection } from '../rx-collection';\nimport { RxDatabase } from '../rx-database';\nimport { RxDocumentBase } from '../rx-document';\nimport { RxStorageInstance } from '../rx-storage.interface';\nimport { Override } from '../util';\n\nexport type LocalDocumentParent = RxDatabase | RxCollection;\nexport type LocalDocumentState = {\n database: RxDatabase;\n parent: LocalDocumentParent;\n storageInstance: RxStorageInstance;\n docCache: DocumentCache;\n incrementalWriteQueue: IncrementalWriteQueue;\n};\nexport type RxLocalDocumentData<\n Data = {\n // local documents are schemaless and contain any data\n [key: string]: any;\n }\n> = {\n id: string;\n data: Data;\n};\n\ndeclare type LocalDocumentModifyFunction = (\n doc: Data,\n rxLocalDocument: RxLocalDocument\n) => Data | Promise;\n\n\nexport declare type RxLocalDocument = Override<\nRxDocumentBase, {}>,\n{\n readonly parent: Parent;\n isLocal(): true;\n\n /**\n * Because local documents store their relevant data inside of the 'data' property,\n * the incremental mutation methods are changed a bit to only allow to change parts of the data property.\n */\n incrementalModify(mutationFunction: LocalDocumentModifyFunction): Promise>;\n incrementalPatch(patch: Partial): Promise>;\n}\n>;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/plugins/lokijs.d.js.map b/dist/es/types/plugins/lokijs.d.js.map index 39ec25a9d6c..d9ccfd4eb93 100644 --- a/dist/es/types/plugins/lokijs.d.js.map +++ b/dist/es/types/plugins/lokijs.d.js.map @@ -1 +1 @@ -{"version":3,"file":"lokijs.d.js","names":[],"sources":["../../../../src/types/plugins/lokijs.d.ts"],"sourcesContent":["import type { LeaderElector } from 'broadcast-channel';\nimport type {\n Collection\n} from 'lokijs';\nimport { AddReturn } from 'unload';\nimport { LokiSaveQueue } from '../../plugins/lokijs/loki-save-queue';\n\nexport type LokiDatabaseSettings = Partial & {};\n\nexport type LokiCollectionSettings = Partial>;\n\nexport type LokiSettings = {\n database?: LokiDatabaseSettings;\n collection?: LokiCollectionSettings;\n};\n\nexport type LokiStorageInternals = {\n leaderElector?: LeaderElector;\n localState?: Promise;\n};\n\nexport type LokiRemoteRequestBroadcastMessage = {\n response: false;\n type: string;\n databaseName: string;\n collectionName: string;\n operation: string;\n params: any[];\n requestId: string;\n};\n\nexport type LokiRemoteResponseBroadcastMessage = {\n response: true;\n type: string;\n databaseName: string;\n collectionName: string;\n requestId: string;\n result: any | any[];\n // if true, the result property will contain an error state\n isError: boolean;\n};\n\nexport type LokiDatabaseState = {\n database: Loki;\n databaseSettings: LokiDatabaseSettings;\n saveQueue: LokiSaveQueue;\n\n // all known collections of the database\n collections: {\n [collectionName: string]: Collection;\n };\n\n /**\n * Registered unload handlers\n * so we can remove them on close.\n */\n unloads: AddReturn[];\n};\n\nexport type LokiLocalDatabaseState = {\n databaseState: LokiDatabaseState;\n collection: Collection;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"lokijs.d.js","names":[],"sources":["../../../../src/types/plugins/lokijs.d.ts"],"sourcesContent":["import type { LeaderElector } from 'broadcast-channel';\nimport type {\n Collection\n} from 'lokijs';\nimport { AddReturn } from 'unload';\nimport { LokiSaveQueue } from '../../plugins/storage-lokijs/loki-save-queue';\n\nexport type LokiDatabaseSettings = Partial & {};\n\nexport type LokiCollectionSettings = Partial>;\n\nexport type LokiSettings = {\n database?: LokiDatabaseSettings;\n collection?: LokiCollectionSettings;\n};\n\nexport type LokiStorageInternals = {\n leaderElector?: LeaderElector;\n localState?: Promise;\n};\n\nexport type LokiRemoteRequestBroadcastMessage = {\n response: false;\n type: string;\n databaseName: string;\n collectionName: string;\n operation: string;\n params: any[];\n requestId: string;\n};\n\nexport type LokiRemoteResponseBroadcastMessage = {\n response: true;\n type: string;\n databaseName: string;\n collectionName: string;\n requestId: string;\n result: any | any[];\n // if true, the result property will contain an error state\n isError: boolean;\n};\n\nexport type LokiDatabaseState = {\n database: Loki;\n databaseSettings: LokiDatabaseSettings;\n saveQueue: LokiSaveQueue;\n\n // all known collections of the database\n collections: {\n [collectionName: string]: Collection;\n };\n\n /**\n * Registered unload handlers\n * so we can remove them on close.\n */\n unloads: AddReturn[];\n};\n\nexport type LokiLocalDatabaseState = {\n databaseState: LokiDatabaseState;\n collection: Collection;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/plugins/replication-couchdb.d.js b/dist/es/types/plugins/replication-couchdb.d.js deleted file mode 100644 index ff57caa6a9c..00000000000 --- a/dist/es/types/plugins/replication-couchdb.d.js +++ /dev/null @@ -1,3 +0,0 @@ -export {}; -export {}; -//# sourceMappingURL=replication-couchdb.d.js.map \ No newline at end of file diff --git a/dist/es/types/plugins/replication-couchdb.d.js.map b/dist/es/types/plugins/replication-couchdb.d.js.map deleted file mode 100644 index 7f972d71fbc..00000000000 --- a/dist/es/types/plugins/replication-couchdb.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"replication-couchdb.d.js","names":[],"sources":["../../../../src/types/plugins/replication-couchdb.d.ts"],"sourcesContent":["import { Observable } from 'rxjs';\n\nimport type {\n RxQuery,\n RxCollection\n} from '../../types';\nimport type {\n PouchReplicationOptions,\n PouchSyncHandler\n} from '../pouch';\nimport type { RxCouchDBReplicationStateBase } from '../../plugins/replication-couchdb';\n\nexport declare class RxCouchDBReplicationState extends RxCouchDBReplicationStateBase {\n collection: RxCollection;\n\n change$: Observable;\n docs$: Observable;\n denied$: Observable;\n active$: Observable;\n alive$: Observable;\n complete$: Observable;\n error$: Observable;\n\n /**\n * waits until the initial replication is done\n * and the client can be expected to have the same data as the server\n */\n awaitInitialReplication(): Promise;\n\n // can be used for debugging or custom event-handling\n // will be set some time after sync() is called\n _pouchEventEmitterObject: PouchSyncHandler | null;\n\n // if you do a custom sync, put the thing you get back from pouch here\n setPouchEventEmitter(pouchSyncState: any): void;\n}\n\nexport type SyncOptions = {\n remote: string | any;\n waitForLeadership?: boolean;\n direction?: {\n push?: boolean;\n pull?: boolean;\n };\n // for options see https://pouchdb.com/api.html#replication\n options?: PouchReplicationOptions;\n query?: RxQuery;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/plugins/replication-graphql.d.js.map b/dist/es/types/plugins/replication-graphql.d.js.map index 90ea25e5091..7fbea9e715b 100644 --- a/dist/es/types/plugins/replication-graphql.d.js.map +++ b/dist/es/types/plugins/replication-graphql.d.js.map @@ -1 +1 @@ -{"version":3,"file":"replication-graphql.d.js","names":[],"sources":["../../../../src/types/plugins/replication-graphql.d.ts"],"sourcesContent":["import { RxReplicationWriteToMasterRow } from '../replication-protocol';\nimport { ById, MaybePromise } from '../util';\nimport { ReplicationOptions, ReplicationPullHandlerResult, ReplicationPullOptions, ReplicationPushOptions } from './replication';\n\nexport interface RxGraphQLReplicationQueryBuilderResponseObject {\n query: string;\n variables: any;\n}\n\nexport type RxGraphQLReplicationClientState = {\n headers: ById;\n credentials: RequestCredentials | undefined;\n};\n\nexport type RxGraphQLReplicationQueryBuilderResponse =\n RxGraphQLReplicationQueryBuilderResponseObject |\n Promise;\nexport type RxGraphQLReplicationPushQueryBuilder = (\n // typed 'any' because the data might be modified by the push.modifier.\n rows: RxReplicationWriteToMasterRow[]\n) => RxGraphQLReplicationQueryBuilderResponse;\n\n\nexport type RxGraphQLReplicationPullQueryBuilder = (\n latestPulledCheckpoint: CheckpointType | null,\n limit: number\n) => RxGraphQLReplicationQueryBuilderResponse;\nexport type GraphQLSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {\n queryBuilder: RxGraphQLReplicationPullQueryBuilder;\n streamQueryBuilder?: RxGraphQLReplicationPullStreamQueryBuilder;\n dataPath?: string;\n responseModifier?: RxGraphQLPullResponseModifier;\n};\n\nexport type RxGraphQLPullResponseModifier = (\n // the exact response that was returned from the server\n plainResponse: ReplicationPullHandlerResult | any,\n // either 'handler' if it came from the pull.handler, or 'stream' if it came from the pull.stream\n origin: 'handler' | 'stream',\n requestCheckpoint?: CheckpointType\n) => MaybePromise>;\n\nexport type RxGraphQLReplicationPullStreamQueryBuilder = (headers: { [k: string]: string; }) => RxGraphQLReplicationQueryBuilderResponse;\n\nexport type GraphQLSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {\n queryBuilder: RxGraphQLReplicationPushQueryBuilder;\n};\n\nexport type GraphQLServerUrl = {\n http?: string;\n ws?: string;\n};\n\nexport type SyncOptionsGraphQL = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier' | 'collection'\n> & {\n url: GraphQLServerUrl;\n headers?: { [k: string]: string; }; // send with all requests to the endpoint\n credentials?: RequestCredentials;\n pull?: GraphQLSyncPullOptions;\n push?: GraphQLSyncPushOptions;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"replication-graphql.d.js","names":[],"sources":["../../../../src/types/plugins/replication-graphql.d.ts"],"sourcesContent":["import { RxReplicationWriteToMasterRow } from '../replication-protocol';\nimport { ById, MaybePromise } from '../util';\nimport { ReplicationOptions, ReplicationPullHandlerResult, ReplicationPullOptions, ReplicationPushOptions } from './replication';\n\nexport interface RxGraphQLReplicationQueryBuilderResponseObject {\n query: string;\n variables: any;\n}\n\nexport type RxGraphQLReplicationClientState = {\n headers: ById;\n credentials: RequestCredentials | undefined;\n};\n\nexport type RxGraphQLReplicationQueryBuilderResponse =\n RxGraphQLReplicationQueryBuilderResponseObject |\n Promise;\nexport type RxGraphQLReplicationPushQueryBuilder = (\n // typed 'any' because the data might be modified by the push.modifier.\n rows: RxReplicationWriteToMasterRow[]\n) => RxGraphQLReplicationQueryBuilderResponse;\n\n\nexport type RxGraphQLReplicationPullQueryBuilder = (\n latestPulledCheckpoint: CheckpointType | null,\n limit: number\n) => RxGraphQLReplicationQueryBuilderResponse;\nexport type GraphQLSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {\n queryBuilder: RxGraphQLReplicationPullQueryBuilder;\n streamQueryBuilder?: RxGraphQLReplicationPullStreamQueryBuilder;\n dataPath?: string;\n responseModifier?: RxGraphQLPullResponseModifier;\n};\n\nexport type RxGraphQLPullResponseModifier = (\n // the exact response that was returned from the server\n plainResponse: ReplicationPullHandlerResult | any,\n // either 'handler' if it came from the pull.handler, or 'stream' if it came from the pull.stream\n origin: 'handler' | 'stream',\n requestCheckpoint?: CheckpointType\n) => MaybePromise>;\n\nexport type RxGraphQLReplicationPullStreamQueryBuilder = (headers: { [k: string]: string; }) => RxGraphQLReplicationQueryBuilderResponse;\n\nexport type GraphQLSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {\n queryBuilder: RxGraphQLReplicationPushQueryBuilder;\n};\n\nexport type GraphQLServerUrl = {\n http?: string;\n ws?: string;\n};\n\nexport type SyncOptionsGraphQL = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier'\n> & {\n url: GraphQLServerUrl;\n headers?: { [k: string]: string; }; // send with all requests to the endpoint\n credentials?: RequestCredentials;\n pull?: GraphQLSyncPullOptions;\n push?: GraphQLSyncPushOptions;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/plugins/replication.d.js.map b/dist/es/types/plugins/replication.d.js.map index 5c8a7c1cfd8..fbf934d9c8c 100644 --- a/dist/es/types/plugins/replication.d.js.map +++ b/dist/es/types/plugins/replication.d.js.map @@ -1 +1 @@ -{"version":3,"file":"replication.d.js","names":[],"sources":["../../../../src/types/plugins/replication.d.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport type {\n InternalStoreDocType,\n MaybePromise,\n RxCollection,\n RxDocumentData,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n WithDeleted\n} from '../../types';\n\n\nexport type InternalStoreReplicationPushDocType = InternalStoreDocType<{\n checkpoint: any;\n}>;\nexport type InternalStoreReplicationPullDocType = InternalStoreDocType<{\n lastPulledDoc: RxDocumentData;\n}>;\n\nexport type ReplicationPullHandlerResult = {\n checkpoint: CheckpointType;\n documents: WithDeleted[];\n};\n\nexport type ReplicationPullHandler = (\n lastPulledCheckpoint: CheckpointType,\n batchSize: number\n) => Promise>;\nexport type ReplicationPullOptions = {\n /**\n * A handler that pulls the new remote changes\n * from the remote actor.\n */\n handler: ReplicationPullHandler;\n\n\n /**\n * An observable that streams all document changes\n * that are happening on the backend.\n * Emits an document bulk together with the latest checkpoint of these documents.\n * Also can emit a 'RESYNC' event when the client was offline and is online again.\n *\n * Not required for non-live replication.\n */\n stream$?: Observable>;\n\n /**\n * Amount of documents that the remote will send in one request.\n * If the response contains less then [batchSize] documents,\n * RxDB will assume there are no more changes on the backend\n * that are not replicated.\n * [default=100]\n */\n batchSize?: number;\n\n /**\n * A modifier that runs on all documents that are pulled,\n * before they are used by RxDB.\n * - the ones from the pull handler\n * - the ones from the pull stream\n */\n modifier?: (docData: any) => MaybePromise>;\n};\n\n/**\n * Gets the new write rows.\n * Returns the current master state of all conflicting writes,\n * so that they can be resolved on the client.\n */\nexport type ReplicationPushHandler = (docs: RxReplicationWriteToMasterRow[]) => Promise[]>;\nexport type ReplicationPushOptions = {\n /**\n * A handler that sends the new local changes\n * to the remote actor.\n * On error, all documents are send again at later time.\n */\n handler: ReplicationPushHandler;\n\n\n /**\n * A modifier that runs on all pushed documents before\n * they are send into the push handler.\n */\n modifier?: (docData: WithDeleted) => MaybePromise;\n\n /**\n * How many local changes to process at once.\n */\n batchSize?: number;\n};\n\n\nexport type ReplicationOptions = {\n /**\n * An id for the replication to identify it\n * and so that RxDB is able to resume the replication on app reload.\n * If you replicate with a remote server, it is recommended to put the\n * server url into the replicationIdentifier.\n * Like 'my-rest-replication-to-https://example.com/api/sync'\n */\n replicationIdentifier: string;\n collection: RxCollection;\n /**\n * Define a custom property that is used\n * to flag a document as being deleted.\n * @default '_deleted'\n */\n deletedField?: '_deleted' | string;\n pull?: ReplicationPullOptions;\n push?: ReplicationPushOptions;\n /**\n * By default it will do an ongoing realtime replication.\n * By settings live: false the replication will run once until the local state\n * is in sync with the remote state, then it will cancel itself.\n * @default true\n */\n live?: boolean;\n /**\n * Time in milliseconds after when a failed backend request\n * has to be retried.\n * This time will be skipped if a offline->online switch is detected\n * via `navigator.onLine`\n * @default 5000\n */\n retryTime?: number;\n /**\n * When multiInstance is `true`, like when you use RxDB in multiple browser tabs,\n * the replication should always run in only one of the open browser tabs.\n * If waitForLeadership is `true`, it will wait until the current instance is leader.\n * If waitForLeadership is `false`, it will start replicating, even if it is not leader.\n * @default true\n */\n waitForLeadership?: boolean;\n /**\n * If this is set to `false`,\n * the replication will not start automatically\n * but will wait for `replicationState.start()` being called.\n * @default true\n */\n autoStart?: boolean;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"replication.d.js","names":[],"sources":["../../../../src/types/plugins/replication.d.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport type {\n InternalStoreDocType,\n MaybePromise,\n RxCollection,\n RxDocumentData,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n WithDeleted\n} from '../../types';\n\n\nexport type InternalStoreReplicationPushDocType = InternalStoreDocType<{\n checkpoint: any;\n}>;\nexport type InternalStoreReplicationPullDocType = InternalStoreDocType<{\n lastPulledDoc: RxDocumentData;\n}>;\n\nexport type ReplicationPullHandlerResult = {\n checkpoint: CheckpointType;\n documents: WithDeleted[];\n};\n\nexport type ReplicationPullHandler = (\n lastPulledCheckpoint: CheckpointType,\n batchSize: number\n) => Promise>;\nexport type ReplicationPullOptions = {\n /**\n * A handler that pulls the new remote changes\n * from the remote actor.\n */\n handler: ReplicationPullHandler;\n\n\n /**\n * An observable that streams all document changes\n * that are happening on the backend.\n * Emits an document bulk together with the latest checkpoint of these documents.\n * Also can emit a 'RESYNC' event when the client was offline and is online again.\n *\n * Not required for non-live replication.\n */\n stream$?: Observable>;\n\n /**\n * Amount of documents that the remote will send in one request.\n * If the response contains less then [batchSize] documents,\n * RxDB will assume there are no more changes on the backend\n * that are not replicated.\n * [default=100]\n */\n batchSize?: number;\n\n /**\n * A modifier that runs on all documents that are pulled,\n * before they are used by RxDB.\n * - the ones from the pull handler\n * - the ones from the pull stream\n */\n modifier?: (docData: any) => MaybePromise>;\n};\n\n/**\n * Gets the new write rows.\n * Returns the current master state of all conflicting writes,\n * so that they can be resolved on the client.\n */\nexport type ReplicationPushHandler = (docs: RxReplicationWriteToMasterRow[]) => Promise[]>;\nexport type ReplicationPushOptions = {\n /**\n * A handler that sends the new local changes\n * to the remote actor.\n * On error, all documents are send again at later time.\n */\n handler: ReplicationPushHandler;\n\n\n /**\n * A modifier that runs on all pushed documents before\n * they are send into the push handler.\n */\n modifier?: (docData: WithDeleted) => MaybePromise;\n\n /**\n * How many local changes to process at once.\n */\n batchSize?: number;\n};\n\n\nexport type ReplicationOptions = {\n /**\n * An id for the replication to identify it\n * and so that RxDB is able to resume the replication on app reload.\n * If you replicate with a remote server, it is recommended to put the\n * server url into the replicationIdentifier.\n * Like 'my-rest-replication-to-https://example.com/api/sync'\n */\n replicationIdentifier: string;\n collection: RxCollection;\n /**\n * Define a custom property that is used\n * to flag a document as being deleted.\n * @default '_deleted'\n */\n deletedField?: '_deleted' | string;\n pull?: ReplicationPullOptions;\n push?: ReplicationPushOptions;\n /**\n * By default it will do an ongoing realtime replication.\n * By settings live: false the replication will run once until the local state\n * is in sync with the remote state, then it will cancel itself.\n * @default true\n */\n live?: boolean;\n /**\n * Time in milliseconds after when a failed backend request\n * has to be retried.\n * This time will be skipped if a offline->online switch is detected\n * via `navigator.onLine`\n * @default 5000\n */\n retryTime?: number;\n /**\n * When multiInstance is `true`, like when you use RxDB in multiple browser tabs,\n * the replication should always run in only one of the open browser tabs.\n * If waitForLeadership is `true`, it will wait until the current instance is leader.\n * If waitForLeadership is `false`, it will start replicating, even if it is not leader.\n * @default true\n */\n waitForLeadership?: boolean;\n /**\n * If this is set to `false`,\n * the replication will not start automatically\n * but will wait for `replicationState.start()` being called.\n * @default true\n */\n autoStart?: boolean;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/plugins/server-couchdb.d.js b/dist/es/types/plugins/server-couchdb.d.js deleted file mode 100644 index d91e43bdedb..00000000000 --- a/dist/es/types/plugins/server-couchdb.d.js +++ /dev/null @@ -1,3 +0,0 @@ -export {}; -export {}; -//# sourceMappingURL=server-couchdb.d.js.map \ No newline at end of file diff --git a/dist/es/types/plugins/server-couchdb.d.js.map b/dist/es/types/plugins/server-couchdb.d.js.map deleted file mode 100644 index 9d9557ec15e..00000000000 --- a/dist/es/types/plugins/server-couchdb.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"server-couchdb.d.js","names":[],"sources":["../../../../src/types/plugins/server-couchdb.d.ts"],"sourcesContent":["export type CouchDBServerResponse = {\n app: any;\n pouchApp: any;\n server: any;\n};\n\n\n/**\n * Options that can be passed to express-pouchdb\n * @link https://github.com/pouchdb/pouchdb-server#api\n */\nexport type PouchDBExpressServerOptions = {\n // a path to the configuration file to use. Defaults to './config.json'.\n configPath?: string;\n // a path to the log file to use. Defaults to './rxdb-server-log.txt' in the tmp folder of the os.\n logPath?: string;\n // If true (=default) the config file is not written to configPath but stored in memory.\n inMemoryConfig?: boolean;\n // determines which parts of the HTTP API express-pouchdb offers are enabled\n mode?: 'fullCouchDB' | 'minimumForPouchDB' | 'custom';\n // Sometimes the preprogrammed modes are insufficient for your needs\n overrideMode?: {\n // a javascript array that specifies parts to include on top of the ones specified by opts.mode\n include?: any[];\n // a javascript array that specifies parts to exclude from the ones specified by opts.mode\n exclude?: any[];\n };\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/pouch.d.js.map b/dist/es/types/pouch.d.js.map index ebf22577264..9c468aebd77 100644 --- a/dist/es/types/pouch.d.js.map +++ b/dist/es/types/pouch.d.js.map @@ -1 +1 @@ -{"version":3,"file":"pouch.d.js","names":[],"sources":["../../../src/types/pouch.d.ts"],"sourcesContent":["import { MangoQuery, MangoQuerySelector, MangoQuerySortPart } from './rx-query';\nimport { BulkWriteRow } from './rx-storage';\n\n/**\n * this file contains types that are pouchdb-specific\n * most of it is copied from @types/pouchdb\n * because it is outdated and strange\n */\n\nexport interface PouchReplicationOptions {\n live?: boolean;\n retry?: boolean;\n filter?: Function;\n doc_ids?: string[];\n query_params?: any;\n view?: any;\n since?: number | 'now';\n heartbeat?: number;\n timeout?: number;\n batch_size?: number;\n batches_limit?: number;\n back_off_function?: Function;\n checkpoint?: false | 'source' | 'target';\n include_docs?: boolean;\n limit?: number;\n}\n\n/**\n * @link https://pouchdb.com/api.html#changes\n */\nexport interface PouchChangesOptionsBase {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n descending?: boolean;\n since?: any;\n limit?: number;\n timeout?: any;\n heartbeat?: number | boolean;\n filter?: any;\n doc_ids?: string | string[];\n query_param?: any;\n view?: any;\n return_docs?: boolean;\n batch_size?: number;\n style?: string;\n}\n\nexport interface PouchChangesOptionsLive extends PouchChangesOptionsBase {\n live: true;\n}\n\nexport interface PouchChangesOptionsNonLive extends PouchChangesOptionsBase {\n live: false;\n}\ninterface PouchChangesOnChangeEvent {\n on: (eventName: string, handler: Function) => void;\n off: (eventName: string, handler: Function) => void;\n cancel(): void;\n}\n\nexport type PouchWriteError = {\n /**\n * status code from pouchdb\n * 409 for 'conflict'\n */\n status: number;\n error: true;\n /**\n * primary key value of the errored document\n */\n id: string;\n};\n\n/**\n * possible pouch-settings\n * @link https://pouchdb.com/api.html#create_database\n */\nexport interface PouchSettings {\n auto_compaction?: boolean;\n revs_limit?: number;\n ajax?: any;\n fetch?: any;\n auth?: any;\n skip_setup?: boolean;\n storage?: any;\n size?: number;\n location?: string;\n iosDatabaseLocation?: string;\n}\n\n/**\n * options for pouch.allDocs()\n * @link https://pouchdb.com/api.html#batch_fetch\n */\nexport type PouchAllDocsOptions = {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n startkey?: string;\n endkey?: string;\n inclusive_end?: boolean;\n limit?: number;\n skip?: number;\n descending?: boolean;\n key?: string;\n keys?: string[];\n update_seq?: string;\n\n // undocument but needed\n revs?: boolean;\n deleted?: 'ok';\n};\n\nexport type PouchSyncHandlerEvents = 'change' | 'paused' | 'active' | 'error' | 'complete';\nexport type PouchSyncHandler = {\n on(ev: PouchSyncHandlerEvents, fn: (el: any) => void): void;\n off(ev: PouchSyncHandlerEvents, fn: any): void;\n cancel(): void;\n};\n\nexport type PouchChangeRow = {\n id: string;\n seq: number;\n deleted?: true;\n changes: {\n rev: 'string';\n }[];\n /**\n * only if include_docs === true\n */\n doc?: PouchChangeDoc;\n};\n\nexport type PouchAttachmentMeta = {\n digest: string;\n content_type: string;\n length: number;\n stub: boolean;\n\n /**\n * 'revpos indicates the generation number (numeric prefix in the revID) at which the attachment was last altered'\n * @link https://github.com/couchbase/couchbase-lite-ios/issues/1200#issuecomment-206444554\n */\n revpos: number;\n};\n\nexport type BlobBuffer = Buffer | Blob;\n\nexport type PouchAttachmentWithData = PouchAttachmentMeta & {\n /**\n * Base64 string with the data\n * or directly a buffer\n */\n data: BlobBuffer;\n type: string;\n /**\n * If set, must be false\n * because we have the full data and not only a stub.\n */\n stub?: false;\n};\n\nexport type PouchChangeDoc = {\n _id: string;\n _rev: string;\n /**\n * True if the document is deleted.\n */\n _deleted?: boolean;\n _attachments: {\n [attachmentId: string]: PouchAttachmentMeta;\n };\n};\n\nexport type WithAttachments = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: PouchAttachmentMeta;\n };\n};\nexport type WithAttachmentsData = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: PouchAttachmentWithData;\n };\n};\n\n\nexport type WithPouchMeta = Data & {\n _rev: string;\n _attachments?: {\n [attachmentId: string]: PouchAttachmentMeta;\n };\n _deleted?: boolean;\n};\n\nexport type PouchdbChangesResult = {\n results: PouchChangeRow[];\n last_seq: number;\n};\n\ndeclare type Debug = {\n enable(what: string): void;\n disable(): void;\n};\n\nexport type PouchDbSorting = (string | string[] | { [k: string]: 'asc' | 'desc' | 1 | -1; })[];\n\n// this is not equal to the standard MangoQuery\n// because of different sorting\nexport type PouchdbQuery = MangoQuery & {\n sort?: PouchDbSorting;\n};\n\nexport type PouchBulkDocResultRow = {\n ok: boolean;\n id: string;\n rev: string;\n\n error?: 'conflict';\n reason?: string;\n};\n\nexport type PouchCheckpoint = {\n sequence: number;\n};\n\nexport type PouchBulkDocOptions = {\n new_edits?: boolean;\n\n // custom options for RxDB\n isDeeper?: boolean;\n custom?: {\n primaryPath: string;\n writeRowById: Map>;\n insertDocsById: Map;\n previousDocsInDb: Map;\n context: string;\n };\n};\n\nexport type PouchMangoQuery = MangoQuery & {\n index: undefined;\n use_index?: string;\n};\n\nexport type ExplainedPouchQuery = {\n dbname: string;\n index: {\n ddoc: string | null;\n name: string; // 'idx-rxdb-index-age,_id'\n type: 'json';\n def: {\n fields: MangoQuerySortPart[];\n };\n };\n selector: MangoQuerySelector;\n range: {\n start_key: any[];\n end_key: any[];\n };\n opts: {\n use_index: string[];\n bookmark: string;\n sort: MangoQuerySortPart[];\n conflicts: boolean;\n r: any[];\n };\n skip: number;\n};\n\nexport type PouchAllDocsResponse = {\n offset: number;\n rows: {\n id: string;\n doc: any;\n key: string;\n value: {\n rev: string;\n deleted?: boolean;\n };\n error?: 'not_found' | string;\n }[];\n total_rows: number;\n};\n\nexport declare class PouchDBInstance {\n constructor(\n name: string,\n options: { adapter: string; }\n );\n readonly name: string;\n readonly adapter: string;\n\n readonly __opts: {\n db: any | string; // contains the adapter function\n deterministic_revs: boolean;\n name: string;\n adapter: string;\n };\n\n static debug: Debug;\n\n static plugin(p: any): void;\n static isInstanceOf(instance: any): boolean;\n info(): Promise;\n\n allDocs(options?: PouchAllDocsOptions): Promise;\n\n bulkDocs(\n docs: { docs: any[]; } | any[],\n options?: PouchBulkDocOptions,\n ): Promise<(PouchBulkDocResultRow | PouchWriteError)[]>;\n\n\n find(mangoQuery: PouchdbQuery): Promise<{\n docs: WithPouchMeta[];\n }>;\n compact(options?: any): Promise;\n destroy(options?: any): Promise;\n get(\n docId: string,\n options?: any\n ): Promise;\n put(\n doc: any,\n options?: any,\n ): Promise;\n remove(\n doc: any | string,\n options?: any,\n ): Promise;\n\n changes(options?: PouchChangesOptionsNonLive): Promise;\n changes(options: PouchChangesOptionsLive): PouchChangesOnChangeEvent;\n\n sync(remoteDb: string | any, options?: PouchReplicationOptions): PouchSyncHandler;\n replicate(options?: PouchReplicationOptions): PouchSyncHandler;\n\n close(): Promise;\n putAttachment(\n docId: string,\n attachmentId: string,\n rev: string,\n attachment: any,\n type: string\n ): Promise;\n getAttachment(\n docId: string,\n attachmentId: string,\n options?: { rev?: string; },\n ): Promise;\n removeAttachment(\n docId: string,\n attachmentId: string,\n rev: string\n ): Promise;\n\n /**\n * @link https://pouchdb.com/api.html#bulk_get\n */\n bulkGet(options: {\n docs: {\n // ID of the document to fetch\n id: string;\n // Revision of the document to fetch. If this is not specified, all available revisions are fetched\n rev?: string;\n\n // I could not find out what this should be\n atts_since?: any;\n }[];\n // Each returned revision body will include its revision history as a _revisions property. Default is false\n revs?: boolean;\n // what does this?\n latest?: boolean;\n // Include attachment data in the response. Default is false, resulting in only stubs being returned.\n attachments?: boolean;\n // Return attachment data as Blobs/Buffers, instead of as base64-encoded strings. Default is false\n binary?: boolean;\n }): Promise<{\n results: {\n id: string;\n docs: {\n ok?: {\n _id: string;\n _rev: string;\n _revisions: {\n ids: string[];\n start: number;\n };\n };\n error?: {\n error: string;\n id: string;\n reason: string;\n rev: string;\n };\n }[];\n }[];\n }>;\n\n revsDiff(diff: any): Promise;\n explain(query: PouchMangoQuery): Promise>;\n\n getIndexes(): Promise<{\n indexes: {\n ddoc: any | null;\n name: string;\n type: string;\n def: {\n fields: {\n [key: string]: 'asc' | 'desc';\n }[];\n };\n }[];\n total_rows: number;\n }>;\n\n createIndex(opts: {\n name: string;\n ddoc: string;\n index: any;\n }): Promise;\n\n /**\n * @link https://pouchdb.com/errors.html#event_emitter_limit\n */\n setMaxListeners(maxListenersAmount: number): void;\n getMaxListeners(): number;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"pouch.d.js","names":[],"sources":["../../../src/types/pouch.d.ts"],"sourcesContent":["import {\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart\n} from './rx-query';\nimport { BulkWriteRow } from './rx-storage';\n\n/**\n * This file contains types that are CouchDB specific\n */\n\nexport interface CouchReplicationOptions {\n live?: boolean;\n retry?: boolean;\n filter?: Function;\n doc_ids?: string[];\n query_params?: any;\n view?: any;\n since?: number | 'now';\n heartbeat?: number;\n timeout?: number;\n batch_size?: number;\n batches_limit?: number;\n back_off_function?: Function;\n checkpoint?: false | 'source' | 'target';\n include_docs?: boolean;\n limit?: number;\n}\n\nexport interface CouchChangesOptionsBase {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n descending?: boolean;\n since?: any;\n limit?: number;\n timeout?: any;\n heartbeat?: number | boolean;\n filter?: any;\n doc_ids?: string | string[];\n query_param?: any;\n view?: any;\n return_docs?: boolean;\n batch_size?: number;\n style?: string;\n}\n\nexport interface CouchChangesOptionsLive extends CouchChangesOptionsBase {\n live: true;\n}\n\nexport interface CouchChangesOptionsNonLive extends CouchChangesOptionsBase {\n live: false;\n}\ninterface CouchChangesOnChangeEvent {\n on: (eventName: string, handler: Function) => void;\n off: (eventName: string, handler: Function) => void;\n cancel(): void;\n}\n\nexport type CouchWriteError = {\n /**\n * status code from couchdb\n * 409 for 'conflict'\n */\n status: number;\n error: true;\n /**\n * primary key value of the errored document\n */\n id: string;\n};\n\n/**\n * possible couch-settings\n * @link https://couchdb.com/api.html#create_database\n */\nexport interface CouchSettings {\n auto_compaction?: boolean;\n revs_limit?: number;\n ajax?: any;\n fetch?: any;\n auth?: any;\n skip_setup?: boolean;\n storage?: any;\n size?: number;\n location?: string;\n iosDatabaseLocation?: string;\n}\n\n/**\n * options for couch.allDocs()\n * @link https://couchdb.com/api.html#batch_fetch\n */\nexport type CouchAllDocsOptions = {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n startkey?: string;\n endkey?: string;\n inclusive_end?: boolean;\n limit?: number;\n skip?: number;\n descending?: boolean;\n key?: string;\n keys?: string[];\n update_seq?: string;\n\n // undocument but needed\n revs?: boolean;\n deleted?: 'ok';\n};\n\nexport type CouchSyncHandlerEvents = 'change' | 'paused' | 'active' | 'error' | 'complete';\nexport type CouchSyncHandler = {\n on(ev: CouchSyncHandlerEvents, fn: (el: any) => void): void;\n off(ev: CouchSyncHandlerEvents, fn: any): void;\n cancel(): void;\n};\n\nexport type CouchChangeRow = {\n id: string;\n seq: number;\n deleted?: true;\n changes: {\n rev: 'string';\n }[];\n /**\n * only if include_docs === true\n */\n doc?: CouchChangeDoc;\n};\n\nexport type CouchAttachmentMeta = {\n digest: string;\n content_type: string;\n length: number;\n stub: boolean;\n\n /**\n * 'revpos indicates the generation number (numeric prefix in the revID) at which the attachment was last altered'\n * @link https://github.com/couchbase/couchbase-lite-ios/issues/1200#issuecomment-206444554\n */\n revpos: number;\n};\n\nexport type BlobBuffer = Buffer | Blob;\n\nexport type CouchAttachmentWithData = CouchAttachmentMeta & {\n /**\n * Base64 string with the data\n * or directly a buffer\n */\n data: BlobBuffer;\n type: string;\n /**\n * If set, must be false\n * because we have the full data and not only a stub.\n */\n stub?: false;\n};\n\nexport type CouchChangeDoc = {\n _id: string;\n _rev: string;\n /**\n * True if the document is deleted.\n */\n _deleted?: boolean;\n _attachments: {\n [attachmentId: string]: CouchAttachmentMeta;\n };\n};\n\nexport type WithAttachments = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: CouchAttachmentMeta;\n };\n};\nexport type WithAttachmentsData = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: CouchAttachmentWithData;\n };\n};\n\n\nexport type WithCouchMeta = Data & {\n _rev: string;\n _attachments?: {\n [attachmentId: string]: CouchAttachmentMeta;\n };\n _deleted?: boolean;\n};\n\nexport type CouchdbChangesResult = {\n results: CouchChangeRow[];\n last_seq: number;\n};\n\ndeclare type Debug = {\n enable(what: string): void;\n disable(): void;\n};\n\nexport type CouchDbSorting = (string | string[] | { [k: string]: 'asc' | 'desc' | 1 | -1; })[];\n\n// this is not equal to the standard MangoQuery\n// because of different sorting\nexport type CouchdbQuery = MangoQuery & {\n sort?: CouchDbSorting;\n};\n\nexport type CouchBulkDocResultRow = {\n ok: boolean;\n id: string;\n rev: string;\n\n error?: 'conflict';\n reason?: string;\n};\n\nexport type CouchCheckpoint = {\n sequence: number;\n};\n\nexport type CouchBulkDocOptions = {\n new_edits?: boolean;\n\n // custom options for RxDB\n isDeeper?: boolean;\n custom?: {\n primaryPath: string;\n writeRowById: Map>;\n insertDocsById: Map;\n previousDocsInDb: Map;\n context: string;\n };\n};\n\nexport type CouchMangoQuery = MangoQuery & {\n index: undefined;\n use_index?: string;\n};\n\nexport type ExplainedCouchQuery = {\n dbname: string;\n index: {\n ddoc: string | null;\n name: string; // 'idx-rxdb-index-age,_id'\n type: 'json';\n def: {\n fields: MangoQuerySortPart[];\n };\n };\n selector: MangoQuerySelector;\n range: {\n start_key: any[];\n end_key: any[];\n };\n opts: {\n use_index: string[];\n bookmark: string;\n sort: MangoQuerySortPart[];\n conflicts: boolean;\n r: any[];\n };\n skip: number;\n};\n\nexport type CouchAllDocsResponse = {\n offset: number;\n rows: {\n id: string;\n doc: any;\n key: string;\n value: {\n rev: string;\n deleted?: boolean;\n };\n error?: 'not_found' | string;\n }[];\n total_rows: number;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/rx-database.d.js.map b/dist/es/types/rx-database.d.js.map index 8e696707939..53ad70ca32c 100644 --- a/dist/es/types/rx-database.d.js.map +++ b/dist/es/types/rx-database.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.d.js","names":[],"sources":["../../../src/types/rx-database.d.ts"],"sourcesContent":["import {\n MigrationState,\n RxCollection,\n RxDumpCollection,\n RxDumpCollectionAsAny\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from '../rx-database';\nimport { Observable } from 'rxjs';\nimport { RxStorage } from './rx-storage.interface';\nimport { PouchDBExpressServerOptions } from './plugins/server-couchdb';\nimport { RxLocalDocument } from './plugins/local-documents';\nimport { RxCleanupPolicy } from './plugins/cleanup';\nimport { HashFunction } from './util';\n\nexport interface RxDatabaseCreator {\n storage: RxStorage;\n instanceCreationOptions?: InstanceCreationOptions;\n name: string;\n password?: string | any;\n multiInstance?: boolean;\n eventReduce?: boolean;\n ignoreDuplicate?: boolean;\n options?: any;\n cleanupPolicy?: Partial;\n /**\n * Set this to true if you want to store local documents\n * in the RxDatabase instance.\n */\n localDocuments?: boolean;\n\n hashFunction?: HashFunction;\n\n /**\n * By default, count() queries in 'slow' mode are not allowed.\n */\n allowSlowCount?: boolean;\n}\n\n// options for the server-plugin\nexport interface CouchDBServerOptions {\n path?: string;\n port?: number;\n cors?: boolean;\n startServer?: boolean;\n pouchdbExpressOptions?: PouchDBExpressServerOptions;\n}\n\nexport type CollectionsOfDatabase = { [key: string]: RxCollection; };\nexport type RxDatabase<\n Collections = CollectionsOfDatabase,\n Internals = any,\n InstanceCreationOptions = any,\n> = RxDatabaseBase<\nInternals,\nInstanceCreationOptions,\nCollections\n> &\nCollections & RxDatabaseGenerated;\n\nexport type AllMigrationStates = {\n collection: RxCollection;\n state: MigrationState;\n}[];\n\nexport interface RxLocalDocumentMutation {\n insertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n upsertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n getLocal(id: string): Promise<\n RxLocalDocument | null\n >;\n getLocal$(id: string): Observable<\n RxLocalDocument | null\n >;\n}\n\nexport interface RxDatabaseGenerated extends RxLocalDocumentMutation> { }\n\n/**\n * Extract the **DocumentType** of a collection.\n */\ntype ExtractDTcol

= P extends RxCollection ? T : { [prop: string]: any; };\n\ninterface RxDumpDatabaseBase {\n instanceToken: string;\n name: string;\n passwordHash: string | null;\n}\nexport interface RxDumpDatabase extends RxDumpDatabaseBase {\n collections: RxDumpCollection>[];\n}\n/**\n * All base properties are typed as any because they can be encrypted.\n */\nexport interface RxDumpDatabaseAny extends RxDumpDatabaseBase {\n collections: RxDumpCollection>>[];\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-database.d.js","names":[],"sources":["../../../src/types/rx-database.d.ts"],"sourcesContent":["import {\n MigrationState,\n RxCollection,\n RxDumpCollection,\n RxDumpCollectionAsAny\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from '../rx-database';\nimport { Observable } from 'rxjs';\nimport { RxStorage } from './rx-storage.interface';\nimport { RxLocalDocument } from './plugins/local-documents';\nimport { RxCleanupPolicy } from './plugins/cleanup';\nimport { HashFunction } from './util';\n\nexport interface RxDatabaseCreator {\n storage: RxStorage;\n instanceCreationOptions?: InstanceCreationOptions;\n name: string;\n password?: string | any;\n multiInstance?: boolean;\n eventReduce?: boolean;\n ignoreDuplicate?: boolean;\n options?: any;\n cleanupPolicy?: Partial;\n /**\n * Set this to true if you want to store local documents\n * in the RxDatabase instance.\n */\n localDocuments?: boolean;\n\n hashFunction?: HashFunction;\n\n /**\n * By default, count() queries in 'slow' mode are not allowed.\n */\n allowSlowCount?: boolean;\n}\n\nexport type CollectionsOfDatabase = { [key: string]: RxCollection; };\nexport type RxDatabase<\n Collections = CollectionsOfDatabase,\n Internals = any,\n InstanceCreationOptions = any,\n> = RxDatabaseBase<\nInternals,\nInstanceCreationOptions,\nCollections\n> &\nCollections & RxDatabaseGenerated;\n\nexport type AllMigrationStates = {\n collection: RxCollection;\n state: MigrationState;\n}[];\n\nexport interface RxLocalDocumentMutation {\n insertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n upsertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n getLocal(id: string): Promise<\n RxLocalDocument | null\n >;\n getLocal$(id: string): Observable<\n RxLocalDocument | null\n >;\n}\n\nexport interface RxDatabaseGenerated extends RxLocalDocumentMutation> { }\n\n/**\n * Extract the **DocumentType** of a collection.\n */\ntype ExtractDTcol

= P extends RxCollection ? T : { [prop: string]: any; };\n\ninterface RxDumpDatabaseBase {\n instanceToken: string;\n name: string;\n passwordHash: string | null;\n}\nexport interface RxDumpDatabase extends RxDumpDatabaseBase {\n collections: RxDumpCollection>[];\n}\n/**\n * All base properties are typed as any because they can be encrypted.\n */\nexport interface RxDumpDatabaseAny extends RxDumpDatabaseBase {\n collections: RxDumpCollection>>[];\n}\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/rx-document.d.js.map b/dist/es/types/rx-document.d.js.map index f6a9da3a41d..881042a6102 100644 --- a/dist/es/types/rx-document.d.js.map +++ b/dist/es/types/rx-document.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-document.d.js","names":[],"sources":["../../../src/types/rx-document.d.ts"],"sourcesContent":["import {\n Observable,\n BehaviorSubject\n} from 'rxjs';\n\nimport {\n RxCollection,\n} from './rx-collection';\nimport {\n RxAttachment,\n RxAttachmentCreator\n} from './rx-attachment';\nimport { RxDocumentData } from './rx-storage';\nimport { RxChangeEvent } from './rx-change-event';\nimport { DeepReadonly, PlainJsonValue } from './util';\nimport { UpdateQuery } from './plugins/update';\nimport { CRDTEntry } from './plugins/crdt';\n\nexport type RxDocument = RxDocumentBase & RxDocumentType & OrmMethods;\n\ndeclare type AtomicUpdateFunction = (\n doc: RxDocumentData,\n rxDocument: RxDocument\n) => RxDocumentType | Promise;\n\n/**\n * Meta data that is attached to each document by RxDB.\n */\nexport type RxDocumentMeta = {\n /**\n * Last write time.\n * Unix epoch in milliseconds.\n */\n lwt: number;\n\n /**\n * Any other value can be attached to the _meta data.\n * Mostly done by plugins to mark documents.\n */\n [k: string]: PlainJsonValue;\n};\n\nexport declare interface RxDocumentBase {\n isInstanceOfRxDocument: true;\n collection: RxCollection;\n readonly deleted: boolean;\n\n readonly $: Observable>;\n readonly deleted$: Observable;\n\n readonly primary: string;\n readonly allAttachments$: Observable[]>;\n\n // internal things\n _dataSync$: BehaviorSubject>;\n _data: RxDocumentData;\n primaryPath: string;\n revision: string;\n _atomicQueue: Promise;\n $emit(cE: RxChangeEvent): void;\n _saveData(newData: any, oldData: any): Promise;\n // /internal things\n\n get$(path: string): Observable;\n get(objPath: string): DeepReadonly;\n populate(objPath: string): Promise | any | null>;\n\n /**\n * mutate the document with a function\n */\n atomicUpdate(mutationFunction: AtomicUpdateFunction, context?: string): Promise>;\n /**\n * patches the given properties\n */\n atomicPatch(patch: Partial): Promise>;\n\n update(updateObj: UpdateQuery): Promise;\n updateCRDT(updateObj: CRDTEntry | CRDTEntry[]): Promise;\n remove(): Promise;\n _handleChangeEvent(cE: any): void;\n\n // only for temporary documents\n set(objPath: string, value: any): RxDocument;\n save(): Promise;\n\n // attachments\n putAttachment(\n creator: RxAttachmentCreator,\n /**\n * If set to true and data is equal,\n * operation will be skipped.\n * This prevents us from upgrading the revision\n * and causing events in the change stream.\n * (default = true)\n */\n skipIfSame?: boolean\n ): Promise>;\n getAttachment(id: string): RxAttachment | null;\n allAttachments(): RxAttachment[];\n\n toJSON(withRevAndAttachments: true): DeepReadonly>;\n toJSON(withRevAndAttachments?: false): DeepReadonly;\n\n toMutableJSON(withRevAndAttachments: true): RxDocumentData;\n toMutableJSON(withRevAndAttachments?: false): RxDocType;\n\n destroy(): void;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-document.d.js","names":[],"sources":["../../../src/types/rx-document.d.ts"],"sourcesContent":["import {\n Observable\n} from 'rxjs';\n\nimport {\n RxCollection,\n} from './rx-collection';\nimport {\n RxAttachment,\n RxAttachmentCreator\n} from './rx-attachment';\nimport { RxDocumentData, WithDeleted } from './rx-storage';\nimport { RxChangeEvent } from './rx-change-event';\nimport { DeepReadonly, MaybePromise, PlainJsonValue } from './util';\nimport { UpdateQuery } from './plugins/update';\nimport { CRDTEntry } from './plugins/crdt';\n\nexport type RxDocument = RxDocumentBase & RxDocumentType & OrmMethods;\n\n\n/**\n * The public facing modify update function.\n * It only gets the document parts as input, that\n * are mutateable by the user.\n */\nexport type ModifyFunction = (\n doc: WithDeleted\n) => MaybePromise> | MaybePromise;\n\n/**\n * Meta data that is attached to each document by RxDB.\n */\nexport type RxDocumentMeta = {\n /**\n * Last write time.\n * Unix epoch in milliseconds.\n */\n lwt: number;\n\n /**\n * Any other value can be attached to the _meta data.\n * Mostly done by plugins to mark documents.\n */\n [k: string]: PlainJsonValue;\n};\n\nexport declare interface RxDocumentBase {\n isInstanceOfRxDocument: true;\n collection: RxCollection;\n readonly deleted: boolean;\n\n readonly $: Observable>>;\n readonly deleted$: Observable;\n\n readonly primary: string;\n readonly allAttachments$: Observable[]>;\n\n // internal things\n _data: RxDocumentData;\n primaryPath: string;\n revision: string;\n $emit(cE: RxChangeEvent): void;\n _saveData(newData: any, oldData: any): Promise>;\n // /internal things\n\n // Returns the latest state of the document\n getLatest(): RxDocument;\n\n\n get$(path: string): Observable;\n get(objPath: string): DeepReadonly;\n populate(objPath: string): Promise | any | null>;\n\n /**\n * mutate the document with a function\n */\n modify(mutationFunction: ModifyFunction, context?: string): Promise>;\n incrementalModify(mutationFunction: ModifyFunction, context?: string): Promise>;\n\n /**\n * patches the given properties\n */\n patch(patch: Partial): Promise>;\n incrementalPatch(patch: Partial): Promise>;\n\n update(updateObj: UpdateQuery): Promise>;\n incrementalUpdate(updateObj: UpdateQuery): Promise>;\n\n updateCRDT(updateObj: CRDTEntry | CRDTEntry[]): Promise>;\n\n remove(): Promise>;\n incrementalRemove(): Promise>;\n\n // only for temporary documents\n set(objPath: string, value: any): RxDocument;\n save(): Promise;\n\n // attachments\n putAttachment(\n creator: RxAttachmentCreator\n ): Promise>;\n getAttachment(id: string): RxAttachment | null;\n allAttachments(): RxAttachment[];\n\n toJSON(withRevAndAttachments: true): DeepReadonly>;\n toJSON(withRevAndAttachments?: false): DeepReadonly;\n\n toMutableJSON(withRevAndAttachments: true): RxDocumentData;\n toMutableJSON(withRevAndAttachments?: false): RxDocType;\n\n destroy(): void;\n}\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/rx-error.d.js.map b/dist/es/types/rx-error.d.js.map index 023f5fe05df..4baab9f02e6 100644 --- a/dist/es/types/rx-error.d.js.map +++ b/dist/es/types/rx-error.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import { RxJsonSchema } from './rx-schema';\nimport {\n RxSchema\n} from '../rx-schema';\nimport { RxPlugin } from './rx-plugin';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages';\nimport { RxReplicationWriteToMasterRow } from './replication-protocol';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport declare class RxError extends Error {\n readonly rxdb: boolean; // always true, use this to detect if its an rxdb-error\n readonly parameters: RxErrorParameters; // an object with parameters to use the programmatically\n readonly code: RxErrorKey; // error-code\n readonly typeError: false; // true if is TypeError\n}\n\nexport declare class RxTypeError extends TypeError {\n readonly rxdb: boolean; // always true, use this to detect if its an rxdb-error\n readonly parameters: RxErrorParameters; // an object with parameters to use the programmatically\n readonly code: RxErrorKey; // error-code\n readonly typeError: true; // true if is TypeError\n}\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: any;\n readonly errors?: RxErrorItem[];\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly pouchDbError?: any;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport interface RxErrorItem {\n readonly field: string;\n readonly message: string;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import { RxJsonSchema } from './rx-schema';\nimport {\n RxSchema\n} from '../rx-schema';\nimport { RxPlugin } from './rx-plugin';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages';\nimport { RxReplicationWriteToMasterRow } from './replication-protocol';\nimport { BulkWriteRow, RxDocumentData } from './rx-storage';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport type {\n RxError,\n RxTypeError\n} from '../rx-error';\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: PlainJsonError;\n readonly errors?: PlainJsonError[];\n readonly writeError?: RxStorageWriteError;\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport type RxValidationError = {\n readonly field: string;\n readonly message: string;\n};\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n rxdb?: true;\n code?: RxErrorKey;\n parameters?: RxErrorParameters;\n stack?: string;\n};\n\n\n\n\n\n/**\n * Error that can happer per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageWriteErrorBase = {\n\n status: number\n | 409 // conflict\n | 422 // schema validation error\n | 510 // attachment data missing\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n};\n\nexport type RxStorageWriteErrorConflict = RxStorageWriteErrorBase & {\n status: 409;\n /**\n * A conflict error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb: RxDocumentData;\n};\n\nexport type RxStorageWriteErrorValidation = RxStorageWriteErrorBase & {\n status: 422;\n /**\n * Other properties that give\n * information about the error,\n * for example a schema validation error\n * might contain the exact error from the validator here.\n * Must be plain JSON!\n */\n validationErrors: RxValidationError[];\n};\n\nexport type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & {\n status: 510;\n attachmentId: string;\n documentInDb?: RxDocumentData;\n};\n\n\nexport type RxStorageWriteError =\n RxStorageWriteErrorConflict |\n RxStorageWriteErrorValidation |\n RxStorageWriteErrorAttachment;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/rx-query.d.js.map b/dist/es/types/rx-query.d.js.map index 9131e759025..f40ba39fc83 100644 --- a/dist/es/types/rx-query.d.js.map +++ b/dist/es/types/rx-query.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.d.js","names":["RxQueryBase"],"sources":["../../../src/types/rx-query.d.ts"],"sourcesContent":["import {\n RxQueryBase\n} from '../rx-query';\nimport { StringKeys } from './util';\n\n/**\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport interface RxQueryOptions {\n $eq?: T;\n $gt?: T;\n $gte?: T;\n $lt?: T;\n $lte?: T;\n $ne?: T;\n $in?: T[];\n $nin?: T[];\n $regex?: RegExp;\n $exists?: boolean;\n $type?: 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object';\n $mod?: number;\n $not?: T;\n $size?: number;\n $elemMatch?: RxQueryOptions;\n}\n\nexport type RxQueryObject = keyof T & { [P in keyof T]?: T[P] | RxQueryOptions; } & {\n $or: RxQueryObject[];\n $nor: RxQueryObject[];\n $and: RxQueryObject[];\n};\n\n// TODO this should be typed\nexport type MangoQuerySelector = {\n [k: string]: MangoQuerySelector | any;\n};\n\n/**\n * Discussion was at:\n * @link https://github.com/pubkey/rxdb/issues/1972\n */\nexport type MangoQuerySortDirection = 'asc' | 'desc';\nexport type MangoQuerySortPart = {\n [k in StringKeys | string]: MangoQuerySortDirection;\n};\n\nexport type MangoQuerySelectorAndIndex = {\n /**\n * Selector is optional,\n * if not given, the query matches all documents\n * that are not _deleted=true.\n */\n selector?: MangoQuerySelector;\n /**\n * By default, the RxStorage implementation\n * decides which index to use when running the query.\n *\n * For better performance, a different index might be defined\n * by setting it in the query.\n * How this improves performance and if the defined index is used,\n * depends on the RxStorage implementation.\n */\n index?: string | string[];\n};\n\nexport type MangoQueryNoLimit = MangoQuerySelectorAndIndex & {\n /**\n * Sorting of the results.\n * If no sort is set, RxDB will sort by the primary key.\n * Also if sort is set, RxDB will add primaryKey sorting\n * if the primaryKey was not in the sort parameters before.\n * This ensures that there is a deterministic sorting of the\n * results, not mather at which order the documents have been\n * inserted into the storage.\n */\n sort?: MangoQuerySortPart[];\n};\n\nexport type MangoQuery = MangoQueryNoLimit & {\n skip?: number;\n limit?: number;\n};\n\nexport type RxQueryOP = 'find' | 'findOne' | 'count';\n\nexport declare class RxQuery extends RxQueryBase {\n equals(queryObj: any): RxQuery;\n eq(queryObj: any): RxQuery;\n or(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n nor(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n and(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n gt(queryObj: any): RxQuery;\n gte(queryObj: any): RxQuery;\n lt(queryObj: any): RxQuery;\n lte(queryObj: any): RxQuery;\n ne(queryObj: any): RxQuery;\n in(queryObj: any[]): RxQuery;\n nin(queryObj: any[]): RxQuery;\n all(queryObj: any): RxQuery;\n regex(queryObj: RegExp): RxQuery;\n exists(queryObj: any): RxQuery;\n elemMatch(queryObj: any): RxQuery;\n mod(p1: any, p2: any, p3: any): RxQuery;\n}\n"],"mappings":"AAAA,SACIA,WAAW,QACR,aAAa"} \ No newline at end of file +{"version":3,"file":"rx-query.d.js","names":["RxQueryBase"],"sources":["../../../src/types/rx-query.d.ts"],"sourcesContent":["import {\n RxQueryBase\n} from '../rx-query';\nimport { StringKeys } from './util';\n\n/**\n * Typed Mango Query Selector\n * @link https://github.com/mongodb/node-mongodb-native/blob/26bce4a8debb65df5a42dc8599e886c9c83de10d/src/mongo_types.ts\n * @link https://stackoverflow.com/a/58436959/3443137\n */\n\ntype Join = K extends string | number ?\n P extends string | number ?\n `${K}${'' extends P ? '' : '.'}${P}`\n : never : never;\n\nexport type Paths = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: K extends string | number ?\n `${K}` | (Paths extends infer R ? Join : never)\n : never\n }[keyof T] : '';\n\nexport type Leaves = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: Join> }[keyof T] : '';\ntype Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]];\n\nexport type PropertyType = string extends Property\n ? unknown\n : Property extends keyof Type\n ? Type[Property]\n : Property extends `${number}`\n ? Type extends ReadonlyArray\n ? ArrayType\n : unknown\n : Property extends `${infer Key}.${infer Rest}`\n ? Key extends `${number}`\n ? Type extends ReadonlyArray\n ? PropertyType\n : unknown\n : Key extends keyof Type\n ? Type[Key] extends Map\n ? MapType\n : PropertyType\n : unknown\n : unknown;\n\n\n/*\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport interface MangoQueryOperators {\n $eq?: PathValueType;\n $gt?: PathValueType;\n $gte?: PathValueType;\n $lt?: PathValueType;\n $lte?: PathValueType;\n $ne?: PathValueType;\n $in?: PathValueType[];\n $nin?: PathValueType[];\n $regex?: string | RegExp;\n $exists?: boolean;\n $type?: 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object';\n $mod?: number;\n $not?: PathValueType;\n $size?: number;\n $elemMatch?: MangoQuerySelector;\n}\n\nexport type MangoQuerySelector = Partial<{\n [Property in Paths]: MangoQueryOperators | PropertyType;\n}> & {\n $and?: MangoQuerySelector[];\n $or?: MangoQuerySelector[];\n $nor?: MangoQuerySelector[];\n};\n\n/**\n * Discussion was at:\n * @link https://github.com/pubkey/rxdb/issues/1972\n */\nexport type MangoQuerySortDirection = 'asc' | 'desc';\nexport type MangoQuerySortPart = {\n [k in StringKeys | string]: MangoQuerySortDirection;\n};\n\nexport type MangoQuerySelectorAndIndex = {\n /**\n * Selector is optional,\n * if not given, the query matches all documents\n * that are not _deleted=true.\n */\n selector?: MangoQuerySelector;\n /**\n * By default, the RxStorage implementation\n * decides which index to use when running the query.\n *\n * For better performance, a different index might be defined\n * by setting it in the query.\n * How this improves performance and if the defined index is used,\n * depends on the RxStorage implementation.\n */\n index?: string | string[];\n};\n\nexport type MangoQueryNoLimit = MangoQuerySelectorAndIndex & {\n /**\n * Sorting of the results.\n * If no sort is set, RxDB will sort by the primary key.\n * Also if sort is set, RxDB will add primaryKey sorting\n * if the primaryKey was not in the sort parameters before.\n * This ensures that there is a deterministic sorting of the\n * results, not mather at which order the documents have been\n * inserted into the storage.\n */\n sort?: MangoQuerySortPart[];\n};\n\nexport type MangoQuery = MangoQueryNoLimit & {\n skip?: number;\n limit?: number;\n};\n\nexport type RxQueryOP = 'find' | 'findOne' | 'count' | 'findByIds';\n\nexport declare class RxQuery extends RxQueryBase {\n equals(queryObj: any): RxQuery;\n eq(queryObj: any): RxQuery;\n or(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n nor(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n and(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n gt(queryObj: any): RxQuery;\n gte(queryObj: any): RxQuery;\n lt(queryObj: any): RxQuery;\n lte(queryObj: any): RxQuery;\n ne(queryObj: any): RxQuery;\n in(queryObj: any[]): RxQuery;\n nin(queryObj: any[]): RxQuery;\n all(queryObj: any): RxQuery;\n regex(queryObj: RegExp): RxQuery;\n exists(queryObj: any): RxQuery;\n elemMatch(queryObj: any): RxQuery;\n mod(p1: any, p2: any, p3: any): RxQuery;\n}\n"],"mappings":"AAAA,SACIA,WAAW,QACR,aAAa"} \ No newline at end of file diff --git a/dist/es/types/rx-storage.d.js.map b/dist/es/types/rx-storage.d.js.map index b462c8add28..5dd65ed6288 100644 --- a/dist/es/types/rx-storage.d.js.map +++ b/dist/es/types/rx-storage.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage.d.js","names":[],"sources":["../../../src/types/rx-storage.d.ts"],"sourcesContent":["import type { ChangeEvent } from 'event-reduce-js';\nimport { RxChangeEvent } from './rx-change-event';\nimport { RxDocumentMeta } from './rx-document';\nimport { MangoQuery } from './rx-query';\nimport { RxJsonSchema } from './rx-schema';\nimport { ById, Override, StringKeys } from './util';\n\n/**\n * The document data how it comes out of the storage instance.\n * Contains all meta data like revision, attachments and deleted-flag.\n */\nexport type RxDocumentData = T & {\n\n /**\n * As other NoSQL databases,\n * RxDB also assumes that no data is finally deleted.\n * Instead the documents are stored with _deleted: true\n * which means they will not be returned at queries.\n */\n _deleted: boolean;\n\n /**\n * The attachments meta data is stored besides to document.\n */\n _attachments: {\n [attachmentId: string]: RxAttachmentData;\n };\n\n /**\n * Contains a revision which is concated with a [height: number]-[identifier: string]\n * like: '1-3hl4kj3l4kgj34g34glk'.\n * The revision is used to detect write conflicts and have a document history.\n * Revisions behave similar to couchdb revisions:\n * @link https://docs.couchdb.org/en/stable/replication/conflicts.html#revision-tree\n\n * When writing a document, you must send the correct revision in the previous-field\n * to make sure that you do not cause a write conflict.\n * The revision of the 'new' document-field must be created, for example via util.createRevision().\n * Any revision that matches the [height]-[hash] format can be used.\n */\n _rev: string;\n _meta: RxDocumentMeta;\n};\n\nexport type RxDocumentDataById = {\n [documentId: string]: RxDocumentData;\n};\n\n/**\n * The document data how it is send to the\n * storage instance to save it.\n */\n// We & T here instead of in RxDocumentData to preserver indexability by keyof T which the Override breaks\nexport type RxDocumentWriteData = T & Override, {\n _attachments: {\n /**\n * To create a new attachment, set the write data\n * To delete an attachment, leave it out on the _attachments property.\n * To change an attachment, set the new write data.\n * To not touch an attachment, just send the stub again\n * which came out of the storage instance.\n */\n [attachmentId: string]: RxAttachmentData | RxAttachmentWriteData;\n };\n}>;\n\nexport type WithDeleted = DocType & {\n _deleted: boolean;\n};\n\n/**\n * Send to the bulkWrite() method of a storage instance.\n */\nexport type BulkWriteRow = {\n /**\n * The current document state in the storage engine,\n * assumed by the application.\n * Undefined if the document is a new insert.\n * While with pouchdb we have to practically only provide the previous revision\n * we here have to send the full previous document data.\n * The reason is that to get the previous revision you anyway have to get the full\n * previous document and so it is easier to just send it all to the storage instance.\n * This will later allow us to use something different then the _rev key for conflict detection\n * when we implement other storage instances.\n */\n previous?: RxDocumentData;\n /**\n * The new document data to be stored in the storage instance.\n */\n document: RxDocumentWriteData;\n};\nexport type BulkWriteRowById = {\n [documentId: string]: BulkWriteRow;\n};\n\n/**\n * After the RxStorage has processed all rows,\n * we have this to work with afterwards.\n */\nexport type BulkWriteRowProcessed = BulkWriteRow & {\n document: RxDocumentData;\n};\n\n\nexport type RxAttachmentDataBase = {\n /**\n * Size of the attachments data\n */\n length: number;\n /**\n * Content type like 'plain/text'\n */\n type: string;\n};\n\n\n/**\n * Meta data of the attachment\n * how it is send to, or comes out of the RxStorage implementation.\n */\nexport type RxAttachmentData = RxAttachmentDataBase & {\n /**\n * The hash of the attachments content.\n * It is NOT calculated by RxDB, instead it is calculated\n * by the RxStorage.\n * There is no way to pre-calculate the hash from the outside because\n * the RxStorage might hash a compressed binary or do a different base64 transformation\n * before hashing.\n * The only guarantee is that the digest will change when the attachments data changes.\n * @link https://github.com/pouchdb/pouchdb/issues/3156#issuecomment-66831010\n * @link https://github.com/pubkey/rxdb/pull/4107\n */\n digest: string;\n};\n\n/**\n * Data which is needed for new attachments\n * that are send from RxDB to the RxStorage implementation.\n */\nexport type RxAttachmentWriteData = RxAttachmentDataBase & {\n /**\n * The data of the attachment. As string in base64 format.\n * In the past we used BlobBuffer internally but it created many\n * problems because of then we need the full data (for encryption/compression)\n * so we anyway have to get the string value out of the BlobBuffer.\n *\n * Also using BlobBuffer has no performance benefit because in some RxStorage implementations,\n * like PouchDB, it just keeps the transaction open for longer because the BlobBuffer\n * has be be read.\n */\n data: string;\n};\n\n\n/**\n * Error that can happer per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageBulkWriteError = {\n\n status: number |\n 409 // conflict\n /**\n * Before you add any other status code,\n * check pouchdb/packages/node_modules/pouch-errors/src/index.js\n * and try to use the same code as PouchDB does.\n */\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n\n /**\n * The error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb?: RxDocumentData;\n};\n\nexport type RxStorageBulkWriteResponse = {\n /**\n * A map that is indexed by the documentId\n * contains all succeeded writes.\n */\n success: RxDocumentDataById;\n\n /**\n * A map that is indexed by the documentId\n * contains all errored writes.\n */\n error: ById>;\n};\n\nexport type PreparedQuery = MangoQuery | any;\n\n/**\n * We return a complex object instead of a single array\n * so we are able to add additional fields in the future.\n */\nexport type RxStorageQueryResult = {\n // the found documents, sort order is important.\n documents: RxDocumentData[];\n};\n\nexport type RxStorageCountResult = {\n count: number;\n /**\n * Returns the mode which was used by the storage\n * to count the documents.\n * If this returns 'slow', RxDB will throw by default\n * if 'allowSlowCount' is not set.\n */\n mode: 'fast' | 'slow';\n};\n\nexport type RxStorageInstanceCreationParams = {\n\n /**\n * A string to uniquely identify the instance of the JavaScript object\n * of the RxDatabase where this RxStorageInstance belongs to.\n * In most cases you would use RxDatabase.token here.\n *\n * This is used so that we can add caching or reuse stuff that belongs to the same RxDatabase.\n * For example the BroadcastChannel that is used for event propagation between multiple browser tabs\n * is cached by this token.\n *\n * In theory we could just use the databaseName for that. But to make it easier in unit tests\n * to simulate cross-tab usage, we cannot assume that the databaseName is unique in a single\n * JavaScript process. Therefore we use the instance token instead.\n */\n databaseInstanceToken: string;\n\n\n databaseName: string;\n collectionName: string;\n schema: RxJsonSchema>;\n options: InstanceCreationOptions;\n /**\n * If multiInstance is true, there can be more\n * then one instance of the database, for example\n * when multiple browser tabs exist or more then one Node.js\n * process relies on the same storage.\n */\n multiInstance: boolean;\n password?: string;\n};\n\nexport type ChangeStreamOptions = {\n\n /**\n * Sequence number of the first event to start with.\n * If you want to get all ongoing events,\n * first get the latest sequence number and input it here.\n *\n * Optional on changeStream,\n * will start from the newest sequence.\n */\n startSequence?: number;\n /**\n * limits the amount of results\n */\n limit?: number;\n};\n\n/**\n * In the past we handles each RxChangeEvent by its own.\n * But it has been shown that this take way more performance then needed,\n * especially when the events get transferred over a data layer\n * like with WebWorkers or the BroadcastChannel.\n * So we now process events as bulks internally.\n */\nexport type EventBulk = {\n /**\n * Unique id of the bulk,\n * used to detect duplicate bulks\n * that have already been processed.\n */\n id: string;\n events: EventType[];\n\n /**\n * Required for replication.\n * Passing this checkpoint into getChangedDocumentsSince()\n * must return all items that have been modied AFTER this write event.\n */\n checkpoint: CheckpointType;\n\n /**\n * The context that was given at the call to bulkWrite()\n * that caused this EventBulk.\n */\n context: string;\n};\n\nexport type ChangeStreamEvent = ChangeEvent> & {\n /**\n * An integer that is increasing\n * and unique per event.\n * Can be used to sort events or get information\n * about how many events there are.\n */\n sequence: number;\n /**\n * The value of the primary key\n * of the changed document\n */\n id: string;\n};\n\nexport type RxStorageChangeEvent = Omit, 'isLocal' | 'collectionName'>;\n\n/**\n * An example for how a RxStorage checkpoint can look like.\n * NOTICE: Not all implementations use this type.\n */\nexport type RxStorageDefaultCheckpoint = {\n id: string;\n lwt: number;\n};\n\n\n\nexport type CategorizeBulkWriteRowsOutput = {\n bulkInsertDocs: BulkWriteRowProcessed[];\n bulkUpdateDocs: BulkWriteRowProcessed[];\n /**\n * Ids of all documents that are changed\n * and so their change must be written into the\n * sequences table so that they can be fetched via\n * RxStorageInstance().getChangedDocumentsSince().\n */\n changedDocumentIds: RxDocType[StringKeys][];\n errors: ById>;\n eventBulk: EventBulk>, any>;\n attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[];\n attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-storage.d.js","names":[],"sources":["../../../src/types/rx-storage.d.ts"],"sourcesContent":["import type { ChangeEvent } from 'event-reduce-js';\nimport { RxChangeEvent } from './rx-change-event';\nimport { RxDocumentMeta } from './rx-document';\nimport { RxStorageWriteError } from './rx-error';\nimport { MangoQuery } from './rx-query';\nimport { RxJsonSchema } from './rx-schema';\nimport { ById, Override, StringKeys } from './util';\n\n/**\n * The document data how it comes out of the storage instance.\n * Contains all meta data like revision, attachments and deleted-flag.\n */\nexport type RxDocumentData = T & {\n\n /**\n * As other NoSQL databases,\n * RxDB also assumes that no data is finally deleted.\n * Instead the documents are stored with _deleted: true\n * which means they will not be returned at queries.\n */\n _deleted: boolean;\n\n /**\n * The attachments meta data is stored besides to document.\n */\n _attachments: {\n [attachmentId: string]: RxAttachmentData;\n };\n\n /**\n * Contains a revision which is concated with a [height: number]-[identifier: string]\n * like: '1-3hl4kj3l4kgj34g34glk'.\n * The revision is used to detect write conflicts and have a document history.\n * Revisions behave similar to couchdb revisions:\n * @link https://docs.couchdb.org/en/stable/replication/conflicts.html#revision-tree\n\n * When writing a document, you must send the correct revision in the previous-field\n * to make sure that you do not cause a write conflict.\n * The revision of the 'new' document-field must be created, for example via util.createRevision().\n * Any revision that matches the [height]-[hash] format can be used.\n */\n _rev: string;\n _meta: RxDocumentMeta;\n};\n\nexport type RxDocumentDataById = {\n [documentId: string]: RxDocumentData;\n};\n\n/**\n * The document data how it is send to the\n * storage instance to save it.\n */\n// We & T here instead of in RxDocumentData to preserver indexability by keyof T which the Override breaks\nexport type RxDocumentWriteData = T & Override, {\n _attachments: {\n /**\n * To create a new attachment, set the write data\n * To delete an attachment, leave it out on the _attachments property.\n * To change an attachment, set the new write data.\n * To not touch an attachment, just send the stub again\n * which came out of the storage instance.\n */\n [attachmentId: string]: RxAttachmentData | RxAttachmentWriteData;\n };\n}>;\n\nexport type WithDeleted = DocType & {\n _deleted: boolean;\n};\n\n/**\n * Send to the bulkWrite() method of a storage instance.\n */\nexport type BulkWriteRow = {\n /**\n * The current document state in the storage engine,\n * assumed by the application.\n * Undefined if the document is a new insert.\n * Notice that we send the full document data as 'previous', not just the revision.\n * The reason is that to get the previous revision you anyway have to get the full\n * previous document and so it is easier to just send it all to the storage instance.\n * This will later allow us to use something different then the _rev key for conflict detection\n * when we implement other storage instances.\n */\n previous?: RxDocumentData;\n /**\n * The new document data to be stored in the storage instance.\n */\n document: RxDocumentWriteData;\n};\nexport type BulkWriteRowById = {\n [documentId: string]: BulkWriteRow;\n};\n\n/**\n * After the RxStorage has processed all rows,\n * we have this to work with afterwards.\n */\nexport type BulkWriteRowProcessed = BulkWriteRow & {\n document: RxDocumentData;\n};\n\n\nexport type RxAttachmentDataBase = {\n /**\n * Size of the attachments data\n */\n length: number;\n /**\n * Content type like 'plain/text'\n */\n type: string;\n};\n\n\n/**\n * Meta data of the attachment\n * how it is send to, or comes out of the RxStorage implementation.\n */\nexport type RxAttachmentData = RxAttachmentDataBase & {\n /**\n * The hash of the attachments content.\n * It is NOT calculated by RxDB, instead it is calculated\n * by the RxStorage.\n * There is no way to pre-calculate the hash from the outside because\n * the RxStorage might hash a compressed binary or do a different base64 transformation\n * before hashing.\n * The only guarantee is that the digest will change when the attachments data changes.\n * @link https://github.com/pouchdb/pouchdb/issues/3156#issuecomment-66831010\n * @link https://github.com/pubkey/rxdb/pull/4107\n */\n digest: string;\n};\n\n/**\n * Data which is needed for new attachments\n * that are send from RxDB to the RxStorage implementation.\n */\nexport type RxAttachmentWriteData = RxAttachmentDataBase & {\n /**\n * The data of the attachment. As string in base64 format.\n * In the past we used BlobBuffer internally but it created many\n * problems because of then we need the full data (for encryption/compression)\n * so we anyway have to get the string value out of the BlobBuffer.\n *\n * Also using BlobBuffer has no performance benefit because in some RxStorage implementations,\n * it just keeps the transaction open for longer because the BlobBuffer\n * has be be read.\n */\n data: string;\n};\n\n\n\n\nexport type RxStorageBulkWriteResponse = {\n /**\n * A map that is indexed by the documentId\n * contains all succeeded writes.\n */\n success: RxDocumentDataById;\n\n /**\n * A map that is indexed by the documentId\n * contains all errored writes.\n */\n error: ById>;\n};\n\nexport type PreparedQuery = MangoQuery | any;\n\n/**\n * We return a complex object instead of a single array\n * so we are able to add additional fields in the future.\n */\nexport type RxStorageQueryResult = {\n // the found documents, sort order is important.\n documents: RxDocumentData[];\n};\n\nexport type RxStorageCountResult = {\n count: number;\n /**\n * Returns the mode which was used by the storage\n * to count the documents.\n * If this returns 'slow', RxDB will throw by default\n * if 'allowSlowCount' is not set.\n */\n mode: 'fast' | 'slow';\n};\n\nexport type RxStorageInstanceCreationParams = {\n\n /**\n * A string to uniquely identify the instance of the JavaScript object\n * of the RxDatabase where this RxStorageInstance belongs to.\n * In most cases you would use RxDatabase.token here.\n *\n * This is used so that we can add caching or reuse stuff that belongs to the same RxDatabase.\n * For example the BroadcastChannel that is used for event propagation between multiple browser tabs\n * is cached by this token.\n *\n * In theory we could just use the databaseName for that. But to make it easier in unit tests\n * to simulate cross-tab usage, we cannot assume that the databaseName is unique in a single\n * JavaScript process. Therefore we use the instance token instead.\n */\n databaseInstanceToken: string;\n\n\n databaseName: string;\n collectionName: string;\n schema: RxJsonSchema>;\n options: InstanceCreationOptions;\n /**\n * If multiInstance is true, there can be more\n * then one instance of the database, for example\n * when multiple browser tabs exist or more then one Node.js\n * process relies on the same storage.\n */\n multiInstance: boolean;\n password?: string;\n};\n\nexport type ChangeStreamOptions = {\n\n /**\n * Sequence number of the first event to start with.\n * If you want to get all ongoing events,\n * first get the latest sequence number and input it here.\n *\n * Optional on changeStream,\n * will start from the newest sequence.\n */\n startSequence?: number;\n /**\n * limits the amount of results\n */\n limit?: number;\n};\n\n/**\n * In the past we handles each RxChangeEvent by its own.\n * But it has been shown that this take way more performance then needed,\n * especially when the events get transferred over a data layer\n * like with WebWorkers or the BroadcastChannel.\n * So we now process events as bulks internally.\n */\nexport type EventBulk = {\n /**\n * Unique id of the bulk,\n * used to detect duplicate bulks\n * that have already been processed.\n */\n id: string;\n events: EventType[];\n\n /**\n * Required for replication.\n * Passing this checkpoint into getChangedDocumentsSince()\n * must return all items that have been modied AFTER this write event.\n */\n checkpoint: CheckpointType;\n\n /**\n * The context that was given at the call to bulkWrite()\n * that caused this EventBulk.\n */\n context: string;\n};\n\nexport type ChangeStreamEvent = ChangeEvent> & {\n /**\n * An integer that is increasing\n * and unique per event.\n * Can be used to sort events or get information\n * about how many events there are.\n */\n sequence: number;\n /**\n * The value of the primary key\n * of the changed document\n */\n id: string;\n};\n\nexport type RxStorageChangeEvent = Omit, 'isLocal' | 'collectionName'>;\n\n/**\n * An example for how a RxStorage checkpoint can look like.\n * NOTICE: Not all implementations use this type.\n */\nexport type RxStorageDefaultCheckpoint = {\n id: string;\n lwt: number;\n};\n\n\n\nexport type CategorizeBulkWriteRowsOutput = {\n bulkInsertDocs: BulkWriteRowProcessed[];\n bulkUpdateDocs: BulkWriteRowProcessed[];\n /**\n * Ids of all documents that are changed\n * and so their change must be written into the\n * sequences table so that they can be fetched via\n * RxStorageInstance().getChangedDocumentsSince().\n */\n changedDocumentIds: RxDocType[StringKeys][];\n errors: ById>;\n eventBulk: EventBulk>, any>;\n attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[];\n attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/rx-storage.interface.d.js.map b/dist/es/types/rx-storage.interface.d.js.map index 578d51d359f..d6fc4ceb444 100644 --- a/dist/es/types/rx-storage.interface.d.js.map +++ b/dist/es/types/rx-storage.interface.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage.interface.d.js","names":[],"sources":["../../../src/types/rx-storage.interface.d.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n RxDocumentData,\n RxDocumentDataById,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from './rx-storage';\nimport type {\n DeepReadonly,\n JsonSchema,\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n Override,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxJsonSchema\n} from './';\nimport type {\n Observable\n} from 'rxjs';\n\n/**\n * RxStorage\n * This is an interface that abstracts the storage engine.\n * This allows us to use RxDB with different engines like PouchDB or LokiJS.\n *\n * Also see\n * @link https://github.com/pubkey/rxdb/issues/1636\n *\n */\n\n\n/**\n * A RxStorage is a module that acts\n * as a factory that can create multiple RxStorageInstance\n * objects.\n *\n * All data inputs and outputs of a StorageInstance must be plain json objects.\n * Do not use Map, Set or anything else that cannot be JSON.stringify-ed.\n * This will ensure that the storage can exchange data\n * when it is a WebWorker or a WASM process or data is send via BroadcastChannel.\n */\nexport interface RxStorage {\n /**\n * name of the storage engine\n * used to detect if plugins do not work so we can throw proper errors.\n */\n readonly name: string;\n\n /**\n * Static functions\n */\n readonly statics: RxStorageStatics;\n\n /**\n * creates a storage instance\n * that can contain the internal database\n * For example the PouchDB instance\n */\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise>;\n}\n\n\n/**\n * User provided mango queries will be filled up by RxDB via normalizeMangoQuery()\n * so we do not have to do many if-field-exist tests in the internals.\n */\nexport type FilledMangoQuery = Override<\nMangoQuery,\n{\n /**\n * The selector is required here.\n */\n selector: MangoQuerySelector;\n\n /**\n * In contrast to the user-provided MangoQuery,\n * the sorting is required here because\n * RxDB has to ensure that the primary key is always\n * part of the sort params.\n */\n sort: MangoQuerySortPart[];\n\n /**\n * In the normalized mango query,\n * the index must always be a string[],\n * never just a string.\n * This makes it easier to use the query because\n * we do not have to do an array check.\n */\n index?: string[];\n\n /**\n * Skip must be set which defaults to 0\n */\n skip: number;\n}\n>;\n\n/**\n * Static functions of the RxStorage.\n * Can be used without creating an instance of any kind.\n * These functions are not directly children of RxStorage because\n * we might need them without having to import the whole storage engine.\n * For example when the Worker plugin is used, the main process only needs the\n * static functions, while the worker process needs the whole storage engine.\n */\nexport type RxStorageStatics = Readonly<{\n /**\n * PouchDB and others have some bugs\n * and behaviors that must be worked around\n * before querying the db.\n *\n * Also some storages do optimizations\n * and other things related to query planning.\n *\n * For performance reason this preparation\n * runs in a single step so it can be cached\n * when the query is used multiple times.\n *\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\n prepareQuery(\n schema: RxJsonSchema>,\n /**\n * a query that can be mutated by the function without side effects.\n */\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery;\n\n /**\n * Returns the sort-comparator,\n * which is able to sort documents in the same way\n * a query over the db would do.\n */\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator;\n\n /**\n * Returns a function\n * that can be used to check if a document\n * matches the query.\n */\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher>;\n\n /**\n * Contains the JsonSchema that matches the checkpoint\n * of this RxStorage.\n * Used in some plugins like the graphql plugin\n * where it is used to create a GraphQL Schema from the checkpoint.\n */\n checkpointSchema: DeepReadonly;\n}>;\n\n\nexport interface RxStorageInstance<\n /**\n * The type of the documents that can be stored in this instance.\n * All documents in an instance must comply to the same schema.\n * Also all documents are RxDocumentData with the meta properties like\n * _deleted or _rev etc.\n */\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType = any\n> {\n readonly databaseName: string;\n /**\n * Returns the internal data that is used by the storage engine.\n * For example the pouchdb instance.\n */\n readonly internals: Readonly;\n readonly options: Readonly;\n /**\n * The schema that defines the documents that are stored in this instance.\n * Notice that the schema must be enhanced with the meta properties like\n * _meta, _rev and _deleted etc. which are added by fillWithDefaultSettings()\n */\n readonly schema: Readonly>>;\n readonly collectionName: string;\n\n /**\n * Writes multiple documents to the storage instance.\n * The write for each single document is atomic, there\n * is no transaction around all documents.\n * The written documents must be the newest revision of that documents data.\n * If the previous document is not the current newest revision, a conflict error\n * must be returned.\n * It must be possible that some document writes succeed\n * and others error. We need this to have a similar behavior as most NoSQL databases.\n */\n bulkWrite(\n documentWrites: BulkWriteRow[],\n /**\n * Context will be used in all\n * changeStream()-events that are emitted as a result\n * of that bulkWrite() operation.\n * Used in plugins so that we can detect that event X\n * comes from operation Y.\n */\n context: string\n ): Promise<\n /**\n * returns the response, split into success and error lists.\n */\n RxStorageBulkWriteResponse\n >;\n\n /**\n * Get Multiple documents by their primary value.\n * This must also return deleted documents.\n */\n findDocumentsById(\n /**\n * List of primary values\n * of the documents to find.\n */\n ids: string[],\n /**\n * If set to true, deleted documents will also be returned.\n */\n withDeleted: boolean\n ): Promise>;\n\n /**\n * Runs a NoSQL 'mango' query over the storage\n * and returns the found documents data.\n * Having all storage instances behave similar\n * is likely the most difficult thing when creating a new\n * rx-storage implementation. Atm we use the pouchdb-find plugin\n * as reference to how NoSQL-queries must work.\n * But the past has shown that pouchdb find can behave wrong,\n * which must be fixed or at least documented.\n */\n query(\n /**\n * Here we get the result of this.prepareQuery()\n * instead of the plain mango query.\n * This makes it easier to have good performance\n * when transformations of the query must be done.\n */\n preparedQuery: PreparedQuery\n ): Promise>;\n\n /**\n * Returns the amount of non-deleted documents\n * that match the given query.\n * Sort, skip and limit of the query must be ignored!\n */\n count(\n preparedQuery: PreparedQuery\n ): Promise;\n\n /**\n * Returns the plain data of a single attachment.\n */\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ): Promise;\n\n /**\n * Returns the current (not the old!) data of all documents that have been changed AFTER the given checkpoint.\n * If the returned array does not reach the limit, it can be assumed that the \"end\" is reached, when paginating over the changes.\n * Also returns a new checkpoint for each document which can be used to continue with the pagination from that change on.\n * Must never return the same document multiple times in the same call operation.\n * This is used by RxDB to known what has changed since X so these docs can be handled by the backup or the replication\n * plugin.\n */\n getChangedDocumentsSince(\n limit: number,\n /**\n * The checkpoint from with to start\n * when the events are sorted in time.\n * If we want to start from the beginning,\n * undefined is used as a checkpoint.\n */\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n }>;\n\n /**\n * Returns an ongoing stream\n * of all changes that happen to the\n * storage instance.\n * Do not forget to unsubscribe.\n *\n * If the RxStorage support multi-instance,\n * and the storage is persistend,\n * then the emitted changes of one RxStorageInstance\n * must be also emitted to other instances with the same databaseName+collectionName.\n * See ./rx-storage-multiinstance.ts\n */\n changeStream(): Observable, CheckpointType>>;\n\n /**\n * Runs a cleanup that removes all tompstones\n * of documents that have _deleted set to true\n * to free up disc space.\n *\n * Returns true if all cleanable documents have been removed.\n * Returns false if there are more documents to be cleaned up,\n * but not all have been purged because that would block the storage for too long.\n */\n cleanup(\n /**\n * The minimum time in milliseconds\n * of how long a document must have been deleted\n * until it is purged by the cleanup.\n */\n minimumDeletedTime: number\n ): Promise<\n /**\n * True if all docs cleaned up,\n * false if there are more docs to clean up\n */\n boolean\n >;\n\n /**\n * Closes the storage instance so it cannot be used\n * anymore and should clear all memory.\n * The returned promise must resolve when everything is cleaned up.\n */\n close(): Promise;\n\n /**\n * Remove the database and\n * deletes all of its data.\n */\n remove(): Promise;\n\n /**\n * Instead of passing the conflict-resolver function\n * into the storage, we have to work with an observable that emits tasks\n * and a resolver that takes resolved tasks.\n * This is needed because the RxStorageInstance might run inside of a Worker\n * other JavaScript process, so we cannot pass plain code.\n */\n conflictResultionTasks(): Observable>;\n resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-storage.interface.d.js","names":[],"sources":["../../../src/types/rx-storage.interface.d.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n RxDocumentData,\n RxDocumentDataById,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from './rx-storage';\nimport type {\n DeepReadonly,\n JsonSchema,\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n Override,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxJsonSchema\n} from './';\nimport type {\n Observable\n} from 'rxjs';\n\n/**\n * RxStorage\n * This is an interface that abstracts the storage engine.\n * This allows us to use RxDB with different storage engines.\n *\n * @link https://rxdb.info/rx-storage.html\n * @link https://github.com/pubkey/rxdb/issues/1636\n */\n\n\n/**\n * A RxStorage is a module that acts\n * as a factory that can create multiple RxStorageInstance\n * objects.\n *\n * All data inputs and outputs of a StorageInstance must be plain json objects.\n * Do not use Map, Set or anything else that cannot be JSON.stringify-ed.\n * This will ensure that the storage can exchange data\n * when it is a WebWorker or a WASM process or data is send via BroadcastChannel.\n */\nexport interface RxStorage {\n /**\n * name of the storage engine\n * used to detect if plugins do not work so we can throw proper errors.\n */\n readonly name: string;\n\n /**\n * Static functions\n */\n readonly statics: RxStorageStatics;\n\n /**\n * Creates a storage instance\n * that can contain the NoSQL documents of a collection.\n */\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise>;\n}\n\n\n/**\n * User provided mango queries will be filled up by RxDB via normalizeMangoQuery()\n * so we do not have to do many if-field-exist tests in the internals.\n */\nexport type FilledMangoQuery = Override<\nMangoQuery,\n{\n /**\n * The selector is required here.\n */\n selector: MangoQuerySelector;\n\n /**\n * In contrast to the user-provided MangoQuery,\n * the sorting is required here because\n * RxDB has to ensure that the primary key is always\n * part of the sort params.\n */\n sort: MangoQuerySortPart[];\n\n /**\n * In the normalized mango query,\n * the index must always be a string[],\n * never just a string.\n * This makes it easier to use the query because\n * we do not have to do an array check.\n */\n index?: string[];\n\n /**\n * Skip must be set which defaults to 0\n */\n skip: number;\n}\n>;\n\n/**\n * Static functions of the RxStorage.\n * Can be used without creating an instance of any kind.\n * These functions are not directly children of RxStorage because\n * we might need them without having to import the whole storage engine.\n * For example when the Worker plugin is used, the main process only needs the\n * static functions, while the worker process needs the whole storage engine.\n */\nexport type RxStorageStatics = Readonly<{\n /**\n * Storages can have some bugs\n * and behaviors that must be worked around\n * before querying the db.\n *\n * Also some storages do optimizations\n * and other things related to query planning.\n *\n * For performance reason this preparation\n * runs in a single step so it can be cached\n * when the query is used multiple times.\n *\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\n prepareQuery(\n schema: RxJsonSchema>,\n /**\n * a query that can be mutated by the function without side effects.\n */\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery;\n\n /**\n * Returns the sort-comparator,\n * which is able to sort documents in the same way\n * a query over the db would do.\n */\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator;\n\n /**\n * Returns a function\n * that can be used to check if a document\n * matches the query.\n */\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher>;\n\n /**\n * Contains the JsonSchema that matches the checkpoint\n * of this RxStorage.\n * Used in some plugins like the graphql plugin\n * where it is used to create a GraphQL Schema from the checkpoint.\n */\n checkpointSchema: DeepReadonly;\n}>;\n\n\nexport interface RxStorageInstance<\n /**\n * The type of the documents that can be stored in this instance.\n * All documents in an instance must comply to the same schema.\n * Also all documents are RxDocumentData with the meta properties like\n * _deleted or _rev etc.\n */\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType = any\n> {\n readonly databaseName: string;\n /**\n * Returns the internal data that is used by the storage engine.\n */\n readonly internals: Readonly;\n readonly options: Readonly;\n /**\n * The schema that defines the documents that are stored in this instance.\n * Notice that the schema must be enhanced with the meta properties like\n * _meta, _rev and _deleted etc. which are added by fillWithDefaultSettings()\n */\n readonly schema: Readonly>>;\n readonly collectionName: string;\n\n /**\n * Writes multiple documents to the storage instance.\n * The write for each single document is atomic, there\n * is no transaction around all documents.\n * The written documents must be the newest revision of that documents data.\n * If the previous document is not the current newest revision, a conflict error\n * must be returned.\n * It must be possible that some document writes succeed\n * and others error. We need this to have a similar behavior as most NoSQL databases.\n */\n bulkWrite(\n documentWrites: BulkWriteRow[],\n /**\n * Context will be used in all\n * changeStream()-events that are emitted as a result\n * of that bulkWrite() operation.\n * Used in plugins so that we can detect that event X\n * comes from operation Y.\n */\n context: string\n ): Promise<\n /**\n * returns the response, split into success and error lists.\n */\n RxStorageBulkWriteResponse\n >;\n\n /**\n * Get Multiple documents by their primary value.\n * This must also return deleted documents.\n */\n findDocumentsById(\n /**\n * List of primary values\n * of the documents to find.\n */\n ids: string[],\n /**\n * If set to true, deleted documents will also be returned.\n */\n withDeleted: boolean\n ): Promise>;\n\n /**\n * Runs a NoSQL 'mango' query over the storage\n * and returns the found documents data.\n * Having all storage instances behave similar\n * is likely the most difficult thing when creating a new\n * rx-storage implementation.\n */\n query(\n /**\n * Here we get the result of this.prepareQuery()\n * instead of the plain mango query.\n * This makes it easier to have good performance\n * when transformations of the query must be done.\n */\n preparedQuery: PreparedQuery\n ): Promise>;\n\n /**\n * Returns the amount of non-deleted documents\n * that match the given query.\n * Sort, skip and limit of the query must be ignored!\n */\n count(\n preparedQuery: PreparedQuery\n ): Promise;\n\n /**\n * Returns the plain data of a single attachment.\n */\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ): Promise;\n\n /**\n * Returns the current (not the old!) data of all documents that have been changed AFTER the given checkpoint.\n * If the returned array does not reach the limit, it can be assumed that the \"end\" is reached, when paginating over the changes.\n * Also returns a new checkpoint for each document which can be used to continue with the pagination from that change on.\n * Must never return the same document multiple times in the same call operation.\n * This is used by RxDB to known what has changed since X so these docs can be handled by the backup or the replication\n * plugin.\n */\n getChangedDocumentsSince(\n limit: number,\n /**\n * The checkpoint from with to start\n * when the events are sorted in time.\n * If we want to start from the beginning,\n * undefined is used as a checkpoint.\n */\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n }>;\n\n /**\n * Returns an ongoing stream\n * of all changes that happen to the\n * storage instance.\n * Do not forget to unsubscribe.\n *\n * If the RxStorage support multi-instance,\n * and the storage is persistend,\n * then the emitted changes of one RxStorageInstance\n * must be also emitted to other instances with the same databaseName+collectionName.\n * See ./rx-storage-multiinstance.ts\n */\n changeStream(): Observable, CheckpointType>>;\n\n /**\n * Runs a cleanup that removes all tompstones\n * of documents that have _deleted set to true\n * to free up disc space.\n *\n * Returns true if all cleanable documents have been removed.\n * Returns false if there are more documents to be cleaned up,\n * but not all have been purged because that would block the storage for too long.\n */\n cleanup(\n /**\n * The minimum time in milliseconds\n * of how long a document must have been deleted\n * until it is purged by the cleanup.\n */\n minimumDeletedTime: number\n ): Promise<\n /**\n * True if all docs cleaned up,\n * false if there are more docs to clean up\n */\n boolean\n >;\n\n /**\n * Closes the storage instance so it cannot be used\n * anymore and should clear all memory.\n * The returned promise must resolve when everything is cleaned up.\n */\n close(): Promise;\n\n /**\n * Remove the database and\n * deletes all of its data.\n */\n remove(): Promise;\n\n /**\n * Instead of passing the conflict-resolver function\n * into the storage, we have to work with an observable that emits tasks\n * and a resolver that takes resolved tasks.\n * This is needed because the RxStorageInstance might run inside of a Worker\n * other JavaScript process, so we cannot pass plain code.\n */\n conflictResultionTasks(): Observable>;\n resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise;\n}\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/types/util.d.js.map b/dist/es/types/util.d.js.map index 76b17ac1f6c..5fd311185a7 100644 --- a/dist/es/types/util.d.js.map +++ b/dist/es/types/util.d.js.map @@ -1 +1 @@ -{"version":3,"file":"util.d.js","names":[],"sources":["../../../src/types/util.d.ts"],"sourcesContent":["import { RxStorage } from './rx-storage.interface';\n\nexport type MaybePromise = Promise | T;\n\n\nexport type PlainJsonValue = string | number | boolean | PlainSimpleJsonObject | PlainSimpleJsonObject[] | PlainJsonValue[];\nexport type PlainSimpleJsonObject = {\n [k: string]: PlainJsonValue | PlainJsonValue[];\n};\n\n/**\n * @link https://stackoverflow.com/a/49670389/3443137\n */\ntype DeepReadonly =\n T extends (infer R)[] ? DeepReadonlyArray :\n T extends Function ? T :\n T extends object ? DeepReadonlyObject :\n T;\n\ninterface DeepReadonlyArray extends ReadonlyArray> { }\n\ntype DeepReadonlyObject = {\n readonly [P in keyof T]: DeepReadonly;\n};\n\nexport type MaybeReadonly = T | Readonly;\n\n\n/**\n * Opposite of DeepReadonly,\n * makes everything mutable again.\n */\ntype DeepMutable = (\n T extends object\n ? {\n -readonly [K in keyof T]: (\n T[K] extends object\n ? DeepMutable\n : T[K]\n )\n }\n : never\n);\n\n/**\n * Can be used like 'keyof'\n * but only represents the string keys, not the Symbols or numbers.\n * @link https://stackoverflow.com/a/51808262/3443137\n */\nexport type StringKeys = Extract;\n\nexport type AnyKeys = { [P in keyof T]?: T[P] | any };\nexport interface AnyObject {\n [k: string]: any;\n}\n\n/**\n * @link https://dev.to/vborodulin/ts-how-to-override-properties-with-type-intersection-554l\n */\nexport type Override = Omit & T2;\n\n\n\nexport type ById = {\n [id: string]: T;\n};\n\n/**\n * To test a storage, we need these\n * configuration values.\n */\nexport type RxTestStorage = {\n // TODO remove name here, it can be read out already via getStorage().name\n readonly name: string;\n readonly getStorage: () => RxStorage;\n /**\n * Returns a storage that is used in performance tests.\n * For example in a browser it should return the storage with an IndexedDB based adapter,\n * while in node.js it must use the filesystem.\n */\n readonly getPerformanceStorage: () => {\n storage: RxStorage;\n /**\n * A description that describes the storage and setting.\n * For example 'pouchdb-idb'.\n */\n description: string;\n };\n /**\n * True if the storage is able to\n * keep data after an instance is closed and opened again.\n */\n readonly hasPersistence: boolean;\n readonly hasMultiInstance: boolean;\n readonly hasCouchDBReplication: boolean;\n readonly hasAttachments: boolean;\n // true if the storage supports $regex queries, false if not.\n readonly hasRegexSupport: boolean;\n};\n\n\nexport type HashFunction = (input: string) => string;\n\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n stack?: string;\n rxdb?: true;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"util.d.js","names":[],"sources":["../../../src/types/util.d.ts"],"sourcesContent":["import { RxStorage } from './rx-storage.interface';\n\nexport type MaybePromise = Promise | T;\n\n\nexport type PlainJsonValue = string | number | boolean | PlainSimpleJsonObject | PlainSimpleJsonObject[] | PlainJsonValue[];\nexport type PlainSimpleJsonObject = {\n [k: string]: PlainJsonValue | PlainJsonValue[];\n};\n\n/**\n * @link https://stackoverflow.com/a/49670389/3443137\n */\ntype DeepReadonly =\n T extends (infer R)[] ? DeepReadonlyArray :\n T extends Function ? T :\n T extends object ? DeepReadonlyObject :\n T;\n\ninterface DeepReadonlyArray extends ReadonlyArray> { }\n\ntype DeepReadonlyObject = {\n readonly [P in keyof T]: DeepReadonly;\n};\n\nexport type MaybeReadonly = T | Readonly;\n\n\n/**\n * Opposite of DeepReadonly,\n * makes everything mutable again.\n */\ntype DeepMutable = (\n T extends object\n ? {\n -readonly [K in keyof T]: (\n T[K] extends object\n ? DeepMutable\n : T[K]\n )\n }\n : never\n);\n\n/**\n * Can be used like 'keyof'\n * but only represents the string keys, not the Symbols or numbers.\n * @link https://stackoverflow.com/a/51808262/3443137\n */\nexport type StringKeys = Extract;\n\nexport type AnyKeys = { [P in keyof T]?: T[P] | any };\nexport interface AnyObject {\n [k: string]: any;\n}\n\n/**\n * @link https://dev.to/vborodulin/ts-how-to-override-properties-with-type-intersection-554l\n */\nexport type Override = Omit & T2;\n\n\n\nexport type ById = {\n [id: string]: T;\n};\n\n/**\n * To test a storage, we need these\n * configuration values.\n */\nexport type RxTestStorage = {\n // TODO remove name here, it can be read out already via getStorage().name\n readonly name: string;\n readonly getStorage: () => RxStorage;\n /**\n * Returns a storage that is used in performance tests.\n * For example in a browser it should return the storage with an IndexedDB based adapter,\n * while in node.js it must use the filesystem.\n */\n readonly getPerformanceStorage: () => {\n storage: RxStorage;\n /**\n * A description that describes the storage and setting.\n * For example 'dexie-native'.\n */\n description: string;\n };\n /**\n * True if the storage is able to\n * keep data after an instance is closed and opened again.\n */\n readonly hasPersistence: boolean;\n readonly hasMultiInstance: boolean;\n readonly hasCouchDBReplication: boolean;\n readonly hasAttachments: boolean;\n // true if the storage supports $regex queries, false if not.\n readonly hasRegexSupport: boolean;\n};\n\n\nexport type HashFunction = (input: string) => string;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/es/util.js b/dist/es/util.js deleted file mode 100644 index 526c8b84bf4..00000000000 --- a/dist/es/util.js +++ /dev/null @@ -1,784 +0,0 @@ -/** - * Returns an error that indicates that a plugin is missing - * We do not throw a RxError because this should not be handled - * programmatically but by using the correct import - */ -export function pluginMissing(pluginKey) { - var keyParts = pluginKey.split('-'); - var pluginName = 'RxDB'; - keyParts.forEach(function (part) { - pluginName += ucfirst(part); - }); - pluginName += 'Plugin'; - return new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { " + pluginName + " } from 'rxdb/plugins/" + pluginKey + "';\n addRxPlugin(" + pluginName + ");\n "); -} - -/** - * This is a very fast hash method - * but it is not cryptographically secure. - * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int). - * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery - * @return a string as hash-result - */ -export function fastUnsecureHash(inputString, -// used to test the polyfill -doNotUseTextEncoder) { - var hashValue = 0, - i, - chr, - len; - - /** - * For better performance we first transform all - * chars into their ascii numbers at once. - * - * This is what makes the murmurhash implementation such fast. - * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4 - */ - var encoded; - - /** - * All modern browsers support the TextEncoder - * @link https://caniuse.com/textencoder - * But to make RxDB work in other JavaScript runtimes, - * like when using it in flutter or QuickJS, we need to - * make it work even when there is no TextEncoder. - */ - if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) { - encoded = new TextEncoder().encode(inputString); - } else { - encoded = []; - for (var j = 0; j < inputString.length; j++) { - encoded.push(inputString.charCodeAt(j)); - } - } - for (i = 0, len = inputString.length; i < len; i++) { - chr = encoded[i]; - hashValue = (hashValue << 5) - hashValue + chr; - hashValue |= 0; // Convert to 32bit integer - } - - if (hashValue < 0) { - hashValue = hashValue * -1; - } - - /** - * To make the output smaller - * but still have it to represent the same value, - * we use the biggest radix of 36 instead of just - * transforming it into a hex string. - */ - return hashValue.toString(36); -} - -/** - * Default hash method used to create revision hashes - * that do not have to be cryptographically secure. - * IMPORTANT: Changing the default hashing method - * requires a BREAKING change! - */ -export function defaultHashFunction(input) { - return fastUnsecureHash(input); -} - -/** - * Returns the current unix time in milliseconds (with two decmials!) - * Because the accuracy of getTime() in javascript is bad, - * and we cannot rely on performance.now() on all platforms, - * this method implements a way to never return the same value twice. - * This ensures that when now() is called often, we do not loose the information - * about which call came first and which came after. - * - * We had to move from having no decimals, to having two decimal - * because it turned out that some storages are such fast that - * calling this method too often would return 'the future'. - */ -var _lastNow = 0; -/** - * Returns the current time in milliseconds, - * also ensures to not return the same value twice. - */ -export function now() { - var ret = new Date().getTime(); - ret = ret + 0.01; - if (ret <= _lastNow) { - ret = _lastNow + 0.01; - } - - /** - * Strip the returned number to max two decimals. - * In theory we would not need this but - * in practice JavaScript has no such good number precision - * so rounding errors could add another decimal place. - */ - var twoDecimals = parseFloat(ret.toFixed(2)); - _lastNow = twoDecimals; - return twoDecimals; -} - -/** - * returns a promise that resolves on the next tick - */ -export function nextTick() { - return new Promise(function (res) { - return setTimeout(res, 0); - }); -} -export function promiseWait() { - var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - return new Promise(function (res) { - return setTimeout(res, ms); - }); -} -export function toPromise(maybePromise) { - if (maybePromise && typeof maybePromise.then === 'function') { - // is promise - return maybePromise; - } else { - return Promise.resolve(maybePromise); - } -} -export var PROMISE_RESOLVE_TRUE = Promise.resolve(true); -export var PROMISE_RESOLVE_FALSE = Promise.resolve(false); -export var PROMISE_RESOLVE_NULL = Promise.resolve(null); -export var PROMISE_RESOLVE_VOID = Promise.resolve(); -export function requestIdlePromise() { - var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - if (typeof window === 'object' && window['requestIdleCallback']) { - return new Promise(function (res) { - return window['requestIdleCallback'](res, { - timeout: timeout - }); - }); - } else { - return promiseWait(0); - } -} - -/** - * like Promise.all() but runs in series instead of parallel - * @link https://github.com/egoist/promise.series/blob/master/index.js - * @param tasks array with functions that return a promise - */ -export function promiseSeries(tasks, initial) { - return tasks.reduce(function (current, next) { - return current.then(next); - }, Promise.resolve(initial)); -} - -/** - * run the callback if requestIdleCallback available - * do nothing if not - * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback - */ -export function requestIdleCallbackIfAvailable(fun) { - if (typeof window === 'object' && window['requestIdleCallback']) window['requestIdleCallback'](fun); -} - -/** - * uppercase first char - */ -export function ucfirst(str) { - str += ''; - var f = str.charAt(0).toUpperCase(); - return f + str.substr(1); -} - -/** - * removes trailing and ending dots from the string - */ -export function trimDots(str) { - // start - while (str.charAt(0) === '.') str = str.substr(1); - - // end - while (str.slice(-1) === '.') str = str.slice(0, -1); - return str; -} -export function runXTimes(xTimes, fn) { - new Array(xTimes).fill(0).forEach(function (_v, idx) { - return fn(idx); - }); -} -export function ensureNotFalsy(obj) { - if (!obj) { - throw new Error('ensureNotFalsy() is falsy'); - } - return obj; -} -export function ensureInteger(obj) { - if (!Number.isInteger(obj)) { - throw new Error('ensureInteger() is falsy'); - } - return obj; -} - -/** - * deep-sort an object so its attributes are in lexical order. - * Also sorts the arrays inside of the object if no-array-sort not set - */ -export function sortObject(obj) { - var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (!obj) return obj; // do not sort null, false or undefined - - // array - if (!noArraySort && Array.isArray(obj)) { - return obj.sort(function (a, b) { - if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b); - if (typeof a === 'object') return 1;else return -1; - }).map(function (i) { - return sortObject(i, noArraySort); - }); - } - - // object - // array is also of type object - if (typeof obj === 'object' && !Array.isArray(obj)) { - if (obj instanceof RegExp) { - return obj; - } - var out = {}; - Object.keys(obj).sort(function (a, b) { - return a.localeCompare(b); - }).forEach(function (key) { - out[key] = sortObject(obj[key], noArraySort); - }); - return out; - } - - // everything else - return obj; -} - -/** - * used to JSON.stringify() objects that contain a regex - * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs! - */ -export function stringifyFilter(key, value) { - if (value instanceof RegExp) { - return value.toString(); - } - return value; -} - -/** - * get a random string which can be used with couchdb - * @link http://stackoverflow.com/a/1349426/3443137 - */ -export function randomCouchString() { - var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; - var text = ''; - var possible = 'abcdefghijklmnopqrstuvwxyz'; - for (var i = 0; i < length; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } - return text; -} - -/** - * A random string that is never inside of any storage - */ -export var RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX'; -export function lastOfArray(ar) { - return ar[ar.length - 1]; -} - -/** - * shuffle the given array - */ -export function shuffleArray(arr) { - return arr.sort(function () { - return Math.random() - 0.5; - }); -} - -/** - * Split array with items into smaller arrays with items - * @link https://stackoverflow.com/a/7273794/3443137 - */ -export function batchArray(array, batchSize) { - array = array.slice(0); - var ret = []; - while (array.length) { - var batch = array.splice(0, batchSize); - ret.push(batch); - } - return ret; -} - -/** - * @link https://stackoverflow.com/a/15996017 - */ -export function removeOneFromArrayIfMatches(ar, condition) { - ar = ar.slice(); - var i = ar.length; - var done = false; - while (i-- && !done) { - if (condition(ar[i])) { - done = true; - ar.splice(i, 1); - } - } - return ar; -} - -/** - * transforms the given adapter into a pouch-compatible object - */ -export function adapterObject(adapter) { - var adapterObj = { - db: adapter - }; - if (typeof adapter === 'string') { - adapterObj = { - adapter: adapter, - db: undefined - }; - } - return adapterObj; -} - -/** - * Deep clone a plain json object. - * Does not work with recursive stuff - * or non-plain-json. - * IMPORANT: Performance of this is very important, - * do not change it without running performance tests! - * - * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts - */ -function deepClone(src) { - if (!src) { - return src; - } - if (src === null || typeof src !== 'object') { - return src; - } - if (Array.isArray(src)) { - var ret = new Array(src.length); - var i = ret.length; - while (i--) { - ret[i] = deepClone(src[i]); - } - return ret; - } - var dest = {}; - // eslint-disable-next-line guard-for-in - for (var key in src) { - // TODO we should not be required to deep clone RegEx objects, - // this must be fixed in RxDB. - if (src[key] instanceof RegExp) { - dest[key] = src[key]; - } else { - dest[key] = deepClone(src[key]); - } - } - return dest; -} -export var clone = deepClone; - -/** - * does a flat copy on the objects, - * is about 3 times faster then using deepClone - * @link https://jsperf.com/object-rest-spread-vs-clone/2 - */ -export function flatClone(obj) { - return Object.assign({}, obj); -} - -/** - * @link https://stackoverflow.com/a/11509718/3443137 - */ -export function firstPropertyNameOfObject(obj) { - return Object.keys(obj)[0]; -} -export function firstPropertyValueOfObject(obj) { - var key = Object.keys(obj)[0]; - return obj[key]; -} - -/** - * returns a flattened object - * @link https://gist.github.com/penguinboy/762197 - */ -export function flattenObject(ob) { - var toReturn = {}; - for (var i in ob) { - if (!ob.hasOwnProperty(i)) continue; - if (typeof ob[i] === 'object') { - var flatObject = flattenObject(ob[i]); - for (var _x in flatObject) { - if (!flatObject.hasOwnProperty(_x)) continue; - toReturn[i + '.' + _x] = flatObject[_x]; - } - } else { - toReturn[i] = ob[i]; - } - } - return toReturn; -} -export function parseRevision(revision) { - var split = revision.split('-'); - return { - height: parseInt(split[0], 10), - hash: split[1] - }; -} -export function getHeightOfRevision(revision) { - return parseRevision(revision).height; -} - -/** - * Creates the next write revision for a given document. - */ -export function createRevision(hashFunction, docData, previousDocData) { - var previousRevision = previousDocData ? previousDocData._rev : null; - var previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0; - var newRevisionHeight = previousRevisionHeigth + 1; - var docWithoutRev = Object.assign({}, docData, { - _rev: undefined, - _rev_tree: undefined, - /** - * All _meta properties MUST NOT be part of the - * revision hash. - * Plugins might temporarily store data in the _meta - * field and strip it away when the document is replicated - * or written to another storage. - */ - _meta: undefined - }); - - /** - * The revision height must be part of the hash - * as the last parameter of the document data. - * This is required to ensure we never ever create - * two different document states that have the same revision - * hash. Even writing the exact same document data - * must have to result in a different hash so that - * the replication can known if the state just looks equal - * or if it is really exactly the equal state in data and time. - */ - delete docWithoutRev._rev; - docWithoutRev._rev = previousDocData ? newRevisionHeight : 1; - var diggestString = JSON.stringify(docWithoutRev); - var revisionHash = hashFunction(diggestString); - return newRevisionHeight + '-' + revisionHash; -} - -/** - * Faster way to check the equalness of document lists - * compared to doing a deep-equal. - * Here we only check the ids and revisions. - */ -export function areRxDocumentArraysEqual(primaryPath, ar1, ar2) { - if (ar1.length !== ar2.length) { - return false; - } - var i = 0; - var len = ar1.length; - while (i < len) { - var row1 = ar1[i]; - var row2 = ar2[i]; - i++; - if (row1._rev !== row2._rev || row1[primaryPath] !== row2[primaryPath]) { - return false; - } - } - return true; -} - -/** - * overwrites the getter with the actual value - * Mostly used for caching stuff on the first run - */ -export function overwriteGetterForCaching(obj, getterName, value) { - Object.defineProperty(obj, getterName, { - get: function get() { - return value; - } - }); - return value; -} - -/** - * returns true if the given name is likely a folder path - */ -export function isFolderPath(name) { - // do not check, if foldername is given - if (name.includes('/') || - // unix - name.includes('\\') // windows - ) { - return true; - } else { - return false; - } -} -export function getFromMapOrThrow(map, key) { - var val = map.get(key); - if (typeof val === 'undefined') { - throw new Error('missing value from map ' + key); - } - return val; -} -export function getFromObjectOrThrow(obj, key) { - var val = obj[key]; - if (!val) { - throw new Error('missing value from object ' + key); - } - return val; -} - -/** - * returns true if the supplied argument is either an Array or a Readonly> - */ -export function isMaybeReadonlyArray(x) { - // While this looks strange, it's a workaround for an issue in TypeScript: - // https://github.com/microsoft/TypeScript/issues/17002 - // - // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array, - // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`. - // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while - // still performing runtime type inspection. - return Array.isArray(x); -} - -/** - * Use this in array.filter() to remove all empty slots - * and have the correct typings afterwards. - * @link https://stackoverflow.com/a/46700791/3443137 - */ -export function arrayFilterNotEmpty(value) { - if (value === null || value === undefined) { - return false; - } - return true; -} - -/** - * NO! We cannot just use btoa() and atob() - * because they do not work correctly with binary data. - * @link https://stackoverflow.com/q/30106476/3443137 - */ -import { encode, decode } from 'js-base64'; - -/** - * atob() and btoa() do not work well with non ascii chars, - * so we have to use these helper methods instead. - * @link https://stackoverflow.com/a/30106551/3443137 - */ -// Encoding UTF8 -> base64 -export function b64EncodeUnicode(str) { - return encode(str); -} - -// Decoding base64 -> UTF8 -export function b64DecodeUnicode(str) { - return decode(str); -} - -/** - * @link https://stackoverflow.com/a/9458996/3443137 - */ -export function arrayBufferToBase64(buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - var len = bytes.byteLength; - for (var i = 0; i < len; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} - -/** - * This is an abstraction over the Blob/Buffer data structure. - * We need this because it behaves different in different JavaScript runtimes. - * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support - * the Blob data structure which is also supported by the browsers. - */ -export var blobBufferUtil = { - /** - * depending if we are on node or browser, - * we have to use Buffer(node) or Blob(browser) - */ - createBlobBuffer: function createBlobBuffer(data, type) { - var blobBuffer = new Blob([data], { - type: type - }); - return blobBuffer; - }, - /** - * depending if we are on node or browser, - * we have to use Buffer(node) or Blob(browser) - */ - createBlobBufferFromBase64: function createBlobBufferFromBase64(base64String, type) { - try { - return Promise.resolve(fetch("data:" + type + ";base64," + base64String)).then(function (base64Response) { - return Promise.resolve(base64Response.blob()); - }); - } catch (e) { - return Promise.reject(e); - } - }, - isBlobBuffer: function isBlobBuffer(data) { - if (data instanceof Blob || typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) { - return true; - } else { - return false; - } - }, - toString: function toString(blobBuffer) { - /** - * in the electron-renderer we have a typed array insteaf of a blob - * so we have to transform it. - * @link https://github.com/pubkey/rxdb/issues/1371 - */ - var blobBufferType = Object.prototype.toString.call(blobBuffer); - if (blobBufferType === '[object Uint8Array]') { - blobBuffer = new Blob([blobBuffer]); - } - if (typeof blobBuffer === 'string') { - return Promise.resolve(blobBuffer); - } - return blobBuffer.text(); - }, - toBase64String: function toBase64String(blobBuffer) { - try { - if (typeof blobBuffer === 'string') { - return Promise.resolve(blobBuffer); - } - - /** - * in the electron-renderer we have a typed array insteaf of a blob - * so we have to transform it. - * @link https://github.com/pubkey/rxdb/issues/1371 - */ - var blobBufferType = Object.prototype.toString.call(blobBuffer); - if (blobBufferType === '[object Uint8Array]') { - blobBuffer = new Blob([blobBuffer]); - } - return Promise.resolve(fetch(URL.createObjectURL(blobBuffer)).then(function (res) { - return res.arrayBuffer(); - })).then(arrayBufferToBase64); - } catch (e) { - return Promise.reject(e); - } - }, - size: function size(blobBuffer) { - return blobBuffer.size; - } -}; - -/** - * Using shareReplay() without settings will not unsubscribe - * if there are no more subscribers. - * So we use these defaults. - * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95 - */ -export var RXJS_SHARE_REPLAY_DEFAULTS = { - bufferSize: 1, - refCount: true -}; - -/** - * We use 1 as minimum so that the value is never falsy. - * This const is used in several places because querying - * with a value lower then the minimum could give false results. - */ -export var RX_META_LWT_MINIMUM = 1; -export function getDefaultRxDocumentMeta() { - return { - /** - * Set this to 1 to not waste performance - * while calling new Date().. - * The storage wrappers will anyway update - * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage() - */ - lwt: RX_META_LWT_MINIMUM - }; -} - -/** - * Returns a revision that is not valid. - * Use this to have correct typings - * while the storage wrapper anyway will overwrite the revision. - */ -export function getDefaultRevision() { - /** - * Use a non-valid revision format, - * to ensure that the RxStorage will throw - * when the revision is not replaced downstream. - */ - return ''; -} -export function getSortDocumentsByLastWriteTimeComparator(primaryPath) { - return function (a, b) { - if (a._meta.lwt === b._meta.lwt) { - if (b[primaryPath] < a[primaryPath]) { - return 1; - } else { - return -1; - } - } else { - return a._meta.lwt - b._meta.lwt; - } - }; -} -export function sortDocumentsByLastWriteTime(primaryPath, docs) { - return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath)); -} - -/** - * To get specific nested path values from objects, - * RxDB normally uses the 'object-path' npm module. - * But when performance is really relevant, this is not fast enough. - * Instead we use a monad that can prepare some stuff up front - * and we can re-use the generated function. - */ - -export function objectPathMonad(objectPath) { - var split = objectPath.split('.'); - - /** - * Performance shortcut, - * if no nested path is used, - * directly return the field of the object. - */ - if (split.length === 1) { - return function (obj) { - return obj[objectPath]; - }; - } - return function (obj) { - var currentVal = obj; - var t = 0; - while (t < split.length) { - var subPath = split[t]; - currentVal = currentVal[subPath]; - if (typeof currentVal === 'undefined') { - return currentVal; - } - t++; - } - return currentVal; - }; -} -export function deepFreeze(o) { - Object.freeze(o); - Object.getOwnPropertyNames(o).forEach(function (prop) { - if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop])) { - deepFreeze(o[prop]); - } - }); - return o; -} -export function errorToPlainJson(err) { - var ret = { - name: err.name, - message: err.message, - stack: err.stack, - rxdb: err.rxdb - }; - return ret; -} -//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/dist/es/util.js.map b/dist/es/util.js.map deleted file mode 100644 index 152d9b8b12b..00000000000 --- a/dist/es/util.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"util.js","names":["pluginMissing","pluginKey","keyParts","split","pluginName","forEach","part","ucfirst","Error","fastUnsecureHash","inputString","doNotUseTextEncoder","hashValue","i","chr","len","encoded","TextEncoder","encode","j","length","push","charCodeAt","toString","defaultHashFunction","input","_lastNow","now","ret","Date","getTime","twoDecimals","parseFloat","toFixed","nextTick","Promise","res","setTimeout","promiseWait","ms","toPromise","maybePromise","then","resolve","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_NULL","PROMISE_RESOLVE_VOID","requestIdlePromise","timeout","window","promiseSeries","tasks","initial","reduce","current","next","requestIdleCallbackIfAvailable","fun","str","f","charAt","toUpperCase","substr","trimDots","slice","runXTimes","xTimes","fn","Array","fill","_v","idx","ensureNotFalsy","obj","ensureInteger","Number","isInteger","sortObject","noArraySort","isArray","sort","a","b","localeCompare","map","RegExp","out","Object","keys","key","stringifyFilter","value","randomCouchString","text","possible","Math","floor","random","RANDOM_STRING","lastOfArray","ar","shuffleArray","arr","batchArray","array","batchSize","batch","splice","removeOneFromArrayIfMatches","condition","done","adapterObject","adapter","adapterObj","db","undefined","deepClone","src","dest","clone","flatClone","assign","firstPropertyNameOfObject","firstPropertyValueOfObject","flattenObject","ob","toReturn","hasOwnProperty","flatObject","x","parseRevision","revision","height","parseInt","hash","getHeightOfRevision","createRevision","hashFunction","docData","previousDocData","previousRevision","_rev","previousRevisionHeigth","newRevisionHeight","docWithoutRev","_rev_tree","_meta","diggestString","JSON","stringify","revisionHash","areRxDocumentArraysEqual","primaryPath","ar1","ar2","row1","row2","overwriteGetterForCaching","getterName","defineProperty","get","isFolderPath","name","includes","getFromMapOrThrow","val","getFromObjectOrThrow","isMaybeReadonlyArray","arrayFilterNotEmpty","decode","b64EncodeUnicode","b64DecodeUnicode","arrayBufferToBase64","buffer","binary","bytes","Uint8Array","byteLength","String","fromCharCode","btoa","blobBufferUtil","createBlobBuffer","data","type","blobBuffer","Blob","createBlobBufferFromBase64","base64String","fetch","base64Response","blob","isBlobBuffer","Buffer","isBuffer","blobBufferType","prototype","call","toBase64String","URL","createObjectURL","arrayBuffer","size","RXJS_SHARE_REPLAY_DEFAULTS","bufferSize","refCount","RX_META_LWT_MINIMUM","getDefaultRxDocumentMeta","lwt","getDefaultRevision","getSortDocumentsByLastWriteTimeComparator","sortDocumentsByLastWriteTime","docs","objectPathMonad","objectPath","currentVal","t","subPath","deepFreeze","o","freeze","getOwnPropertyNames","prop","isFrozen","errorToPlainJson","err","message","stack","rxdb"],"sources":["../../src/util.ts"],"sourcesContent":["import type {\n BlobBuffer,\n DeepReadonlyObject,\n HashFunction,\n MaybeReadonly,\n PlainJsonError,\n RxDocumentData,\n RxDocumentMeta,\n RxDocumentWriteData,\n RxError,\n RxTypeError,\n StringKeys\n} from './types';\n\n/**\n * Returns an error that indicates that a plugin is missing\n * We do not throw a RxError because this should not be handled\n * programmatically but by using the correct import\n */\nexport function pluginMissing(\n pluginKey: string\n): Error {\n const keyParts = pluginKey.split('-');\n let pluginName = 'RxDB';\n keyParts.forEach(part => {\n pluginName += ucfirst(part);\n });\n pluginName += 'Plugin';\n return new Error(\n `You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { ${pluginName} } from 'rxdb/plugins/${pluginKey}';\n addRxPlugin(${pluginName});\n `\n );\n}\n\n/**\n * This is a very fast hash method\n * but it is not cryptographically secure.\n * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int).\n * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery\n * @return a string as hash-result\n */\nexport function fastUnsecureHash(\n inputString: string,\n // used to test the polyfill\n doNotUseTextEncoder?: boolean\n): string {\n let hashValue = 0,\n i, chr, len;\n\n /**\n * For better performance we first transform all\n * chars into their ascii numbers at once.\n *\n * This is what makes the murmurhash implementation such fast.\n * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4\n */\n let encoded: Uint8Array | number[];\n\n /**\n * All modern browsers support the TextEncoder\n * @link https://caniuse.com/textencoder\n * But to make RxDB work in other JavaScript runtimes,\n * like when using it in flutter or QuickJS, we need to\n * make it work even when there is no TextEncoder.\n */\n if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) {\n encoded = new TextEncoder().encode(inputString);\n } else {\n encoded = [];\n for (let j = 0; j < inputString.length; j++) {\n encoded.push(inputString.charCodeAt(j));\n }\n }\n\n for (i = 0, len = inputString.length; i < len; i++) {\n chr = encoded[i];\n hashValue = ((hashValue << 5) - hashValue) + chr;\n hashValue |= 0; // Convert to 32bit integer\n }\n if (hashValue < 0) {\n hashValue = hashValue * -1;\n }\n\n /**\n * To make the output smaller\n * but still have it to represent the same value,\n * we use the biggest radix of 36 instead of just\n * transforming it into a hex string.\n */\n return hashValue.toString(36);\n}\n\n\n/**\n * Default hash method used to create revision hashes\n * that do not have to be cryptographically secure.\n * IMPORTANT: Changing the default hashing method\n * requires a BREAKING change!\n */\nexport function defaultHashFunction(input: string): string {\n return fastUnsecureHash(input);\n}\n\n/**\n * Returns the current unix time in milliseconds (with two decmials!)\n * Because the accuracy of getTime() in javascript is bad,\n * and we cannot rely on performance.now() on all platforms,\n * this method implements a way to never return the same value twice.\n * This ensures that when now() is called often, we do not loose the information\n * about which call came first and which came after.\n *\n * We had to move from having no decimals, to having two decimal\n * because it turned out that some storages are such fast that\n * calling this method too often would return 'the future'.\n */\nlet _lastNow: number = 0;\n/**\n * Returns the current time in milliseconds,\n * also ensures to not return the same value twice.\n */\nexport function now(): number {\n let ret = new Date().getTime();\n ret = ret + 0.01;\n if (ret <= _lastNow) {\n ret = _lastNow + 0.01;\n }\n\n /**\n * Strip the returned number to max two decimals.\n * In theory we would not need this but\n * in practice JavaScript has no such good number precision\n * so rounding errors could add another decimal place.\n */\n const twoDecimals = parseFloat(ret.toFixed(2));\n\n _lastNow = twoDecimals;\n return twoDecimals;\n}\n\n/**\n * returns a promise that resolves on the next tick\n */\nexport function nextTick(): Promise {\n return new Promise(res => setTimeout(res, 0));\n}\n\nexport function promiseWait(ms: number = 0): Promise {\n return new Promise(res => setTimeout(res, ms));\n}\n\nexport function toPromise(maybePromise: Promise | T): Promise {\n if (maybePromise && typeof (maybePromise as any).then === 'function') {\n // is promise\n return maybePromise as any;\n } else {\n return Promise.resolve(maybePromise);\n }\n}\n\nexport const PROMISE_RESOLVE_TRUE: Promise = Promise.resolve(true);\nexport const PROMISE_RESOLVE_FALSE: Promise = Promise.resolve(false);\nexport const PROMISE_RESOLVE_NULL: Promise = Promise.resolve(null);\nexport const PROMISE_RESOLVE_VOID: Promise = Promise.resolve();\n\nexport function requestIdlePromise(timeout: number | null = null) {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) {\n return new Promise(\n res => (window as any)['requestIdleCallback'](res, {\n timeout\n })\n );\n } else {\n return promiseWait(0);\n }\n}\n\n\n/**\n * like Promise.all() but runs in series instead of parallel\n * @link https://github.com/egoist/promise.series/blob/master/index.js\n * @param tasks array with functions that return a promise\n */\nexport function promiseSeries(\n tasks: Function[],\n initial?: any\n): Promise {\n return tasks\n .reduce(\n (current, next) => (current as any).then(next),\n Promise.resolve(initial)\n );\n}\n\n/**\n * run the callback if requestIdleCallback available\n * do nothing if not\n * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback\n */\nexport function requestIdleCallbackIfAvailable(fun: Function): void {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) (window as any)['requestIdleCallback'](fun);\n}\n\n/**\n * uppercase first char\n */\nexport function ucfirst(str: string): string {\n str += '';\n const f = str.charAt(0)\n .toUpperCase();\n return f + str.substr(1);\n}\n\n/**\n * removes trailing and ending dots from the string\n */\nexport function trimDots(str: string): string {\n // start\n while (str.charAt(0) === '.')\n str = str.substr(1);\n\n // end\n while (str.slice(-1) === '.')\n str = str.slice(0, -1);\n\n return str;\n}\n\n\nexport function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null): T {\n if (!obj) {\n throw new Error('ensureNotFalsy() is falsy');\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n/**\n * deep-sort an object so its attributes are in lexical order.\n * Also sorts the arrays inside of the object if no-array-sort not set\n */\nexport function sortObject(obj: any, noArraySort = false): any {\n if (!obj) return obj; // do not sort null, false or undefined\n\n // array\n if (!noArraySort && Array.isArray(obj)) {\n return obj\n .sort((a, b) => {\n if (typeof a === 'string' && typeof b === 'string')\n return a.localeCompare(b);\n\n if (typeof a === 'object') return 1;\n else return -1;\n })\n .map(i => sortObject(i, noArraySort));\n }\n\n // object\n // array is also of type object\n if (typeof obj === 'object' && !Array.isArray(obj)) {\n if (obj instanceof RegExp) {\n return obj;\n }\n\n const out: any = {};\n Object.keys(obj)\n .sort((a, b) => a.localeCompare(b))\n .forEach(key => {\n out[key] = sortObject(obj[key], noArraySort);\n });\n return out;\n }\n\n // everything else\n return obj;\n}\n\n\n/**\n * used to JSON.stringify() objects that contain a regex\n * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs!\n */\nexport function stringifyFilter(key: string, value: any) {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n}\n\n/**\n * get a random string which can be used with couchdb\n * @link http://stackoverflow.com/a/1349426/3443137\n */\nexport function randomCouchString(length: number = 10): string {\n let text = '';\n const possible = 'abcdefghijklmnopqrstuvwxyz';\n\n for (let i = 0; i < length; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n\n return text;\n}\n\n/**\n * A random string that is never inside of any storage\n */\nexport const RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX';\n\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.sort(() => (Math.random() - 0.5));\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n\n/**\n * transforms the given adapter into a pouch-compatible object\n */\nexport function adapterObject(adapter: any): any {\n let adapterObj: any = {\n db: adapter\n };\n if (typeof adapter === 'string') {\n adapterObj = {\n adapter,\n db: undefined,\n };\n }\n return adapterObj;\n}\n\n\n/**\n * Deep clone a plain json object.\n * Does not work with recursive stuff\n * or non-plain-json.\n * IMPORANT: Performance of this is very important,\n * do not change it without running performance tests!\n *\n * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts\n */\nfunction deepClone(src: T | DeepReadonlyObject): T {\n if (!src) {\n return src;\n }\n if (src === null || typeof (src) !== 'object') {\n return src;\n }\n if (Array.isArray(src)) {\n const ret = new Array(src.length);\n let i = ret.length;\n while (i--) {\n ret[i] = deepClone(src[i]);\n }\n return ret as any;\n }\n const dest: any = {};\n // eslint-disable-next-line guard-for-in\n for (const key in src) {\n // TODO we should not be required to deep clone RegEx objects,\n // this must be fixed in RxDB.\n if (src[key] instanceof RegExp) {\n dest[key] = src[key];\n } else {\n dest[key] = deepClone(src[key]);\n }\n }\n return dest;\n}\nexport const clone = deepClone;\n\n/**\n * does a flat copy on the objects,\n * is about 3 times faster then using deepClone\n * @link https://jsperf.com/object-rest-spread-vs-clone/2\n */\nexport function flatClone(obj: T | DeepReadonlyObject): T {\n return Object.assign({}, obj) as any;\n}\n\n/**\n * @link https://stackoverflow.com/a/11509718/3443137\n */\nexport function firstPropertyNameOfObject(obj: any): string {\n return Object.keys(obj)[0];\n}\nexport function firstPropertyValueOfObject(obj: { [k: string]: T; }): T {\n const key = Object.keys(obj)[0];\n return obj[key];\n}\n\n/**\n * returns a flattened object\n * @link https://gist.github.com/penguinboy/762197\n */\nexport function flattenObject(ob: any) {\n const toReturn: any = {};\n\n for (const i in ob) {\n if (!ob.hasOwnProperty(i)) continue;\n\n if ((typeof ob[i]) === 'object') {\n const flatObject = flattenObject(ob[i]);\n for (const x in flatObject) {\n if (!flatObject.hasOwnProperty(x)) continue;\n\n toReturn[i + '.' + x] = flatObject[x];\n }\n } else {\n toReturn[i] = ob[i];\n }\n }\n return toReturn;\n}\n\n\nexport function parseRevision(revision: string): { height: number; hash: string; } {\n const split = revision.split('-');\n return {\n height: parseInt(split[0], 10),\n hash: split[1]\n };\n}\n\nexport function getHeightOfRevision(revision: string): number {\n return parseRevision(revision).height;\n}\n\n/**\n * Creates the next write revision for a given document.\n */\nexport function createRevision(\n hashFunction: HashFunction,\n docData: RxDocumentWriteData & {\n /**\n * Passing a revision is optional here,\n * because it is anyway not needed to calculate\n * the new revision.\n */\n _rev?: string;\n },\n previousDocData?: RxDocumentData\n): string {\n\n const previousRevision = previousDocData ? previousDocData._rev : null;\n const previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0;\n const newRevisionHeight = previousRevisionHeigth + 1;\n\n\n const docWithoutRev: any = Object.assign({}, docData, {\n _rev: undefined,\n _rev_tree: undefined,\n /**\n * All _meta properties MUST NOT be part of the\n * revision hash.\n * Plugins might temporarily store data in the _meta\n * field and strip it away when the document is replicated\n * or written to another storage.\n */\n _meta: undefined\n });\n\n /**\n * The revision height must be part of the hash\n * as the last parameter of the document data.\n * This is required to ensure we never ever create\n * two different document states that have the same revision\n * hash. Even writing the exact same document data\n * must have to result in a different hash so that\n * the replication can known if the state just looks equal\n * or if it is really exactly the equal state in data and time.\n */\n delete docWithoutRev._rev;\n docWithoutRev._rev = previousDocData ? newRevisionHeight : 1;\n\n const diggestString = JSON.stringify(docWithoutRev);\n\n const revisionHash = hashFunction(diggestString);\n return newRevisionHeight + '-' + revisionHash;\n}\n\n\n/**\n * Faster way to check the equalness of document lists\n * compared to doing a deep-equal.\n * Here we only check the ids and revisions.\n */\nexport function areRxDocumentArraysEqual(\n primaryPath: StringKeys>,\n ar1: RxDocumentData[],\n ar2: RxDocumentData[]\n): boolean {\n if (ar1.length !== ar2.length) {\n return false;\n }\n let i = 0;\n const len = ar1.length;\n while (i < len) {\n const row1 = ar1[i];\n const row2 = ar2[i];\n i++;\n\n if (\n row1._rev !== row2._rev ||\n row1[primaryPath] !== row2[primaryPath]\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * overwrites the getter with the actual value\n * Mostly used for caching stuff on the first run\n */\nexport function overwriteGetterForCaching(\n obj: any,\n getterName: string,\n value: ValueType\n): ValueType {\n Object.defineProperty(obj, getterName, {\n get: function () {\n return value;\n }\n });\n return value;\n}\n\n/**\n * returns true if the given name is likely a folder path\n */\nexport function isFolderPath(name: string) {\n // do not check, if foldername is given\n if (\n name.includes('/') || // unix\n name.includes('\\\\') // windows\n ) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function getFromMapOrThrow(map: Map | WeakMap, key: K): V {\n const val = map.get(key);\n if (typeof val === 'undefined') {\n throw new Error('missing value from map ' + key);\n }\n return val;\n}\n\nexport function getFromObjectOrThrow(\n obj: { [k: string]: V; },\n key: string\n): V {\n const val = obj[key];\n if (!val) {\n throw new Error('missing value from object ' + key);\n }\n return val;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n\n\n/**\n * NO! We cannot just use btoa() and atob()\n * because they do not work correctly with binary data.\n * @link https://stackoverflow.com/q/30106476/3443137\n */\nimport { encode, decode } from 'js-base64';\n\n/**\n * atob() and btoa() do not work well with non ascii chars,\n * so we have to use these helper methods instead.\n * @link https://stackoverflow.com/a/30106551/3443137\n */\n// Encoding UTF8 -> base64\nexport function b64EncodeUnicode(str: string) {\n return encode(str);\n}\n\n// Decoding base64 -> UTF8\nexport function b64DecodeUnicode(str: string) {\n return decode(str);\n}\n\n/**\n * @link https://stackoverflow.com/a/9458996/3443137\n */\nexport function arrayBufferToBase64(buffer: ArrayBuffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n\n/**\n * This is an abstraction over the Blob/Buffer data structure.\n * We need this because it behaves different in different JavaScript runtimes.\n * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support\n * the Blob data structure which is also supported by the browsers.\n */\nexport const blobBufferUtil = {\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n createBlobBuffer(\n data: string,\n type: string\n ): BlobBuffer {\n const blobBuffer = new Blob([data], {\n type\n });\n return blobBuffer;\n },\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n async createBlobBufferFromBase64(\n base64String: string,\n type: string\n ): Promise {\n const base64Response = await fetch(`data:${type};base64,${base64String}`);\n const blob = await base64Response.blob();\n return blob;\n\n },\n isBlobBuffer(data: any): boolean {\n if (data instanceof Blob || (typeof Buffer !== 'undefined' && Buffer.isBuffer(data))) {\n return true;\n } else {\n return false;\n }\n },\n toString(blobBuffer: BlobBuffer | string): Promise {\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n if (typeof blobBuffer === 'string') {\n return Promise.resolve(blobBuffer);\n }\n\n return (blobBuffer as Blob).text();\n },\n async toBase64String(blobBuffer: BlobBuffer | string): Promise {\n if (typeof blobBuffer === 'string') {\n return blobBuffer;\n }\n\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n\n const arrayBuffer = await fetch(URL.createObjectURL(blobBuffer as Blob)).then(res => res.arrayBuffer());\n return arrayBufferToBase64(arrayBuffer);\n },\n size(blobBuffer: BlobBuffer): number {\n return (blobBuffer as Blob).size;\n }\n};\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n\n/**\n * We use 1 as minimum so that the value is never falsy.\n * This const is used in several places because querying\n * with a value lower then the minimum could give false results.\n */\nexport const RX_META_LWT_MINIMUM = 1;\n\nexport function getDefaultRxDocumentMeta(): RxDocumentMeta {\n return {\n /**\n * Set this to 1 to not waste performance\n * while calling new Date()..\n * The storage wrappers will anyway update\n * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage()\n */\n lwt: RX_META_LWT_MINIMUM\n };\n}\n\n/**\n * Returns a revision that is not valid.\n * Use this to have correct typings\n * while the storage wrapper anyway will overwrite the revision.\n */\nexport function getDefaultRevision(): string {\n /**\n * Use a non-valid revision format,\n * to ensure that the RxStorage will throw\n * when the revision is not replaced downstream.\n */\n return '';\n}\n\n\nexport function getSortDocumentsByLastWriteTimeComparator(primaryPath: string) {\n return (a: RxDocumentData, b: RxDocumentData) => {\n if (a._meta.lwt === b._meta.lwt) {\n if ((b as any)[primaryPath] < (a as any)[primaryPath]) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return a._meta.lwt - b._meta.lwt;\n }\n };\n}\nexport function sortDocumentsByLastWriteTime(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData[] {\n return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath));\n}\n\n\n\n/**\n * To get specific nested path values from objects,\n * RxDB normally uses the 'object-path' npm module.\n * But when performance is really relevant, this is not fast enough.\n * Instead we use a monad that can prepare some stuff up front\n * and we can re-use the generated function.\n */\nexport type ObjectPathMonadFunction = (obj: T) => R;\nexport function objectPathMonad(objectPath: string): ObjectPathMonadFunction {\n const split = objectPath.split('.');\n\n /**\n * Performance shortcut,\n * if no nested path is used,\n * directly return the field of the object.\n */\n if (split.length === 1) {\n return (obj: T) => (obj as any)[objectPath];\n }\n\n\n return (obj: T) => {\n let currentVal: any = obj;\n let t = 0;\n while (t < split.length) {\n const subPath = split[t];\n currentVal = currentVal[subPath];\n if (typeof currentVal === 'undefined') {\n return currentVal;\n }\n t++;\n }\n return currentVal;\n };\n}\n\n\nexport function deepFreeze(o: T): T {\n Object.freeze(o);\n Object.getOwnPropertyNames(o).forEach(function (prop) {\n if (\n (o as any).hasOwnProperty(prop)\n &&\n (o as any)[prop] !== null\n &&\n (\n typeof (o as any)[prop] === 'object'\n ||\n typeof (o as any)[prop] === 'function'\n )\n &&\n !Object.isFrozen((o as any)[prop])\n ) {\n deepFreeze((o as any)[prop]);\n }\n });\n return o;\n}\n\n\n\nexport function errorToPlainJson(err: Error | TypeError | RxError | RxTypeError): PlainJsonError {\n const ret: PlainJsonError = {\n name: err.name,\n message: err.message,\n stack: err.stack,\n rxdb: (err as any).rxdb\n };\n return ret;\n}\n"],"mappings":"AAcA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,aAAa,CACzBC,SAAiB,EACZ;EACL,IAAMC,QAAQ,GAAGD,SAAS,CAACE,KAAK,CAAC,GAAG,CAAC;EACrC,IAAIC,UAAU,GAAG,MAAM;EACvBF,QAAQ,CAACG,OAAO,CAAC,UAAAC,IAAI,EAAI;IACrBF,UAAU,IAAIG,OAAO,CAACD,IAAI,CAAC;EAC/B,CAAC,CAAC;EACFF,UAAU,IAAI,QAAQ;EACtB,OAAO,IAAII,KAAK,iLAGGJ,UAAU,8BAAyBH,SAAS,oCACzCG,UAAU,kBAE/B;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASK,gBAAgB,CAC5BC,WAAmB;AACnB;AACAC,mBAA6B,EACvB;EACN,IAAIC,S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IAE9BH,CAAC,CAASG,IAAI,CAAC,KAAK,IAAI,KAGrB,OAAQH,CAAC,CAASG,IAAI,CAAC,KAAK,QAAQ,IAEpC,OAAQH,CAAC,CAASG,IAAI,CAAC,KAAK,UAAU,CACzC,IAED,CAACvI,MAAM,CAACwI,QAAQ,CAAEJ,CAAC,CAASG,IAAI,CAAC,CAAC,EACpC;MACEJ,UAAU,CAAEC,CAAC,CAASG,IAAI,CAAC,CAAC;IAChC;EACJ,CAAC,CAAC;EACF,OAAOH,CAAC;AACZ;AAIA,OAAO,SAASK,gBAAgB,CAACC,GAA8C,EAAkB;EAC7F,IAAMtM,GAAmB,GAAG;IACxBuI,IAAI,EAAE+D,GAAG,CAAC/D,IAAI;IACdgE,OAAO,EAAED,GAAG,CAACC,OAAO;IACpBC,KAAK,EAAEF,GAAG,CAACE,KAAK;IAChBC,IAAI,EAAGH,GAAG,CAASG;EACvB,CAAC;EACD,OAAOzM,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/browserify.index.js b/dist/lib/browserify.index.js index 7f400e45d6c..25b9f20bcb3 100644 --- a/dist/lib/browserify.index.js +++ b/dist/lib/browserify.index.js @@ -2,7 +2,6 @@ require("@babel/polyfill"); var RxDB = _interopRequireWildcard(require("./index.js")); -var RxDbPouchPlugin = _interopRequireWildcard(require("./plugins/pouchdb/index.js")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** @@ -11,7 +10,5 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && * and used via window.RxDB */ -RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb')); -RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http')); window['RxDB'] = RxDB; //# sourceMappingURL=browserify.index.js.map \ No newline at end of file diff --git a/dist/lib/browserify.index.js.map b/dist/lib/browserify.index.js.map index c0b1c5e4746..acdd0437eda 100644 --- a/dist/lib/browserify.index.js.map +++ b/dist/lib/browserify.index.js.map @@ -1 +1 @@ -{"version":3,"file":"browserify.index.js","names":["RxDbPouchPlugin","addPouchPlugin","require","window","RxDB"],"sources":["../../src/browserify.index.ts"],"sourcesContent":["/**\n * this is the index for a browserify-build\n * which produces a single file that can be embedded into the html\n * and used via window.RxDB\n */\n\nimport '@babel/polyfill';\nimport * as RxDB from './index.js';\nimport * as RxDbPouchPlugin from './plugins/pouchdb/index.js';\n\nRxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb'));\nRxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http'));\n\n(window as any)['RxDB'] = RxDB;\n"],"mappings":";;AAMA;AACA;AACA;AAA8D;AAAA;AAR9D;AACA;AACA;AACA;AACA;;AAMAA,eAAe,CAACC,cAAc,CAACC,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAC9DF,eAAe,CAACC,cAAc,CAACC,OAAO,CAAC,sBAAsB,CAAC,CAAC;AAE9DC,MAAM,CAAS,MAAM,CAAC,GAAGC,IAAI"} \ No newline at end of file +{"version":3,"file":"browserify.index.js","names":["window","RxDB"],"sources":["../../src/browserify.index.ts"],"sourcesContent":["/**\n * this is the index for a browserify-build\n * which produces a single file that can be embedded into the html\n * and used via window.RxDB\n */\n\nimport '@babel/polyfill';\nimport * as RxDB from './index.js';\n\n(window as any)['RxDB'] = RxDB;\n"],"mappings":";;AAMA;AACA;AAAmC;AAAA;AAPnC;AACA;AACA;AACA;AACA;;AAKCA,MAAM,CAAS,MAAM,CAAC,GAAGC,IAAI"} \ No newline at end of file diff --git a/dist/lib/custom-index.js b/dist/lib/custom-index.js index e1f249fe2db..93a0255f1c1 100644 --- a/dist/lib/custom-index.js +++ b/dist/lib/custom-index.js @@ -9,7 +9,7 @@ exports.getStartIndexStringFromLowerBound = getStartIndexStringFromLowerBound; exports.getStartIndexStringFromUpperBound = getStartIndexStringFromUpperBound; exports.getStringLengthOfIndexNumber = getStringLengthOfIndexNumber; var _rxSchemaHelper = require("./rx-schema-helper"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _queryPlanner = require("./query-planner"); /** * For some RxStorage implementations, @@ -50,7 +50,7 @@ function getIndexableStringMonad(schema, index) { schemaPart: schemaPart, parsedLengths: parsedLengths, hasComplexPath: fieldName.includes('.'), - getValueFn: (0, _util.objectPathMonad)(fieldName) + getValueFn: (0, _utils.objectPathMonad)(fieldName) }; }); var ret = function ret(docData) { @@ -68,7 +68,7 @@ function getIndexableStringMonad(schema, index) { var boolToStr = fieldValue ? '1' : '0'; str += boolToStr; } else { - var parsedLengths = (0, _util.ensureNotFalsy)(props.parsedLengths); + var parsedLengths = (0, _utils.ensureNotFalsy)(props.parsedLengths); if (!fieldValue) { fieldValue = 0; } @@ -113,7 +113,7 @@ function getStartIndexStringFromLowerBound(schema, index, lowerBound, inclusiveS var type = schemaPart.type; switch (type) { case 'string': - var maxLength = (0, _util.ensureNotFalsy)(schemaPart.maxLength); + var maxLength = (0, _utils.ensureNotFalsy)(schemaPart.maxLength); if (typeof bound === 'string') { str += bound.padEnd(maxLength, ' '); } else { @@ -153,7 +153,7 @@ function getStartIndexStringFromUpperBound(schema, index, upperBound, inclusiveE var type = schemaPart.type; switch (type) { case 'string': - var maxLength = (0, _util.ensureNotFalsy)(schemaPart.maxLength); + var maxLength = (0, _utils.ensureNotFalsy)(schemaPart.maxLength); if (typeof bound === 'string') { str += bound.padEnd(maxLength, inclusiveEnd ? _queryPlanner.INDEX_MAX : ' '); } else { diff --git a/dist/lib/custom-index.js.map b/dist/lib/custom-index.js.map index 6f7c4e52224..63e55edac5c 100644 --- a/dist/lib/custom-index.js.map +++ b/dist/lib/custom-index.js.map @@ -1 +1 @@ -{"version":3,"file":"custom-index.js","names":["getIndexableStringMonad","schema","index","fieldNameProperties","map","fieldName","schemaPart","getSchemaByObjectPath","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","objectPathMonad","ret","docData","str","forEach","props","fieldValue","padEnd","maxLength","boolToStr","ensureNotFalsy","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","length","multipleOfParts","split","decimals","roundedMinimum","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","INDEX_MAX","INDEX_MIN","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './util';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n\n\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n let fieldValue = props.getValueFn(docData);\n\n if (type === 'string') {\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n const parsedLengths = ensureNotFalsy(props.parsedLengths);\n if (!fieldValue) {\n fieldValue = 0;\n }\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n });\n return str;\n };\n return ret;\n}\n\ndeclare type ParsedLengths = {\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":";;;;;;;;;;AAMA;AAMA;AAKA;AAjBA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,uBAAuB,CACnCC,MAA+C,EAC/CC,KAAe,EAC+B;EAE9C;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAAC,UAAAC,SAAS,EAAI;IACzB,IAAMC,UAAU,GAAG,IAAAC,qCAAqB,EACpCN,MAAM,EACNI,SAAS,CACZ;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIE,KAAK,CAAC,iBAAiB,GAAGH,SAAS,CAAC;IAClD;IACA,IAAMI,IAAI,GAAGH,UAAU,CAACG,IAAI;IAC5B,IAAIC,aAAwC;IAC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;MACb,KAAK,SAAS;QACV,IAAMd,aAAa,GAAGC,4BAA4B,CAC9CL,UAAU,CACb;QACD,IAAI2C,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAKC,uBAAS,EAAE;UACvC,IAAME,QAAQ,GAAGI,YAAY,GAAG,GAAG,GAAG,GAAG;UACzCtC,GAAG,IAAIkC,QAAQ,CAACC,MAAM,CAAC3C,aAAa,CAACwB,WAAW,GAAGxB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHrB,GAAG,IAAIQ,oBAAoB,CACvBhB,aAAa,EACbuC,KAAK,CACR;QACL;QACA;MACJ;QACI,MAAM,IAAIzC,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOS,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"custom-index.js","names":["getIndexableStringMonad","schema","index","fieldNameProperties","map","fieldName","schemaPart","getSchemaByObjectPath","Error","type","parsedLengths","getStringLengthOfIndexNumber","hasComplexPath","includes","getValueFn","objectPathMonad","ret","docData","str","forEach","props","fieldValue","padEnd","maxLength","boolToStr","ensureNotFalsy","getNumberIndexString","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","length","multipleOfParts","split","decimals","roundedMinimum","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","inclusiveStart","idx","bound","INDEX_MAX","INDEX_MIN","fillChar","repeat","getStartIndexStringFromUpperBound","upperBound","inclusiveEnd"],"sources":["../../src/custom-index.ts"],"sourcesContent":["/**\n * For some RxStorage implementations,\n * we need to use our custom crafted indexes\n * so we can easily iterate over them. And sort plain arrays of document data.\n */\n\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils';\nimport { INDEX_MAX, INDEX_MIN } from './query-planner';\n\n\n/**\n * Crafts an indexable string that can be used\n * to check if a document would be sorted below or above\n * another documents, dependent on the index values.\n * @monad for better performance\n *\n * IMPORTANT: Performance is really important here\n * which is why we code so 'strange'.\n * Always run performance tests when you want to\n * change something in this method.\n */\nexport function getIndexableStringMonad(\n schema: RxJsonSchema>,\n index: string[]\n): (docData: RxDocumentData) => string {\n\n /**\n * Prepare all relevant information\n * outside of the returned function\n * to save performance when the returned\n * function is called many times.\n */\n const fieldNameProperties: {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValueFn: ObjectPathMonadFunction;\n }[] = index.map(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n if (!schemaPart) {\n throw new Error('not in schema: ' + fieldName);\n }\n const type = schemaPart.type;\n let parsedLengths: ParsedLengths | undefined;\n if (type === 'number' || type === 'integer') {\n parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n }\n\n return {\n fieldName,\n schemaPart,\n parsedLengths,\n hasComplexPath: fieldName.includes('.'),\n getValueFn: objectPathMonad(fieldName)\n };\n });\n\n\n const ret = function (docData: RxDocumentData): string {\n let str = '';\n fieldNameProperties.forEach(props => {\n const schemaPart = props.schemaPart;\n const type = schemaPart.type;\n\n let fieldValue = props.getValueFn(docData);\n\n if (type === 'string') {\n if (!fieldValue) {\n fieldValue = '';\n }\n str += fieldValue.padEnd(schemaPart.maxLength as number, ' ');\n } else if (type === 'boolean') {\n const boolToStr = fieldValue ? '1' : '0';\n str += boolToStr;\n } else {\n const parsedLengths = ensureNotFalsy(props.parsedLengths);\n if (!fieldValue) {\n fieldValue = 0;\n }\n str += getNumberIndexString(\n parsedLengths,\n fieldValue\n );\n }\n });\n return str;\n };\n return ret;\n}\n\ndeclare type ParsedLengths = {\n nonDecimals: number;\n decimals: number;\n roundedMinimum: number;\n};\nexport function getStringLengthOfIndexNumber(\n schemaPart: JsonSchema\n): ParsedLengths {\n const minimum = Math.floor(schemaPart.minimum as number);\n const maximum = Math.ceil(schemaPart.maximum as number);\n const multipleOf: number = schemaPart.multipleOf as number;\n\n const valueSpan = maximum - minimum;\n const nonDecimals = valueSpan.toString().length;\n\n const multipleOfParts = multipleOf.toString().split('.');\n let decimals = 0;\n if (multipleOfParts.length > 1) {\n decimals = multipleOfParts[1].length;\n }\n return {\n nonDecimals,\n decimals,\n roundedMinimum: minimum\n };\n}\n\n\nexport function getNumberIndexString(\n parsedLengths: ParsedLengths,\n fieldValue: number\n): string {\n let str: string = '';\n const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n str += nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '0';\n\n str += decimalValueAsString.padEnd(parsedLengths.decimals, '0');\n return str;\n}\n\nexport function getStartIndexStringFromLowerBound(\n schema: RxJsonSchema,\n index: string[],\n lowerBound: (string | boolean | number | null | undefined)[],\n inclusiveStart: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = lowerBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, ' ');\n } else {\n // str += ''.padStart(maxLength, inclusiveStart ? ' ' : INDEX_MAX);\n str += ''.padEnd(maxLength, ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveStart ? '0' : INDEX_MAX;\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MIN) {\n const fillChar = inclusiveStart ? '0' : INDEX_MAX;\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n\n\nexport function getStartIndexStringFromUpperBound(\n schema: RxJsonSchema,\n index: string[],\n upperBound: (string | boolean | number | null | undefined)[],\n inclusiveEnd: boolean\n): string {\n let str = '';\n index.forEach((fieldName, idx) => {\n const schemaPart = getSchemaByObjectPath(\n schema,\n fieldName\n );\n const bound = upperBound[idx];\n const type = schemaPart.type;\n\n switch (type) {\n case 'string':\n const maxLength = ensureNotFalsy(schemaPart.maxLength);\n if (typeof bound === 'string') {\n str += (bound as string).padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n } else {\n str += ''.padEnd(maxLength, inclusiveEnd ? INDEX_MAX : ' ');\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += inclusiveEnd ? '0' : '1';\n } else {\n const boolToStr = bound ? '1' : '0';\n str += boolToStr;\n }\n break;\n case 'number':\n case 'integer':\n const parsedLengths = getStringLengthOfIndexNumber(\n schemaPart\n );\n if (bound === null || bound === INDEX_MAX) {\n const fillChar = inclusiveEnd ? '9' : '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else {\n str += getNumberIndexString(\n parsedLengths,\n bound as number\n );\n }\n break;\n default:\n throw new Error('unknown index type ' + type);\n }\n });\n return str;\n}\n"],"mappings":";;;;;;;;;;AAMA;AAMA;AAKA;AAjBA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,uBAAuB,CACnCC,MAA+C,EAC/CC,KAAe,EAC+B;EAE9C;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMC,mBAQH,GAAGD,KAAK,CAACE,GAAG,CAAC,UAAAC,SAAS,EAAI;IACzB,IAAMC,UAAU,GAAG,IAAAC,qCAAqB,EACpCN,MAAM,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B,GAAG,IAAIsC,YAAY,GAAG,GAAG,GAAG,GAAG;QACnC,CAAC,MAAM;UACH,IAAMhC,SAAS,GAAGyB,KAAK,GAAG,GAAG,GAAG,GAAG;UACnC/B,GAAG,IAAIM,SAAS;QACpB;QACA;MACJ,KAAK,QAAQ;MACb,KAAK,SAAS;QACV,IAAMd,aAAa,GAAGC,4BAA4B,CAC9CL,UAAU,CACb;QACD,IAAI2C,KAAK,KAAK,IAAI,IAAIA,KAAK,KAAKC,uBAAS,EAAE;UACvC,IAAME,QAAQ,GAAGI,YAAY,GAAG,GAAG,GAAG,GAAG;UACzCtC,GAAG,IAAIkC,QAAQ,CAACC,MAAM,CAAC3C,aAAa,CAACwB,WAAW,GAAGxB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHrB,GAAG,IAAIQ,oBAAoB,CACvBhB,aAAa,EACbuC,KAAK,CACR;QACL;QACA;MACJ;QACI,MAAM,IAAIzC,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IAAC;EAE1D,CAAC,CAAC;EACF,OAAOS,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/doc-cache.js b/dist/lib/doc-cache.js index 0cfeff8b063..3437ba51a49 100644 --- a/dist/lib/doc-cache.js +++ b/dist/lib/doc-cache.js @@ -3,23 +3,127 @@ Object.defineProperty(exports, "__esModule", { value: true }); -exports.DocCache = void 0; -var DocCache = /*#__PURE__*/function () { - function DocCache() { - this._map = new Map(); - this._map = new Map(); +exports.DocumentCache = void 0; +var _utils = require("./plugins/utils"); +var _overwritable = require("./overwritable"); +var _rxChangeEvent = require("./rx-change-event"); +/** + * The DocumentCache stores RxDocument objects + * by their primary key and revision. + * This is useful on client side applications where + * it is not known how much memory can be used, so + * we de-duplicate RxDocument states to save memory. + * To not fill up the memory with old document states, the DocumentCache + * only contains weak references to the RxDocuments themself. + * @link https://caniuse.com/?search=weakref + */ +var DocumentCache = /*#__PURE__*/function () { + /** + * Some JavaScript runtimes like QuickJS, + * so not have a FinalizationRegistry or WeakRef. + * Therefore we need a workaround which might waste a lot of memory, + * but at least works. + */ + + function DocumentCache(primaryPath, changes$, + /** + * A method that can create a RxDocument by the given document data. + */ + documentCreator) { + var _this = this; + this.cacheItemByDocId = new Map(); + this.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (docMeta) { + var docId = docMeta.docId; + var cacheItem = _this.cacheItemByDocId.get(docId); + if (cacheItem) { + cacheItem.documentByRevisionHeight["delete"](docMeta.revisionHeight); + if (cacheItem.documentByRevisionHeight.size === 0) { + /** + * No state of the document is cached anymore, + * so we can clean up. + */ + _this.cacheItemByDocId["delete"](docId); + } + } + }) : undefined; + this.primaryPath = primaryPath; + this.changes$ = changes$; + this.documentCreator = documentCreator; + changes$.subscribe(function (changeEvent) { + var docId = changeEvent.documentId; + var cacheItem = _this.cacheItemByDocId.get(docId); + if (cacheItem) { + var documentData = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + cacheItem.latestDoc = documentData; + } + }); } - var _proto = DocCache.prototype; - _proto.get = function get(id) { - return this._map.get(id); - }; - _proto.set = function set(id, obj) { - return this._map.set(id, obj); + + /** + * Get the RxDocument from the cache + * and create a new one if not exits before. + */ + var _proto = DocumentCache.prototype; + _proto.getCachedRxDocument = function getCachedRxDocument(docData) { + var docId = docData[this.primaryPath]; + var revisionHeight = (0, _utils.parseRevision)(docData._rev).height; + var cacheItem = (0, _utils.getFromMapOrFill)(this.cacheItemByDocId, docId, function () { + return getNewCacheItem(docData); + }); + var cachedRxDocumentWeakRef = cacheItem.documentByRevisionHeight.get(revisionHeight); + var cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined; + if (!cachedRxDocument) { + docData = _overwritable.overwritable.deepFreezeWhenDevMode(docData); + cachedRxDocument = this.documentCreator(docData); + cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument)); + if (this.registry) { + this.registry.register(cachedRxDocument, { + docId: docId, + revisionHeight: revisionHeight + }); + } + } + return cachedRxDocument; + } + + /** + * Throws if not exists + */; + _proto.getLatestDocumentData = function getLatestDocumentData(docId) { + var cacheItem = (0, _utils.getFromMapOrThrow)(this.cacheItemByDocId, docId); + return cacheItem.latestDoc; }; - _proto["delete"] = function _delete(id) { - return this._map["delete"](id); + _proto.getLatestDocumentDataIfExists = function getLatestDocumentDataIfExists(docId) { + var cacheItem = this.cacheItemByDocId.get(docId); + if (cacheItem) { + return cacheItem.latestDoc; + } }; - return DocCache; + return DocumentCache; }(); -exports.DocCache = DocCache; +exports.DocumentCache = DocumentCache; +function getNewCacheItem(docData) { + return { + documentByRevisionHeight: new Map(), + latestDoc: docData + }; +} + +/** + * Fallback for JavaScript runtimes that do not support WeakRef. + * The fallback will keep the items in cache forever, + * but at least works. + */ +var HAS_WEAK_REF = typeof WeakRef === 'function'; +function createWeakRefWithFallback(obj) { + if (HAS_WEAK_REF) { + return new WeakRef(obj); + } else { + return { + deref: function deref() { + return obj; + } + }; + } +} //# sourceMappingURL=doc-cache.js.map \ No newline at end of file diff --git a/dist/lib/doc-cache.js.map b/dist/lib/doc-cache.js.map index f01af96fb6d..d4e509bcfb1 100644 --- a/dist/lib/doc-cache.js.map +++ b/dist/lib/doc-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"doc-cache.js","names":["DocCache","_map","Map","get","id","set","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["export class DocCache {\n private _map: Map = new Map();\n constructor() {\n this._map = new Map();\n }\n\n get(id: string): T | undefined {\n return this._map.get(id);\n }\n set(id: string, obj: T) {\n return this._map.set(id, obj);\n }\n delete(id: string) {\n return this._map.delete(id);\n }\n}\n"],"mappings":";;;;;;IAAaA,QAAQ;EAEjB,oBAAc;IAAA,KADNC,IAAI,GAAmB,IAAIC,GAAG,EAAE;IAEpC,IAAI,CAACD,IAAI,GAAG,IAAIC,GAAG,EAAE;EACzB;EAAC;EAAA,OAEDC,GAAG,GAAH,aAAIC,EAAU,EAAiB;IAC3B,OAAO,IAAI,CAACH,IAAI,CAACE,GAAG,CAACC,EAAE,CAAC;EAC5B,CAAC;EAAA,OACDC,GAAG,GAAH,aAAID,EAAU,EAAEE,GAAM,EAAE;IACpB,OAAO,IAAI,CAACL,IAAI,CAACI,GAAG,CAACD,EAAE,EAAEE,GAAG,CAAC;EACjC,CAAC;EAAA,mBACD,iBAAOF,EAAU,EAAE;IACf,OAAO,IAAI,CAACH,IAAI,UAAO,CAACG,EAAE,CAAC;EAC/B,CAAC;EAAA;AAAA;AAAA"} \ No newline at end of file +{"version":3,"file":"doc-cache.js","names":["DocumentCache","primaryPath","changes$","documentCreator","cacheItemByDocId","Map","registry","FinalizationRegistry","docMeta","docId","cacheItem","get","documentByRevisionHeight","revisionHeight","size","undefined","subscribe","changeEvent","documentId","documentData","getDocumentDataOfRxChangeEvent","latestDoc","getCachedRxDocument","docData","parseRevision","_rev","height","getFromMapOrFill","getNewCacheItem","cachedRxDocumentWeakRef","cachedRxDocument","deref","overwritable","deepFreezeWhenDevMode","set","createWeakRefWithFallback","register","getLatestDocumentData","getFromMapOrThrow","getLatestDocumentDataIfExists","HAS_WEAK_REF","WeakRef","obj"],"sources":["../../src/doc-cache.ts"],"sourcesContent":["import type {\n RxChangeEvent,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n getFromMapOrFill,\n getFromMapOrThrow,\n parseRevision\n} from './plugins/utils';\nimport {\n overwritable\n} from './overwritable';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\nimport { Observable } from 'rxjs';\n\ndeclare type CacheItem = {\n /**\n * Store the different document states of time\n * based on their revision height.\n * We store WeakRefs so that we can later clean up\n * document states that are no longer needed.\n */\n documentByRevisionHeight: Map>>;\n\n /**\n * Store the latest known document state.\n * As long as any state of the document is in the cache,\n * we observe the changestream and update the latestDoc accordingly.\n * This makes it easier to optimize performance on other parts\n * because for each known document we can always get the current state\n * in the storage.\n * Also it makes it possible to call RxDocument.latest() in a non-async way\n * to retrieve the latest document state or to observe$ some property.\n *\n * To not prevent the whole cacheItem from being garbage collected,\n * we store only the document data here, but not the RxDocument.\n */\n latestDoc: RxDocumentData;\n};\n\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\ndeclare type FinalizationRegistryValue = {\n docId: string;\n revisionHeight: number;\n};\n\n/**\n * The DocumentCache stores RxDocument objects\n * by their primary key and revision.\n * This is useful on client side applications where\n * it is not known how much memory can be used, so\n * we de-duplicate RxDocument states to save memory.\n * To not fill up the memory with old document states, the DocumentCache\n * only contains weak references to the RxDocuments themself.\n * @link https://caniuse.com/?search=weakref\n */\nexport class DocumentCache {\n public cacheItemByDocId = new Map>();\n\n /**\n * Some JavaScript runtimes like QuickJS,\n * so not have a FinalizationRegistry or WeakRef.\n * Therefore we need a workaround which might waste a lot of memory,\n * but at least works.\n */\n private registry?: FinalizationRegistry = typeof FinalizationRegistry === 'function' ?\n new FinalizationRegistry(docMeta => {\n const docId = docMeta.docId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n cacheItem.documentByRevisionHeight.delete(docMeta.revisionHeight);\n if (cacheItem.documentByRevisionHeight.size === 0) {\n /**\n * No state of the document is cached anymore,\n * so we can clean up.\n */\n this.cacheItemByDocId.delete(docId);\n }\n }\n }) :\n undefined;\n\n constructor(\n public readonly primaryPath: string,\n public readonly changes$: Observable>,\n /**\n * A method that can create a RxDocument by the given document data.\n */\n public documentCreator: (docData: RxDocumentData) => RxDocument\n ) {\n changes$.subscribe(changeEvent => {\n const docId = changeEvent.documentId;\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n const documentData = getDocumentDataOfRxChangeEvent(changeEvent);\n cacheItem.latestDoc = documentData;\n }\n });\n }\n\n /**\n * Get the RxDocument from the cache\n * and create a new one if not exits before.\n */\n public getCachedRxDocument(docData: RxDocumentData): RxDocument {\n const docId: string = (docData as any)[this.primaryPath];\n const revisionHeight = parseRevision(docData._rev).height;\n const cacheItem = getFromMapOrFill>(\n this.cacheItemByDocId,\n docId,\n () => getNewCacheItem(docData)\n );\n\n const cachedRxDocumentWeakRef: WeakRef> | undefined = cacheItem.documentByRevisionHeight.get(revisionHeight);\n let cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined;\n if (!cachedRxDocument) {\n docData = overwritable.deepFreezeWhenDevMode(docData) as any;\n cachedRxDocument = this.documentCreator(docData) as RxDocument;\n cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument));\n\n if (this.registry) {\n this.registry.register(cachedRxDocument, {\n docId,\n revisionHeight\n });\n }\n }\n return cachedRxDocument;\n }\n\n /**\n * Throws if not exists\n */\n public getLatestDocumentData(docId: string): RxDocumentData {\n const cacheItem = getFromMapOrThrow(this.cacheItemByDocId, docId);\n return cacheItem.latestDoc;\n }\n\n public getLatestDocumentDataIfExists(docId: string): RxDocumentData | undefined {\n const cacheItem = this.cacheItemByDocId.get(docId);\n if (cacheItem) {\n return cacheItem.latestDoc;\n }\n }\n}\n\n\nfunction getNewCacheItem(docData: RxDocumentData): CacheItem {\n return {\n documentByRevisionHeight: new Map(),\n latestDoc: docData\n };\n}\n\n\n/**\n * Fallback for JavaScript runtimes that do not support WeakRef.\n * The fallback will keep the items in cache forever,\n * but at least works.\n */\nconst HAS_WEAK_REF = typeof WeakRef === 'function';\nfunction createWeakRefWithFallback(obj: T): WeakRef {\n if (HAS_WEAK_REF) {\n return new WeakRef(obj) as any;\n } else {\n return {\n deref() {\n return obj;\n }\n } as any;\n }\n}\n"],"mappings":";;;;;;AAKA;AAKA;AAGA;AAqCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATA,IAUaA,aAAa;EAGtB;AACJ;AACA;AACA;AACA;AACA;;EAkBI,uBACoBC,WAAmB,EACnBC,QAA8C;EAC9D;AACR;AACA;EACeC,eAA0F,EACnG;IAAA;IAAA,KAhC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AwB,EAAE,IAAIP,GAAG,EAAE;IACnCgB,SAAS,EAAEE;EACf,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA;AACA,IAAMiB,YAAY,GAAG,OAAOC,OAAO,KAAK,UAAU;AAClD,SAASN,yBAAyB,CAAmBO,GAAM,EAAc;EACrE,IAAIF,YAAY,EAAE;IACd,OAAO,IAAIC,OAAO,CAACC,GAAG,CAAC;EAC3B,CAAC,MAAM;IACH,OAAO;MACHX,KAAK,mBAAG;QACJ,OAAOW,GAAG;MACd;IACJ,CAAC;EACL;AACJ"} \ No newline at end of file diff --git a/dist/lib/event-reduce.js b/dist/lib/event-reduce.js index b00bd307e14..76edb58268a 100644 --- a/dist/lib/event-reduce.js +++ b/dist/lib/event-reduce.js @@ -9,7 +9,7 @@ exports.getQueryParams = getQueryParams; exports.getSortFieldsOfQuery = getSortFieldsOfQuery; var _eventReduceJs = require("event-reduce-js"); var _rxChangeEvent = require("./rx-change-event"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxQueryHelper = require("./rx-query-helper"); function getSortFieldsOfQuery(primaryKey, query) { if (!query.sort || query.sort.length === 0) { @@ -26,7 +26,7 @@ function getQueryParams(rxQuery) { if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) { var collection = rxQuery.collection; var preparedQuery = rxQuery.getPreparedQuery(); - var normalizedMangoQuery = (0, _rxQueryHelper.normalizeMangoQuery)(collection.storageInstance.schema, (0, _util.clone)(rxQuery.mangoQuery)); + var normalizedMangoQuery = (0, _rxQueryHelper.normalizeMangoQuery)(collection.storageInstance.schema, (0, _utils.clone)(rxQuery.mangoQuery)); var primaryKey = collection.schema.primaryPath; /** @@ -78,12 +78,12 @@ function calculateNewResults(rxQuery, rxChangeEvents) { }; } var queryParams = getQueryParams(rxQuery); - var previousResults = (0, _util.ensureNotFalsy)(rxQuery._result).docsData.slice(0); - var previousResultsMap = (0, _util.ensureNotFalsy)(rxQuery._result).docsDataMap; + var previousResults = (0, _utils.ensureNotFalsy)(rxQuery._result).docsData.slice(0); + var previousResultsMap = (0, _utils.ensureNotFalsy)(rxQuery._result).docsDataMap; var changed = false; var eventReduceEvents = rxChangeEvents.map(function (cE) { return (0, _rxChangeEvent.rxChangeEventToEventReduceChangeEvent)(cE); - }).filter(_util.arrayFilterNotEmpty); + }).filter(_utils.arrayFilterNotEmpty); var foundNonOptimizeable = eventReduceEvents.find(function (eventReduceEvent) { var stateResolveFunctionInput = { queryParams: queryParams, diff --git a/dist/lib/event-reduce.js.map b/dist/lib/event-reduce.js.map index 24a58fef258..0dcd6321a6e 100644 --- a/dist/lib/event-reduce.js.map +++ b/dist/lib/event-reduce.js.map @@ -1 +1 @@ -{"version":3,"file":"event-reduce.js","names":["getSortFieldsOfQuery","primaryKey","query","sort","length","map","part","Object","keys","RXQUERY_QUERY_PARAMS_CACHE","WeakMap","getQueryParams","rxQuery","has","collection","preparedQuery","getPreparedQuery","normalizedMangoQuery","normalizeMangoQuery","storageInstance","schema","clone","mangoQuery","primaryPath","sortComparator","database","storage","statics","getSortComparator","jsonSchema","useSortComparator","docA","docB","sortComparatorData","queryMatcher","getQueryMatcher","useQueryMatcher","doc","queryMatcherData","ret","skip","limit","sortFields","set","get","calculateNewResults","rxChangeEvents","eventReduce","runFullQueryAgain","queryParams","previousResults","ensureNotFalsy","_result","docsData","slice","previousResultsMap","docsDataMap","changed","eventReduceEvents","cE","rxChangeEventToEventReduceChangeEvent","filter","arrayFilterNotEmpty","foundNonOptimizeable","find","eventReduceEvent","stateResolveFunctionInput","changeEvent","keyDocumentMap","actionName","calculateActionName","runAction","newResults"],"sources":["../../src/event-reduce.ts"],"sourcesContent":["import {\n ActionName,\n calculateActionName,\n runAction,\n QueryParams,\n QueryMatcher,\n DeterministicSortComparator,\n StateResolveFunctionInput,\n ChangeEvent\n} from 'event-reduce-js';\nimport type {\n RxQuery,\n MangoQuery,\n RxChangeEvent,\n PreparedQuery,\n StringKeys,\n RxDocumentData\n} from './types';\nimport { rxChangeEventToEventReduceChangeEvent } from './rx-change-event';\nimport { arrayFilterNotEmpty, clone, ensureNotFalsy } from './util';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nexport type EventReduceResultNeg = {\n runFullQueryAgain: true;\n};\nexport type EventReduceResultPos = {\n runFullQueryAgain: false;\n changed: boolean;\n newResults: RxDocumentType[];\n};\nexport type EventReduceResult = EventReduceResultNeg | EventReduceResultPos;\n\n\nexport function getSortFieldsOfQuery(\n primaryKey: StringKeys>,\n query: MangoQuery\n): (string | StringKeys)[] {\n if (!query.sort || query.sort.length === 0) {\n return [primaryKey];\n } else {\n return query.sort.map(part => Object.keys(part)[0]);\n }\n}\n\n\n\nexport const RXQUERY_QUERY_PARAMS_CACHE: WeakMap> = new WeakMap();\nexport function getQueryParams(\n rxQuery: RxQuery\n): QueryParams {\n if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) {\n const collection = rxQuery.collection;\n const preparedQuery: PreparedQuery = rxQuery.getPreparedQuery();\n const normalizedMangoQuery = normalizeMangoQuery(\n collection.storageInstance.schema,\n clone(rxQuery.mangoQuery)\n );\n const primaryKey = collection.schema.primaryPath;\n\n /**\n * Create a custom sort comparator\n * that uses the hooks to ensure\n * we send for example compressed documents to be sorted by compressed queries.\n */\n const sortComparator = collection.database.storage.statics.getSortComparator(\n collection.schema.jsonSchema,\n preparedQuery\n );\n\n const useSortComparator: DeterministicSortComparator = (docA: RxDocType, docB: RxDocType) => {\n const sortComparatorData = {\n docA,\n docB,\n rxQuery\n };\n return sortComparator(sortComparatorData.docA, sortComparatorData.docB);\n };\n\n /**\n * Create a custom query matcher\n * that uses the hooks to ensure\n * we send for example compressed documents to match compressed queries.\n */\n const queryMatcher = collection.database.storage.statics.getQueryMatcher(\n collection.schema.jsonSchema,\n preparedQuery\n );\n const useQueryMatcher: QueryMatcher> = (doc: RxDocumentData) => {\n const queryMatcherData = {\n doc,\n rxQuery\n };\n return queryMatcher(queryMatcherData.doc);\n };\n\n const ret: QueryParams = {\n primaryKey: rxQuery.collection.schema.primaryPath as any,\n skip: normalizedMangoQuery.skip,\n limit: normalizedMangoQuery.limit,\n sortFields: getSortFieldsOfQuery(primaryKey, normalizedMangoQuery) as string[],\n sortComparator: useSortComparator,\n queryMatcher: useQueryMatcher\n };\n RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret);\n return ret;\n } else {\n return RXQUERY_QUERY_PARAMS_CACHE.get(rxQuery) as QueryParams;\n }\n}\n\n\nexport function calculateNewResults(\n rxQuery: RxQuery,\n rxChangeEvents: RxChangeEvent[]\n): EventReduceResult {\n if (!rxQuery.collection.database.eventReduce) {\n return {\n runFullQueryAgain: true\n };\n }\n const queryParams = getQueryParams(rxQuery);\n const previousResults: RxDocumentType[] = ensureNotFalsy(rxQuery._result).docsData.slice(0);\n const previousResultsMap: Map = ensureNotFalsy(rxQuery._result).docsDataMap;\n let changed: boolean = false;\n\n const eventReduceEvents: ChangeEvent[] = rxChangeEvents\n .map(cE => rxChangeEventToEventReduceChangeEvent(cE))\n .filter(arrayFilterNotEmpty);\n const foundNonOptimizeable = eventReduceEvents.find(eventReduceEvent => {\n const stateResolveFunctionInput: StateResolveFunctionInput = {\n queryParams,\n changeEvent: eventReduceEvent,\n previousResults,\n keyDocumentMap: previousResultsMap\n };\n\n const actionName: ActionName = calculateActionName(stateResolveFunctionInput);\n if (actionName === 'runFullQueryAgain') {\n return true;\n } else if (actionName !== 'doNothing') {\n changed = true;\n runAction(\n actionName,\n queryParams,\n eventReduceEvent,\n previousResults,\n previousResultsMap\n );\n return false;\n }\n });\n if (foundNonOptimizeable) {\n return {\n runFullQueryAgain: true,\n };\n } else {\n return {\n runFullQueryAgain: false,\n changed,\n newResults: previousResults\n };\n }\n}\n"],"mappings":";;;;;;;;;AAAA;AAkBA;AACA;AACA;AAaO,SAASA,oBAAoB,CAChCC,UAAiD,EACjDC,KAA4B,EACM;EAClC,IAAI,CAACA,KAAK,CAACC,IAAI,IAAID,KAAK,CAACC,IAAI,CAACC,MAA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AgD,GAAGZ,cAAc,CAClEzC,GAAG,CAAC,UAAAsD,EAAE;IAAA,OAAI,IAAAC,oDAAqC,EAACD,EAAE,CAAC;EAAA,EAAC,CACpDE,MAAM,CAACC,yBAAmB,CAAC;EAChC,IAAMC,oBAAoB,GAAGL,iBAAiB,CAACM,IAAI,CAAC,UAAAC,gBAAgB,EAAI;IACpE,IAAMC,yBAAoE,GAAG;MACzEjB,WAAW,EAAXA,WAAW;MACXkB,WAAW,EAAEF,gBAAgB;MAC7Bf,eAAe,EAAfA,eAAe;MACfkB,cAAc,EAAEb;IACpB,CAAC;IAED,IAAMc,UAAsB,GAAG,IAAAC,kCAAmB,EAACJ,yBAAyB,CAAC;IAC7E,IAAIG,UAAU,KAAK,mBAAmB,EAAE;MACpC,OAAO,IAAI;IACf,CAAC,MAAM,IAAIA,UAAU,KAAK,WAAW,EAAE;MACnCZ,OAAO,GAAG,IAAI;MACd,IAAAc,wBAAS,EACLF,UAAU,EACVpB,WAAW,EACXgB,gBAAgB,EAChBf,eAAe,EACfK,kBAAkB,CACrB;MACD,OAAO,KAAK;IAChB;EACJ,CAAC,CAAC;EACF,IAAIQ,oBAAoB,EAAE;IACtB,OAAO;MACHf,iBAAiB,EAAE;IACvB,CAAC;EACL,CAAC,MAAM;IACH,OAAO;MACHA,iBAAiB,EAAE,KAAK;MACxBS,OAAO,EAAPA,OAAO;MACPe,UAAU,EAAEtB;IAChB,CAAC;EACL;AACJ"} \ No newline at end of file +{"version":3,"file":"event-reduce.js","names":["getSortFieldsOfQuery","primaryKey","query","sort","length","map","part","Object","keys","RXQUERY_QUERY_PARAMS_CACHE","WeakMap","getQueryParams","rxQuery","has","collection","preparedQuery","getPreparedQuery","normalizedMangoQuery","normalizeMangoQuery","storageInstance","schema","clone","mangoQuery","primaryPath","sortComparator","database","storage","statics","getSortComparator","jsonSchema","useSortComparator","docA","docB","sortComparatorData","queryMatcher","getQueryMatcher","useQueryMatcher","doc","queryMatcherData","ret","skip","limit","sortFields","set","get","calculateNewResults","rxChangeEvents","eventReduce","runFullQueryAgain","queryParams","previousResults","ensureNotFalsy","_result","docsData","slice","previousResultsMap","docsDataMap","changed","eventReduceEvents","cE","rxChangeEventToEventReduceChangeEvent","filter","arrayFilterNotEmpty","foundNonOptimizeable","find","eventReduceEvent","stateResolveFunctionInput","changeEvent","keyDocumentMap","actionName","calculateActionName","runAction","newResults"],"sources":["../../src/event-reduce.ts"],"sourcesContent":["import {\n ActionName,\n calculateActionName,\n runAction,\n QueryParams,\n QueryMatcher,\n DeterministicSortComparator,\n StateResolveFunctionInput,\n ChangeEvent\n} from 'event-reduce-js';\nimport type {\n RxQuery,\n MangoQuery,\n RxChangeEvent,\n PreparedQuery,\n StringKeys,\n RxDocumentData\n} from './types';\nimport { rxChangeEventToEventReduceChangeEvent } from './rx-change-event';\nimport { arrayFilterNotEmpty, clone, ensureNotFalsy } from './plugins/utils';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nexport type EventReduceResultNeg = {\n runFullQueryAgain: true;\n};\nexport type EventReduceResultPos = {\n runFullQueryAgain: false;\n changed: boolean;\n newResults: RxDocumentType[];\n};\nexport type EventReduceResult = EventReduceResultNeg | EventReduceResultPos;\n\n\nexport function getSortFieldsOfQuery(\n primaryKey: StringKeys>,\n query: MangoQuery\n): (string | StringKeys)[] {\n if (!query.sort || query.sort.length === 0) {\n return [primaryKey];\n } else {\n return query.sort.map(part => Object.keys(part)[0]);\n }\n}\n\n\n\nexport const RXQUERY_QUERY_PARAMS_CACHE: WeakMap> = new WeakMap();\nexport function getQueryParams(\n rxQuery: RxQuery\n): QueryParams {\n if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) {\n const collection = rxQuery.collection;\n const preparedQuery: PreparedQuery = rxQuery.getPreparedQuery();\n const normalizedMangoQuery = normalizeMangoQuery(\n collection.storageInstance.schema,\n clone(rxQuery.mangoQuery)\n );\n const primaryKey = collection.schema.primaryPath;\n\n /**\n * Create a custom sort comparator\n * that uses the hooks to ensure\n * we send for example compressed documents to be sorted by compressed queries.\n */\n const sortComparator = collection.database.storage.statics.getSortComparator(\n collection.schema.jsonSchema,\n preparedQuery\n );\n\n const useSortComparator: DeterministicSortComparator = (docA: RxDocType, docB: RxDocType) => {\n const sortComparatorData = {\n docA,\n docB,\n rxQuery\n };\n return sortComparator(sortComparatorData.docA, sortComparatorData.docB);\n };\n\n /**\n * Create a custom query matcher\n * that uses the hooks to ensure\n * we send for example compressed documents to match compressed queries.\n */\n const queryMatcher = collection.database.storage.statics.getQueryMatcher(\n collection.schema.jsonSchema,\n preparedQuery\n );\n const useQueryMatcher: QueryMatcher> = (doc: RxDocumentData) => {\n const queryMatcherData = {\n doc,\n rxQuery\n };\n return queryMatcher(queryMatcherData.doc);\n };\n\n const ret: QueryParams = {\n primaryKey: rxQuery.collection.schema.primaryPath as any,\n skip: normalizedMangoQuery.skip,\n limit: normalizedMangoQuery.limit,\n sortFields: getSortFieldsOfQuery(primaryKey, normalizedMangoQuery) as string[],\n sortComparator: useSortComparator,\n queryMatcher: useQueryMatcher\n };\n RXQUERY_QUERY_PARAMS_CACHE.set(rxQuery, ret);\n return ret;\n } else {\n return RXQUERY_QUERY_PARAMS_CACHE.get(rxQuery) as QueryParams;\n }\n}\n\n\nexport function calculateNewResults(\n rxQuery: RxQuery,\n rxChangeEvents: RxChangeEvent[]\n): EventReduceResult {\n if (!rxQuery.collection.database.eventReduce) {\n return {\n runFullQueryAgain: true\n };\n }\n const queryParams = getQueryParams(rxQuery);\n const previousResults: RxDocumentType[] = ensureNotFalsy(rxQuery._result).docsData.slice(0);\n const previousResultsMap: Map = ensureNotFalsy(rxQuery._result).docsDataMap;\n let changed: boolean = false;\n\n const eventReduceEvents: ChangeEvent[] = rxChangeEvents\n .map(cE => rxChangeEventToEventReduceChangeEvent(cE))\n .filter(arrayFilterNotEmpty);\n const foundNonOptimizeable = eventReduceEvents.find(eventReduceEvent => {\n const stateResolveFunctionInput: StateResolveFunctionInput = {\n queryParams,\n changeEvent: eventReduceEvent,\n previousResults,\n keyDocumentMap: previousResultsMap\n };\n\n const actionName: ActionName = calculateActionName(stateResolveFunctionInput);\n if (actionName === 'runFullQueryAgain') {\n return true;\n } else if (actionName !== 'doNothing') {\n changed = true;\n runAction(\n actionName,\n queryParams,\n eventReduceEvent,\n previousResults,\n previousResultsMap\n );\n return false;\n }\n });\n if (foundNonOptimizeable) {\n return {\n runFullQueryAgain: true,\n };\n } else {\n return {\n runFullQueryAgain: false,\n changed,\n newResults: previousResults\n };\n }\n}\n"],"mappings":";;;;;;;;;AAAA;AAkBA;AACA;AACA;AAaO,SAASA,oBAAoB,CAChCC,UAAiD,EACjDC,KAA4B,EACM;EAClC,IAAI,CAACA,KAAK,CAACC,IAAI,IAAID,KAAK,CAACC,IAAI,CAACC,MAAM,KAAK,CAAC,EAAE;IACxC,OAAO,CAACH,UAAU,CAAC;EACvB,CAAC,MAAM;IACH,OAAOC,KAAK,CAACC,IAAI,CAACE,GAAG,CAAC,UAAAC,IAAI;MAAA,OAAIC,MAAM,CAACC,IAAI,CAACF,IAAI,CAAC,CAAC,CAAC,CAAC;IAAA,EAAC;EACvD;AACJ;AAIO,IAAMG,0BAA8D,GAAG,IAAIC,OAAO,EAAE;AAAC;AACrF,SAASC,cAAc,CAC1BC,OAA2B,EACL;EACtB,IAAI,CAACH,0BAA0B,CAACI,GAAG,CAACD,OAAO,CAAC,EAAE;IAC1C,IAAME,UAAU,GAAGF,OAAO,CAACE,UAAU;IACrC,IAAMC,aAAuC,GAAGH,OAAO,CAACI,gBAAgB,EAAE;IAC1E,IAAMC,oBAAoB,GAAG,IAAAC,kCAAmB,EAC5CJ,UAAU,CAACK,eAAe,CAACC,MAAM,EACjC,IAAAC,YAAK,EAACT,OAAO,CAACU,UAAU,CAAC,CAC5B;IACD,IAAMrB,UAAU,GAAGa,UAAU,CAACM,MAAM,CAACG,WAAW;;IAEhD;AACR;AACA;AACA;AACA;IACQ,IAAMC,cAAc,GAAGV,UAAU,CAACW,QAAQ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,iBAAiB,EAAE;IACvB,CAAC;EACL,CAAC,MAAM;IACH,OAAO;MACHA,iBAAiB,EAAE,KAAK;MACxBS,OAAO,EAAPA,OAAO;MACPe,UAAU,EAAEtB;IAChB,CAAC;EACL;AACJ"} \ No newline at end of file diff --git a/dist/lib/incremental-write.js b/dist/lib/incremental-write.js new file mode 100644 index 00000000000..2660dba00e8 --- /dev/null +++ b/dist/lib/incremental-write.js @@ -0,0 +1,275 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.IncrementalWriteQueue = void 0; +exports.findNewestOfDocumentStates = findNewestOfDocumentStates; +exports.modifierFromPublicToInternal = modifierFromPublicToInternal; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _rxError = require("./rx-error"); +var _utils = require("./plugins/utils"); +function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/** + * The incremental write queue + * batches up all incremental writes to a collection + * so that performance can be improved by: + * - Running only one write even when there are multiple modifications to the same document. + * - Run all writes ins a single bulkWrite() call even when there are writes to many documents. + */ +var IncrementalWriteQueue = /*#__PURE__*/function () { + function IncrementalWriteQueue(storageInstance, primaryPath, + // can be used to run hooks etc. + preWrite, postWrite) { + this.queueByDocId = new Map(); + this.isRunning = false; + this.storageInstance = storageInstance; + this.primaryPath = primaryPath; + this.preWrite = preWrite; + this.postWrite = postWrite; + } + var _proto = IncrementalWriteQueue.prototype; + _proto.addWrite = function addWrite(lastKnownDocumentState, modifier) { + var _this = this; + var docId = lastKnownDocumentState[this.primaryPath]; + var ar = (0, _utils.getFromMapOrFill)(this.queueByDocId, docId, function () { + return []; + }); + var ret = new Promise(function (resolve, reject) { + var item = { + lastKnownDocumentState: lastKnownDocumentState, + modifier: modifier, + resolve: resolve, + reject: reject + }; + (0, _utils.ensureNotFalsy)(ar).push(item); + _this.triggerRun(); + }); + return ret; + }; + _proto.triggerRun = /*#__PURE__*/function () { + var _triggerRun = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var _this2 = this; + var writeRows, itemsById, writeResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(this.isRunning === true || this.queueByDocId.size === 0)) { + _context2.next = 2; + break; + } + return _context2.abrupt("return"); + case 2: + this.isRunning = true; + writeRows = []; + /** + * 'take over' so that while the async functions runs, + * new incremental updates could be added from the outside. + */ + itemsById = this.queueByDocId; + this.queueByDocId = new Map(); + _context2.next = 8; + return Promise.all(Array.from(itemsById.entries()).map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_ref) { + var _docId, items, oldData, newData, _iterator, _step, item; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _docId = _ref[0], items = _ref[1]; + oldData = findNewestOfDocumentStates(items.map(function (i) { + return i.lastKnownDocumentState; + })); + newData = oldData; + _iterator = _createForOfIteratorHelperLoose(items); + case 4: + if ((_step = _iterator()).done) { + _context.next = 19; + break; + } + item = _step.value; + _context.prev = 6; + _context.next = 9; + return item.modifier( + /** + * We have to clone() each time because the modifier + * might throw while it already changed some properties + * of the document. + */ + (0, _utils.clone)(newData)); + case 9: + newData = _context.sent; + _context.next = 17; + break; + case 12: + _context.prev = 12; + _context.t0 = _context["catch"](6); + item.reject(_context.t0); + item.reject = function () {}; + item.resolve = function () {}; + case 17: + _context.next = 4; + break; + case 19: + _context.prev = 19; + _context.next = 22; + return _this2.preWrite(newData, oldData); + case 22: + _context.next = 28; + break; + case 24: + _context.prev = 24; + _context.t1 = _context["catch"](19); + /** + * If the before-hooks fail, + * we reject all of the writes because it is + * not possible to determine which one is to blame. + */ + items.forEach(function (item) { + return item.reject(_context.t1); + }); + return _context.abrupt("return"); + case 28: + writeRows.push({ + previous: oldData, + document: newData + }); + case 29: + case "end": + return _context.stop(); + } + }, _callee, null, [[6, 12], [19, 24]]); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); + case 8: + if (!(writeRows.length > 0)) { + _context2.next = 14; + break; + } + _context2.next = 11; + return this.storageInstance.bulkWrite(writeRows, 'incremental-write'); + case 11: + _context2.t0 = _context2.sent; + _context2.next = 15; + break; + case 14: + _context2.t0 = { + error: {}, + success: {} + }; + case 15: + writeResult = _context2.t0; + _context2.next = 18; + return Promise.all(Array.from(Object.entries(writeResult.success)).map(function (_ref3) { + var docId = _ref3[0], + result = _ref3[1]; + _this2.postWrite(result); + var items = (0, _utils.getFromMapOrThrow)(itemsById, docId); + items.forEach(function (item) { + return item.resolve(result); + }); + })); + case 18: + // process errors + Array.from(Object.entries(writeResult.error)).forEach(function (_ref4) { + var docId = _ref4[0], + error = _ref4[1]; + var items = (0, _utils.getFromMapOrThrow)(itemsById, docId); + var isConflict = (0, _rxError.isBulkWriteConflictError)(error); + if (isConflict) { + // had conflict -> retry afterwards + var ar = (0, _utils.getFromMapOrFill)(_this2.queueByDocId, docId, function () { + return []; + }); + /** + * Add the items back to this.queueByDocId + * by maintaining the original order. + */ + items.reverse().forEach(function (item) { + item.lastKnownDocumentState = (0, _utils.ensureNotFalsy)(isConflict.documentInDb); + (0, _utils.ensureNotFalsy)(ar).unshift(item); + }); + } else { + // other error -> must be thrown + var rxError = (0, _rxError.rxStorageWriteErrorToRxError)(error); + items.forEach(function (item) { + return item.reject(rxError); + }); + } + }); + this.isRunning = false; + + /** + * Always trigger another run + * because in between there might be new items + * been added to the queue. + */ + return _context2.abrupt("return", this.triggerRun()); + case 21: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function triggerRun() { + return _triggerRun.apply(this, arguments); + } + return triggerRun; + }(); + return IncrementalWriteQueue; +}(); +exports.IncrementalWriteQueue = IncrementalWriteQueue; +function modifierFromPublicToInternal(publicModifier) { + var ret = /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(docData) { + var withoutMeta, modified, reattachedMeta; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + withoutMeta = (0, _utils.stripMetaDataFromDocument)(docData); + withoutMeta._deleted = docData._deleted; + _context3.next = 4; + return publicModifier(withoutMeta); + case 4: + modified = _context3.sent; + reattachedMeta = Object.assign({}, modified, { + _meta: docData._meta, + _attachments: docData._attachments, + _rev: docData._rev, + _deleted: typeof modified._deleted !== 'undefined' ? modified._deleted : docData._deleted + }); + if (typeof reattachedMeta._deleted === 'undefined') { + reattachedMeta._deleted = false; + } + return _context3.abrupt("return", reattachedMeta); + case 8: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function ret(_x2) { + return _ref5.apply(this, arguments); + }; + }(); + return ret; +} +function findNewestOfDocumentStates(docs) { + var newest = docs[0]; + var newestRevisionHeight = (0, _utils.parseRevision)(newest._rev).height; + docs.forEach(function (doc) { + var height = (0, _utils.parseRevision)(doc._rev).height; + if (height > newestRevisionHeight) { + newest = doc; + newestRevisionHeight = height; + } + }); + return newest; +} +//# sourceMappingURL=incremental-write.js.map \ No newline at end of file diff --git a/dist/lib/incremental-write.js.map b/dist/lib/incremental-write.js.map new file mode 100644 index 00000000000..de0706cfb9a --- /dev/null +++ b/dist/lib/incremental-write.js.map @@ -0,0 +1 @@ +{"version":3,"file":"incremental-write.js","names":["IncrementalWriteQueue","storageInstance","primaryPath","preWrite","postWrite","queueByDocId","Map","isRunning","addWrite","lastKnownDocumentState","modifier","docId","ar","getFromMapOrFill","ret","Promise","resolve","reject","item","ensureNotFalsy","push","triggerRun","size","writeRows","itemsById","all","Array","from","entries","map","_docId","items","oldData","findNewestOfDocumentStates","i","newData","clone","forEach","previous","document","length","bulkWrite","error","success","writeResult","Object","result","getFromMapOrThrow","isConflict","isBulkWriteConflictError","reverse","documentInDb","unshift","rxError","rxStorageWriteErrorToRxError","modifierFromPublicToInternal","publicModifier","docData","withoutMeta","stripMetaDataFromDocument","_deleted","modified","reattachedMeta","assign","_meta","_attachments","_rev","docs","newest","newestRevisionHeight","parseRevision","height","doc"],"sources":["../../src/incremental-write.ts"],"sourcesContent":["import {\n isBulkWriteConflictError,\n rxStorageWriteErrorToRxError\n} from './rx-error';\nimport type {\n ModifyFunction,\n BulkWriteRow,\n MaybePromise,\n RxDocumentData,\n RxDocumentWriteData,\n RxError,\n RxStorageBulkWriteResponse,\n RxStorageInstance,\n StringKeys,\n WithDeleted\n} from './types';\nimport {\n clone,\n ensureNotFalsy,\n getFromMapOrFill,\n getFromMapOrThrow,\n parseRevision,\n stripMetaDataFromDocument\n} from './plugins/utils';\n\n\n\nexport type IncrementalWriteModifier = (\n doc: RxDocumentData\n) => MaybePromise> | MaybePromise>;\n\n\ntype IncrementalWriteQueueItem = {\n lastKnownDocumentState: RxDocumentData;\n modifier: IncrementalWriteModifier;\n resolve: (d: RxDocumentData) => void;\n reject: (error: RxError) => void;\n};\n\n/**\n * The incremental write queue\n * batches up all incremental writes to a collection\n * so that performance can be improved by:\n * - Running only one write even when there are multiple modifications to the same document.\n * - Run all writes ins a single bulkWrite() call even when there are writes to many documents.\n */\nexport class IncrementalWriteQueue {\n public queueByDocId = new Map[]>();\n public isRunning: boolean = false;\n\n constructor(\n public readonly storageInstance: RxStorageInstance,\n public readonly primaryPath: StringKeys>,\n // can be used to run hooks etc.\n public readonly preWrite: (newData: RxDocumentData, oldData: RxDocumentData) => MaybePromise,\n public readonly postWrite: (docData: RxDocumentData) => void\n\n ) { }\n\n addWrite(\n lastKnownDocumentState: RxDocumentData,\n modifier: IncrementalWriteModifier\n ): Promise> {\n const docId: string = lastKnownDocumentState[this.primaryPath] as any;\n const ar = getFromMapOrFill(this.queueByDocId, docId, () => []);\n const ret = new Promise>((resolve, reject) => {\n const item: IncrementalWriteQueueItem = {\n lastKnownDocumentState,\n modifier,\n resolve,\n reject\n };\n ensureNotFalsy(ar).push(item);\n this.triggerRun();\n });\n return ret;\n }\n\n async triggerRun(): Promise {\n if (\n this.isRunning === true ||\n this.queueByDocId.size === 0\n ) {\n // already running\n return;\n }\n this.isRunning = true;\n const writeRows: BulkWriteRow[] = [];\n\n /**\n * 'take over' so that while the async functions runs,\n * new incremental updates could be added from the outside.\n */\n const itemsById = this.queueByDocId;\n this.queueByDocId = new Map();\n await Promise.all(\n Array.from(itemsById.entries())\n .map(async ([_docId, items]) => {\n const oldData = findNewestOfDocumentStates(\n items.map(i => i.lastKnownDocumentState)\n );\n let newData = oldData;\n for (const item of items) {\n try {\n newData = await item.modifier(\n /**\n * We have to clone() each time because the modifier\n * might throw while it already changed some properties\n * of the document.\n */\n clone(newData)\n ) as any;\n } catch (err: any) {\n item.reject(err);\n item.reject = () => { };\n item.resolve = () => { };\n }\n }\n\n try {\n await this.preWrite(newData, oldData);\n } catch (err: any) {\n /**\n * If the before-hooks fail,\n * we reject all of the writes because it is\n * not possible to determine which one is to blame.\n */\n items.forEach(item => item.reject(err));\n return;\n }\n writeRows.push({\n previous: oldData,\n document: newData\n });\n })\n );\n const writeResult: RxStorageBulkWriteResponse = writeRows.length > 0 ?\n await this.storageInstance.bulkWrite(writeRows, 'incremental-write') :\n { error: {}, success: {} };\n\n // process success\n await Promise.all(\n Array\n .from(Object.entries(writeResult.success))\n .map(([docId, result]) => {\n this.postWrite(result);\n const items = getFromMapOrThrow(itemsById, docId);\n items.forEach(item => item.resolve(result));\n })\n );\n\n // process errors\n Array\n .from(Object.entries(writeResult.error))\n .forEach(([docId, error]) => {\n const items = getFromMapOrThrow(itemsById, docId);\n const isConflict = isBulkWriteConflictError(error);\n if (isConflict) {\n // had conflict -> retry afterwards\n const ar = getFromMapOrFill(this.queueByDocId, docId, () => []);\n /**\n * Add the items back to this.queueByDocId\n * by maintaining the original order.\n */\n items\n .reverse()\n .forEach(item => {\n item.lastKnownDocumentState = ensureNotFalsy(isConflict.documentInDb);\n ensureNotFalsy(ar).unshift(item);\n });\n } else {\n // other error -> must be thrown\n const rxError = rxStorageWriteErrorToRxError(error);\n items.forEach(item => item.reject(rxError));\n }\n });\n this.isRunning = false;\n\n /**\n * Always trigger another run\n * because in between there might be new items\n * been added to the queue.\n */\n return this.triggerRun();\n }\n}\n\n\nexport function modifierFromPublicToInternal(\n publicModifier: ModifyFunction\n): IncrementalWriteModifier {\n const ret = async (docData: RxDocumentData) => {\n const withoutMeta: WithDeleted = stripMetaDataFromDocument(docData) as any;\n withoutMeta._deleted = docData._deleted;\n const modified = await publicModifier(withoutMeta);\n const reattachedMeta: RxDocumentData = Object.assign({}, modified, {\n _meta: docData._meta,\n _attachments: docData._attachments,\n _rev: docData._rev,\n _deleted: typeof (modified as WithDeleted)._deleted !== 'undefined' ?\n (modified as WithDeleted)._deleted :\n docData._deleted\n });\n if (typeof reattachedMeta._deleted === 'undefined') {\n reattachedMeta._deleted = false;\n }\n return reattachedMeta;\n };\n return ret;\n}\n\n\nexport function findNewestOfDocumentStates(\n docs: RxDocumentData[]\n): RxDocumentData {\n\n let newest = docs[0];\n let newestRevisionHeight = parseRevision(newest._rev).height;\n docs.forEach(doc => {\n const height = parseRevision(doc._rev).height;\n if (height > newestRevisionHeight) {\n newest = doc;\n newestRevisionHeight = height;\n }\n });\n return newest;\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAgBA;AAOyB;AAAA;AAAA;AAgBzB;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOaA,qBAAqB;EAI9B,+BACoBC,eAAuD,EACvDC,WAAkD;EAClE;EACgBC,QAAwG,EACxGC,SAAuD,EAEzE;IAAA,KAVKC,YAAY,GAAG,IAAIC,GAAG,EAAkD;IAAA,KACxEC,SAAS,GAAY,KAAK;IAAA,KAGbN,eAAuD,GAAvDA,eAAuD;IAAA,KACvDC,WAAkD,GAAlDA,WAAkD;IAAA,KAElDC,QAAwG,GAAxGA,QAAwG;IAAA,KACxGC,SAAuD,GAAvDA,SAAuD;EAEvE;EAAC;EAAA,OAELI,QAAQ,GAAR,kBACIC,sBAAiD,EACjDC,QAA6C,EACX;IAAA;IAClC,IAAMC,KAAa,GAAGF,sBAAsB,CAAC,IAAI,CAACP,WAAW,CAAQ;IACrE,IAAMU,EAAE,GAAG,IAAAC,uBAAgB,EAAC,IAAI,CAACR,YAAY,EAAEM,KAAK,EAAE;MAAA,OAAM,EAAE;IAAA,EAAC;IAC/D,IAAMG,GAAG,GAAG,IAAIC,OAAO,CAA4B,UAACC,OAAO,EAAEC,MAAM,EAAK;MACpE,IAAMC,IAA0C,GAAG;QAC/CT,sBAAsB,EAAtBA,sBAAsB;QACtBC,QAAQ,EAARA,QAAQ;QACRM,OAAO,EAAPA,OAAO;QACPC,MAAM,EAANA;MACJ,CAAC;MACD,IAAAE,qBAAc,EAACP,EAAE,CAAC,CAACQ,IAAI,CAACF,IAAI,CAAC;MAC7B,KAAI,CAACG,UAAU,EAAE;IACrB,CAAC,CAAC;IACF,OAAOP,GAAG;EACd,CA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AACE,WAAW,CAAC;UAAA;YAA5CG,QAAQ;YACRC,cAAyC,GAAGjB,MAAM,CAACkB,MAAM,CAAC,CAAC,CAAC,EAAEF,QAAQ,EAAE;cAC1EG,KAAK,EAAEP,OAAO,CAACO,KAAK;cACpBC,YAAY,EAAER,OAAO,CAACQ,YAAY;cAClCC,IAAI,EAAET,OAAO,CAACS,IAAI;cAClBN,QAAQ,EAAE,OAAQC,QAAQ,CAA4BD,QAAQ,KAAK,WAAW,GACzEC,QAAQ,CAA4BD,QAAQ,GAC7CH,OAAO,CAACG;YAChB,CAAC,CAAC;YACF,IAAI,OAAOE,cAAc,CAACF,QAAQ,KAAK,WAAW,EAAE;cAChDE,cAAc,CAACF,QAAQ,GAAG,KAAK;YACnC;YAAC,kCACME,cAAc;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACxB;IAAA,gBAhBKhD,GAAG;MAAA;IAAA;EAAA,GAgBR;EACD,OAAOA,GAAG;AACd;AAGO,SAASmB,0BAA0B,CACtCkC,IAAiC,EACR;EAEzB,IAAIC,MAAM,GAAGD,IAAI,CAAC,CAAC,CAAC;EACpB,IAAIE,oBAAoB,GAAG,IAAAC,oBAAa,EAACF,MAAM,CAACF,IAAI,CAAC,CAACK,MAAM;EAC5DJ,IAAI,CAAC9B,OAAO,CAAC,UAAAmC,GAAG,EAAI;IAChB,IAAMD,MAAM,GAAG,IAAAD,oBAAa,EAACE,GAAG,CAACN,IAAI,CAAC,CAACK,MAAM;IAC7C,IAAIA,MAAM,GAAGF,oBAAoB,EAAE;MAC/BD,MAAM,GAAGI,GAAG;MACZH,oBAAoB,GAAGE,MAAM;IACjC;EACJ,CAAC,CAAC;EACF,OAAOH,MAAM;AACjB"} \ No newline at end of file diff --git a/dist/lib/index.js b/dist/lib/index.js index 81759deda02..26b9af83f20 100644 --- a/dist/lib/index.js +++ b/dist/lib/index.js @@ -305,28 +305,28 @@ Object.keys(_pluginHelpers).forEach(function (key) { } }); }); -var _hooks = require("./hooks"); -var _queryCache = require("./query-cache"); -Object.keys(_queryCache).forEach(function (key) { +var _utils = require("./plugins/utils"); +Object.keys(_utils).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _queryCache[key]) return; + if (key in exports && exports[key] === _utils[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { - return _queryCache[key]; + return _utils[key]; } }); }); -var _util = require("./util"); -Object.keys(_util).forEach(function (key) { +var _hooks = require("./hooks"); +var _queryCache = require("./query-cache"); +Object.keys(_queryCache).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _util[key]) return; + if (key in exports && exports[key] === _queryCache[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { - return _util[key]; + return _queryCache[key]; } }); }); diff --git a/dist/lib/index.js.map b/dist/lib/index.js.map index 51a3b91d4c5..38aa2f5779a 100644 --- a/dist/lib/index.js.map +++ b/dist/lib/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * this is the main entry-point\n * for when the you call \"import from 'rxdb'\".\n */\n\nimport './types/modules/mocha.parallel.d';\nimport './types/modules/modifiyjs.d';\n\n\nexport { addRxPlugin } from './plugin';\n\nexport {\n createRxDatabase,\n removeRxDatabase,\n isRxDatabase,\n dbCount,\n isRxDatabaseFirstTimeInstantiated,\n ensureNoStartupErrors\n} from './rx-database';\n\nexport * from './rx-error';\n\nexport * from './rx-database-internal-store';\n\nexport {\n overwritable\n} from './overwritable';\n\nexport {\n isRxCollection,\n RxCollectionBase,\n createRxCollection // used in tests\n} from './rx-collection';\n\nexport {\n fillObjectDataBeforeInsert\n} from './rx-collection-helper';\n\nexport {\n isRxDocument\n} from './rx-document';\n\nexport {\n flattenEvents\n} from './rx-change-event';\n\nexport {\n getDocumentOrmPrototype,\n getDocumentPrototype\n} from './rx-document-prototype-merge';\n\nexport {\n isInstanceOf as isRxQuery\n} from './rx-query';\nexport * from './rx-query-helper';\n\nexport {\n isInstanceOf as isRxSchema,\n createRxSchema,\n RxSchema,\n getIndexes,\n getPreviousVersions,\n toTypedRxJsonSchema\n} from './rx-schema';\nexport * from './rx-schema-helper';\n\nexport * from './rx-storage-helper';\nexport * from './replication-protocol/index';\nexport * from './rx-storage-multiinstance';\nexport * from './custom-index';\nexport * from './query-planner';\nexport * from './plugin-helpers';\n\nexport {\n _clearHook // used in tests\n} from './hooks';\n\nexport * from './query-cache';\n\nexport * from './util';\n\n// TODO how to do 'export type * ..' ?\nexport type {\n JsonSchemaTypes,\n GraphQLSyncPullOptions,\n GraphQLSyncPushOptions,\n AtomicUpdateFunction,\n CollectionsOfDatabase,\n MangoQuery,\n MangoQueryNoLimit,\n JsonSchema,\n ExtractDocumentTypeFromTypedRxJsonSchema,\n KeyFunctionMap,\n MangoQuerySelector,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n MigrationState,\n NumberFunctionMap,\n DeepReadonlyObject,\n RxAttachment,\n RxAttachmentCreator,\n RxCollection,\n RxCacheReplacementPolicy,\n RxChangeEvent,\n RxChangeEventBulk,\n RxCollectionCreator,\n RxCollectionGenerated,\n RxCollectionHookCallback,\n RxCollectionHookCallbackNonAsync,\n RxCollectionHookNoInstance,\n RxCollectionHookNoInstanceCallback,\n RxDatabase,\n RxDatabaseCreator,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n RxDumpCollectionAsAny,\n RxDumpDatabase,\n Buffer,\n Debug,\n ExtractDTcol,\n RxDatabaseGenerated,\n RxDocumentBase,\n StringKeys,\n\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n\n // stuff from the RxStorage interface\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n WithDeleted,\n BulkWriteRow,\n BulkWriteRowById,\n RxAttachmentDataBase,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxStorage,\n RxStorageStatics,\n RxStorageBulkWriteError,\n RxStorageBulkWriteResponse,\n PreparedQuery,\n RxStorageQueryResult,\n RxStorageInstanceCreationParams,\n ChangeStreamOptions,\n EventBulk,\n ChangeStreamEvent,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n DexiePreparedQuery,\n RxStorageCountResult,\n\n // conflict handling\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxReplicationWriteToMasterRow,\n\n // stuff from the RxStorage replication\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta,\n DocumentsWithCheckpoint,\n RxReplicationPullStreamItem,\n ReplicationPullHandlerResult,\n\n // crdt\n UpdateQuery,\n CRDTEntry,\n CRDTOperation,\n CRDTDocumentField,\n\n // other stuff\n RxDumpCollectionBase,\n RxDumpDatabaseAny,\n RxDumpDatabaseBase,\n RxError,\n RxErrorItem,\n RxErrorParameters,\n RxGraphQLReplicationPushQueryBuilder,\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLPullResponseModifier,\n RxJsonSchema,\n RxLocalDocument,\n RxPlugin,\n RxQuery,\n RxQueryOP,\n RxQueryObject,\n RxQueryOptions,\n RxCouchDBReplicationState,\n RxTypeError,\n CouchDBServerOptions,\n SyncOptions,\n SyncOptionsGraphQL,\n MigrationStrategy,\n MigrationStrategies,\n FilledMangoQuery,\n OldRxCollection,\n WithAttachmentsData,\n RxTestStorage,\n ById,\n RxQueryPlan,\n PlainJsonError\n} from './types';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA;AACA;AAGA;AAEA;AASA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAIA;AAMA;AAIA;AAIA;AAIA;AAKA;AAGA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAQA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAIA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file +{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * this is the main entry-point\n * for when the you call \"import from 'rxdb'\".\n */\n\nimport './types/modules/mocha.parallel.d';\nimport './types/modules/modifiyjs.d';\n\n\nexport { addRxPlugin } from './plugin';\n\nexport {\n createRxDatabase,\n removeRxDatabase,\n isRxDatabase,\n dbCount,\n isRxDatabaseFirstTimeInstantiated,\n ensureNoStartupErrors\n} from './rx-database';\n\nexport * from './rx-error';\n\nexport * from './rx-database-internal-store';\n\nexport {\n overwritable\n} from './overwritable';\n\nexport {\n isRxCollection,\n RxCollectionBase,\n createRxCollection // used in tests\n} from './rx-collection';\n\nexport {\n fillObjectDataBeforeInsert\n} from './rx-collection-helper';\n\nexport {\n isRxDocument\n} from './rx-document';\n\nexport {\n flattenEvents\n} from './rx-change-event';\n\nexport {\n getDocumentOrmPrototype,\n getDocumentPrototype\n} from './rx-document-prototype-merge';\n\nexport {\n isInstanceOf as isRxQuery\n} from './rx-query';\nexport * from './rx-query-helper';\n\nexport {\n isInstanceOf as isRxSchema,\n createRxSchema,\n RxSchema,\n getIndexes,\n getPreviousVersions,\n toTypedRxJsonSchema\n} from './rx-schema';\nexport * from './rx-schema-helper';\n\nexport * from './rx-storage-helper';\nexport * from './replication-protocol/index';\nexport * from './rx-storage-multiinstance';\nexport * from './custom-index';\nexport * from './query-planner';\nexport * from './plugin-helpers';\nexport * from './plugins/utils';\n\nexport {\n _clearHook // used in tests\n} from './hooks';\n\nexport * from './query-cache';\n\n// TODO how to do 'export type * ..' ?\nexport type {\n JsonSchemaTypes,\n GraphQLSyncPullOptions,\n GraphQLSyncPushOptions,\n ModifyFunction,\n CollectionsOfDatabase,\n MangoQuery,\n MangoQueryNoLimit,\n JsonSchema,\n ExtractDocumentTypeFromTypedRxJsonSchema,\n KeyFunctionMap,\n MangoQuerySelector,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n MigrationState,\n NumberFunctionMap,\n DeepReadonlyObject,\n RxAttachment,\n RxAttachmentCreator,\n RxCollection,\n RxCacheReplacementPolicy,\n RxChangeEvent,\n RxChangeEventBulk,\n RxCollectionCreator,\n RxCollectionGenerated,\n RxCollectionHookCallback,\n RxCollectionHookCallbackNonAsync,\n RxCollectionHookNoInstance,\n RxCollectionHookNoInstanceCallback,\n RxDatabase,\n RxDatabaseCreator,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n RxDumpCollectionAsAny,\n RxDumpDatabase,\n Buffer,\n Debug,\n ExtractDTcol,\n RxDatabaseGenerated,\n RxDocumentBase,\n StringKeys,\n\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n\n // stuff from the RxStorage interface\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n WithDeleted,\n BulkWriteRow,\n BulkWriteRowById,\n RxAttachmentDataBase,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxStorage,\n RxStorageStatics,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n PreparedQuery,\n RxStorageQueryResult,\n RxStorageInstanceCreationParams,\n ChangeStreamOptions,\n EventBulk,\n ChangeStreamEvent,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n DexiePreparedQuery,\n RxStorageCountResult,\n\n // conflict handling\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxReplicationWriteToMasterRow,\n\n // stuff from the RxStorage replication\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta,\n DocumentsWithCheckpoint,\n RxReplicationPullStreamItem,\n ReplicationPullHandlerResult,\n\n // crdt\n UpdateQuery,\n CRDTEntry,\n CRDTOperation,\n CRDTDocumentField,\n\n // other stuff\n RxDumpCollectionBase,\n RxDumpDatabaseAny,\n RxDumpDatabaseBase,\n RxError,\n RxTypeError,\n RxValidationError,\n RxErrorParameters,\n RxGraphQLReplicationPushQueryBuilder,\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLPullResponseModifier,\n RxJsonSchema,\n RxLocalDocument,\n RxPlugin,\n RxQuery,\n RxQueryOP,\n MangoQueryOperators,\n SyncOptionsGraphQL,\n MigrationStrategy,\n MigrationStrategies,\n FilledMangoQuery,\n OldRxCollection,\n WithAttachmentsData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ib/plugin-helpers.js b/dist/lib/plugin-helpers.js index c59d3359800..6447d67cdac 100644 --- a/dist/lib/plugin-helpers.js +++ b/dist/lib/plugin-helpers.js @@ -1,12 +1,16 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapRxStorageInstance = wrapRxStorageInstance; exports.wrappedValidateStorageFactory = wrappedValidateStorageFactory; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _rxSchemaHelper = require("./rx-schema-helper"); +var _utils = require("./plugins/utils"); /** * cache the validators by the schema-hash * so we can reuse them when multiple collections have the same schema @@ -30,47 +34,83 @@ validatorKey) { if (!VALIDATOR_CACHE_BY_VALIDATOR_KEY.has(validatorKey)) { VALIDATOR_CACHE_BY_VALIDATOR_KEY.set(validatorKey, new Map()); } - var VALIDATOR_CACHE = (0, _util.getFromMapOrThrow)(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey); + var VALIDATOR_CACHE = (0, _utils.getFromMapOrThrow)(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey); function initValidator(schema) { - var hash = (0, _util.fastUnsecureHash)(JSON.stringify(schema)); + var hash = (0, _utils.fastUnsecureHash)(JSON.stringify(schema)); if (!VALIDATOR_CACHE.has(hash)) { var validator = getValidator(schema); VALIDATOR_CACHE.set(hash, validator); return validator; } - return (0, _util.getFromMapOrThrow)(VALIDATOR_CACHE, hash); + return (0, _utils.getFromMapOrThrow)(VALIDATOR_CACHE, hash); } return function (args) { return Object.assign({}, args.storage, { - createStorageInstance: function createStorageInstance(params) { - try { - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (instance) { - /** - * Lazy initialize the validator - * to save initial page load performance. - * Some libraries take really long to initialize the validator - * from the schema. - */ - var validatorCached; - (0, _util.requestIdleCallbackIfAvailable)(function () { - return validatorCached = initValidator(params.schema); - }); - var oldBulkWrite = instance.bulkWrite.bind(instance); - instance.bulkWrite = function (documentWrites, context) { - if (!validatorCached) { - validatorCached = initValidator(params.schema); - } - documentWrites.forEach(function (row) { - validatorCached(row.document); - }); - return oldBulkWrite(documentWrites, context); - }; - return instance; - }); - } catch (e) { - return Promise.reject(e); + createStorageInstance: function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var instance, primaryPath, validatorCached, oldBulkWrite; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return args.storage.createStorageInstance(params); + case 2: + instance = _context.sent; + primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(params.schema.primaryKey); + /** + * Lazy initialize the validator + * to save initial page load performance. + * Some libraries take really long to initialize the validator + * from the schema. + */ + (0, _utils.requestIdleCallbackIfAvailable)(function () { + return validatorCached = initValidator(params.schema); + }); + oldBulkWrite = instance.bulkWrite.bind(instance); + instance.bulkWrite = function (documentWrites, context) { + if (!validatorCached) { + validatorCached = initValidator(params.schema); + } + var errors = []; + var continueWrites = []; + documentWrites.forEach(function (row) { + var documentId = row.document[primaryPath]; + var validationErrors = validatorCached(row.document); + if (validationErrors.length > 0) { + errors.push({ + status: 422, + isError: true, + documentId: documentId, + writeRow: row, + validationErrors: validationErrors + }); + } else { + continueWrites.push(row); + } + }); + var writePromise = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ + error: {}, + success: {} + }); + return writePromise.then(function (writeResult) { + errors.forEach(function (validationError) { + writeResult.error[validationError.documentId] = validationError; + }); + return writeResult; + }); + }; + return _context.abrupt("return", instance); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); }; } @@ -80,246 +120,409 @@ validatorKey) { * data of that storage instance. */ function wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage) { - var errorFromStorage = function errorFromStorage(error) { - try { - var _temp4 = function _temp4() { - function _temp2() { - return Promise.resolve(fromStorage(ret.writeRow.document)).then(function (_fromStorage4) { - ret.writeRow.document = _fromStorage4; - return ret; - }); - } - var _temp = function () { - if (ret.writeRow.previous) { - return Promise.resolve(fromStorage(ret.writeRow.previous)).then(function (_fromStorage3) { - ret.writeRow.previous = _fromStorage3; - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }; - var ret = (0, _util.flatClone)(error); - ret.writeRow = (0, _util.flatClone)(ret.writeRow); - var _temp3 = function () { - if (ret.documentInDb) { - return Promise.resolve(fromStorage(ret.documentInDb)).then(function (_fromStorage2) { - ret.documentInDb = _fromStorage2; - }); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); - } - }; - var fromStorage = function fromStorage(docData) { - try { - if (!docData) { - return Promise.resolve(docData); - } - return Promise.resolve(modifyFromStorage(docData)); - } catch (e) { - return Promise.reject(e); - } - }; - var toStorage = function toStorage(docData) { - try { - if (!docData) { - return Promise.resolve(docData); - } - return Promise.resolve(modifyToStorage(docData)); - } catch (e) { - return Promise.reject(e); - } - }; var modifyAttachmentFromStorage = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function (v) { return v; }; - var oldBulkWrite = instance.bulkWrite.bind(instance); - instance.bulkWrite = function (documentWrites, context) { - try { - var useRows = []; - return Promise.resolve(Promise.all(documentWrites.map(function (row) { - try { - return Promise.resolve(Promise.all([row.previous ? toStorage(row.previous) : undefined, toStorage(row.document)])).then(function (_ref) { - var previous = _ref[0], - document = _ref[1]; - useRows.push({ - previous: previous, - document: document - }); - }); - } catch (e) { - return Promise.reject(e); + function toStorage(_x2) { + return _toStorage.apply(this, arguments); + } + function _toStorage() { + _toStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(docData) { + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + if (docData) { + _context11.next = 2; + break; + } + return _context11.abrupt("return", docData); + case 2: + _context11.next = 4; + return modifyToStorage(docData); + case 4: + return _context11.abrupt("return", _context11.sent); + case 5: + case "end": + return _context11.stop(); } - }))).then(function () { - return Promise.resolve(oldBulkWrite(useRows, context)).then(function (writeResult) { - var ret = { - success: {}, - error: {} - }; - var promises = []; - Object.entries(writeResult.success).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - promises.push(fromStorage(v).then(function (v2) { - return ret.success[k] = v2; - })); - }); - Object.entries(writeResult.error).forEach(function (_ref3) { - var k = _ref3[0], - error = _ref3[1]; - promises.push(errorFromStorage(error).then(function (err) { - return ret.error[k] = err; - })); - }); - return Promise.resolve(Promise.all(promises)).then(function () { - return ret; - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - var oldQuery = instance.query.bind(instance); - instance.query = function (preparedQuery) { - return oldQuery(preparedQuery).then(function (queryResult) { - return Promise.all(queryResult.documents.map(function (doc) { - return fromStorage(doc); + }, _callee11); + })); + return _toStorage.apply(this, arguments); + } + function fromStorage(_x3) { + return _fromStorage.apply(this, arguments); + } + function _fromStorage() { + _fromStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(docData) { + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + if (docData) { + _context12.next = 2; + break; + } + return _context12.abrupt("return", docData); + case 2: + _context12.next = 4; + return modifyFromStorage(docData); + case 4: + return _context12.abrupt("return", _context12.sent); + case 5: + case "end": + return _context12.stop(); + } + }, _callee12); + })); + return _fromStorage.apply(this, arguments); + } + function errorFromStorage(_x4) { + return _errorFromStorage.apply(this, arguments); + } + function _errorFromStorage() { + _errorFromStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(error) { + var ret; + return _regenerator["default"].wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + ret = (0, _utils.flatClone)(error); + ret.writeRow = (0, _utils.flatClone)(ret.writeRow); + if (!ret.documentInDb) { + _context13.next = 6; + break; + } + _context13.next = 5; + return fromStorage(ret.documentInDb); + case 5: + ret.documentInDb = _context13.sent; + case 6: + if (!ret.writeRow.previous) { + _context13.next = 10; + break; + } + _context13.next = 9; + return fromStorage(ret.writeRow.previous); + case 9: + ret.writeRow.previous = _context13.sent; + case 10: + _context13.next = 12; + return fromStorage(ret.writeRow.document); + case 12: + ret.writeRow.document = _context13.sent; + return _context13.abrupt("return", ret); + case 14: + case "end": + return _context13.stop(); + } + }, _callee13); + })); + return _errorFromStorage.apply(this, arguments); + } + var wrappedInstance = { + databaseName: instance.databaseName, + internals: instance.internals, + cleanup: instance.cleanup.bind(instance), + options: instance.options, + close: instance.close.bind(instance), + schema: instance.schema, + collectionName: instance.collectionName, + count: instance.count.bind(instance), + remove: instance.remove.bind(instance), + originalStorageInstance: instance, + bulkWrite: function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(documentWrites, context) { + var useRows, writeResult, ret, promises; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + useRows = []; + _context3.next = 3; + return Promise.all(documentWrites.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(row) { + var _yield$Promise$all, previous, document; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all([row.previous ? toStorage(row.previous) : undefined, toStorage(row.document)]); + case 2: + _yield$Promise$all = _context2.sent; + previous = _yield$Promise$all[0]; + document = _yield$Promise$all[1]; + useRows.push({ + previous: previous, + document: document + }); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x7) { + return _ref.apply(this, arguments); + }; + }())); + case 3: + _context3.next = 5; + return instance.bulkWrite(useRows, context); + case 5: + writeResult = _context3.sent; + ret = { + success: {}, + error: {} + }; + promises = []; + Object.entries(writeResult.success).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; + promises.push(fromStorage(v).then(function (v2) { + return ret.success[k] = v2; + })); + }); + Object.entries(writeResult.error).forEach(function (_ref3) { + var k = _ref3[0], + error = _ref3[1]; + promises.push(errorFromStorage(error).then(function (err) { + return ret.error[k] = err; + })); + }); + _context3.next = 12; + return Promise.all(promises); + case 12: + return _context3.abrupt("return", ret); + case 13: + case "end": + return _context3.stop(); + } + }, _callee3); })); - }).then(function (documents) { - return { - documents: documents - }; - }); - }; - var oldGetAttachmentData = instance.getAttachmentData.bind(instance); - instance.getAttachmentData = function (documentId, attachmentId) { - try { - return Promise.resolve(oldGetAttachmentData(documentId, attachmentId)).then(function (data) { - return Promise.resolve(modifyAttachmentFromStorage(data)).then(function (_modifyAttachmentFrom) { - data = _modifyAttachmentFrom; - return data; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - var oldFindDocumentsById = instance.findDocumentsById.bind(instance); - instance.findDocumentsById = function (ids, deleted) { - return oldFindDocumentsById(ids, deleted).then(function (findResult) { - try { - var ret = {}; - return Promise.resolve(Promise.all(Object.entries(findResult).map(function (_ref4) { - var key = _ref4[0], - doc = _ref4[1]; - return Promise.resolve(fromStorage(doc)).then(function (_fromStorage) { - ret[key] = _fromStorage; - }); - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }); - }; - var oldGetChangedDocumentsSince = instance.getChangedDocumentsSince.bind(instance); - instance.getChangedDocumentsSince = function (limit, checkpoint) { - return oldGetChangedDocumentsSince(limit, checkpoint).then(function (result) { - try { - var _result$checkpoint = result.checkpoint; - return Promise.resolve(Promise.all(result.documents.map(function (d) { - return fromStorage(d); - }))).then(function (_Promise$all) { - return { - checkpoint: _result$checkpoint, - documents: _Promise$all - }; - }); - } catch (e) { - return Promise.reject(e); + function bulkWrite(_x5, _x6) { + return _bulkWrite.apply(this, arguments); } - }); - }; - var oldChangeStream = instance.changeStream.bind(instance); - instance.changeStream = function () { - return oldChangeStream().pipe((0, _operators.mergeMap)(function (eventBulk) { - try { - return Promise.resolve(Promise.all(eventBulk.events.map(function (event) { - try { - return Promise.resolve(Promise.all([fromStorage(event.documentData), fromStorage(event.previousDocumentData)])).then(function (_ref5) { - var documentData = _ref5[0], - previousDocumentData = _ref5[1]; - var ev = { - operation: event.operation, - eventId: event.eventId, - documentId: event.documentId, - endTime: event.endTime, - startTime: event.startTime, - documentData: documentData, - previousDocumentData: previousDocumentData, - isLocal: false - }; - return ev; - }); - } catch (e) { - return Promise.reject(e); + return bulkWrite; + }(), + query: function query(preparedQuery) { + return instance.query(preparedQuery).then(function (queryResult) { + return Promise.all(queryResult.documents.map(function (doc) { + return fromStorage(doc); + })); + }).then(function (documents) { + return { + documents: documents + }; + }); + }, + getAttachmentData: function () { + var _getAttachmentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(documentId, attachmentId) { + var data; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return instance.getAttachmentData(documentId, attachmentId); + case 2: + data = _context4.sent; + _context4.next = 5; + return modifyAttachmentFromStorage(data); + case 5: + data = _context4.sent; + return _context4.abrupt("return", data); + case 7: + case "end": + return _context4.stop(); } - }))).then(function (useEvents) { - var ret = { - id: eventBulk.id, - events: useEvents, - checkpoint: eventBulk.checkpoint, - context: eventBulk.context - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); + }, _callee4); + })); + function getAttachmentData(_x8, _x9) { + return _getAttachmentData.apply(this, arguments); } - })); - }; - var oldConflictResultionTasks = instance.conflictResultionTasks.bind(instance); - instance.conflictResultionTasks = function () { - return oldConflictResultionTasks().pipe((0, _operators.mergeMap)(function (task) { - try { - return Promise.resolve(fromStorage(task.input.assumedMasterState)).then(function (assumedMasterState) { - return Promise.resolve(fromStorage(task.input.newDocumentState)).then(function (newDocumentState) { - return Promise.resolve(fromStorage(task.input.realMasterState)).then(function (realMasterState) { - return { - id: task.id, - context: task.context, - input: { - assumedMasterState: assumedMasterState, - realMasterState: realMasterState, - newDocumentState: newDocumentState - } - }; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + return getAttachmentData; + }(), + findDocumentsById: function findDocumentsById(ids, deleted) { + return instance.findDocumentsById(ids, deleted).then( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(findResult) { + var ret; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + ret = {}; + _context6.next = 3; + return Promise.all(Object.entries(findResult).map( /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_ref5) { + var key, doc; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + key = _ref5[0], doc = _ref5[1]; + _context5.next = 3; + return fromStorage(doc); + case 3: + ret[key] = _context5.sent; + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x11) { + return _ref6.apply(this, arguments); + }; + }())); + case 3: + return _context6.abrupt("return", ret); + case 4: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return function (_x10) { + return _ref4.apply(this, arguments); + }; + }()); + }, + getChangedDocumentsSince: function getChangedDocumentsSince(limit, checkpoint) { + return instance.getChangedDocumentsSince(limit, checkpoint).then( /*#__PURE__*/function () { + var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(result) { + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.t0 = result.checkpoint; + _context7.next = 3; + return Promise.all(result.documents.map(function (d) { + return fromStorage(d); + })); + case 3: + _context7.t1 = _context7.sent; + return _context7.abrupt("return", { + checkpoint: _context7.t0, + documents: _context7.t1 + }); + case 5: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return function (_x12) { + return _ref7.apply(this, arguments); + }; + }()); + }, + changeStream: function changeStream() { + return instance.changeStream().pipe((0, _operators.mergeMap)( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(eventBulk) { + var useEvents, ret; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return Promise.all(eventBulk.events.map( /*#__PURE__*/function () { + var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(event) { + var _yield$Promise$all2, documentData, previousDocumentData, ev; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return Promise.all([fromStorage(event.documentData), fromStorage(event.previousDocumentData)]); + case 2: + _yield$Promise$all2 = _context8.sent; + documentData = _yield$Promise$all2[0]; + previousDocumentData = _yield$Promise$all2[1]; + ev = { + operation: event.operation, + eventId: event.eventId, + documentId: event.documentId, + endTime: event.endTime, + startTime: event.startTime, + documentData: documentData, + previousDocumentData: previousDocumentData, + isLocal: false + }; + return _context8.abrupt("return", ev); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + return function (_x14) { + return _ref9.apply(this, arguments); + }; + }())); + case 2: + useEvents = _context9.sent; + ret = { + id: eventBulk.id, + events: useEvents, + checkpoint: eventBulk.checkpoint, + context: eventBulk.context + }; + return _context9.abrupt("return", ret); + case 5: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + return function (_x13) { + return _ref8.apply(this, arguments); + }; + }())); + }, + conflictResultionTasks: function conflictResultionTasks() { + return instance.conflictResultionTasks().pipe((0, _operators.mergeMap)( /*#__PURE__*/function () { + var _ref10 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(task) { + var assumedMasterState, newDocumentState, realMasterState; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return fromStorage(task.input.assumedMasterState); + case 2: + assumedMasterState = _context10.sent; + _context10.next = 5; + return fromStorage(task.input.newDocumentState); + case 5: + newDocumentState = _context10.sent; + _context10.next = 8; + return fromStorage(task.input.realMasterState); + case 8: + realMasterState = _context10.sent; + return _context10.abrupt("return", { + id: task.id, + context: task.context, + input: { + assumedMasterState: assumedMasterState, + realMasterState: realMasterState, + newDocumentState: newDocumentState + } + }); + case 10: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + return function (_x15) { + return _ref10.apply(this, arguments); + }; + }())); + }, + resolveConflictResultionTask: function resolveConflictResultionTask(taskSolution) { + if (taskSolution.output.isEqual) { + return instance.resolveConflictResultionTask(taskSolution); } - })); - }; - var oldResolveConflictResultionTask = instance.resolveConflictResultionTask.bind(instance); - instance.resolveConflictResultionTask = function (taskSolution) { - if (taskSolution.output.isEqual) { - return oldResolveConflictResultionTask(taskSolution); + var useSolution = { + id: taskSolution.id, + output: { + isEqual: false, + documentData: taskSolution.output.documentData + } + }; + return instance.resolveConflictResultionTask(useSolution); } - var useSolution = { - id: taskSolution.id, - output: { - isEqual: false, - documentData: taskSolution.output.documentData - } - }; - return oldResolveConflictResultionTask(useSolution); }; - return instance; + return wrappedInstance; } //# sourceMappingURL=plugin-helpers.js.map \ No newline at end of file diff --git a/dist/lib/plugin-helpers.js.map b/dist/lib/plugin-helpers.js.map index b833cf5e5b5..91da5fea60a 100644 --- a/dist/lib/plugin-helpers.js.map +++ b/dist/lib/plugin-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin-helpers.js","names":["VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","has","set","VALIDATOR_CACHE","getFromMapOrThrow","initValidator","schema","hash","fastUnsecureHash","JSON","stringify","validator","args","Object","assign","storage","createStorageInstance","params","instance","validatorCached","requestIdleCallbackIfAvailable","oldBulkWrite","bulkWrite","bind","documentWrites","context","forEach","row","document","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","errorFromStorage","error","fromStorage","ret","writeRow","previous","flatClone","documentInDb","docData","toStorage","modifyAttachmentFromStorage","v","useRows","Promise","all","map","undefined","push","writeResult","success","promises","entries","k","then","v2","err","oldQuery","query","preparedQuery","queryResult","documents","doc","oldGetAttachmentData","getAttachmentData","documentId","attachmentId","data","oldFindDocumentsById","findDocumentsById","ids","deleted","findResult","key","oldGetChangedDocumentsSince","getChangedDocumentsSince","limit","checkpoint","result","d","oldChangeStream","changeStream","pipe","mergeMap","eventBulk","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","useEvents","id","oldConflictResultionTasks","conflictResultionTasks","task","input","assumedMasterState","newDocumentState","realMasterState","oldResolveConflictResultionTask","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { mergeMap } from 'rxjs/operators';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\nimport {\n fastUnsecureHash,\n flatClone,\n getFromMapOrThrow,\n requestIdleCallbackIfAvailable\n} from './util';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\ntype ValidatorFunction = (docData: RxDocumentData) => void;\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n if (!VALIDATOR_CACHE_BY_VALIDATOR_KEY.has(validatorKey)) {\n VALIDATOR_CACHE_BY_VALIDATOR_KEY.set(validatorKey, new Map());\n }\n const VALIDATOR_CACHE = getFromMapOrThrow(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey);\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = fastUnsecureHash(JSON.stringify(schema));\n if (!VALIDATOR_CACHE.has(hash)) {\n const validator = getValidator(schema);\n VALIDATOR_CACHE.set(hash, validator);\n return validator;\n }\n return getFromMapOrThrow(VALIDATOR_CACHE, hash);\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n documentWrites.forEach(row => {\n validatorCached(row.document);\n });\n return oldBulkWrite(documentWrites, context);\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n) {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageBulkWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if (ret.documentInDb) {\n ret.documentInDb = await fromStorage(ret.documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await oldBulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n return ret;\n };\n\n const oldQuery = instance.query.bind(instance);\n instance.query = (preparedQuery) => {\n return oldQuery(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n };\n\n const oldGetAttachmentData = instance.getAttachmentData.bind(instance);\n instance.getAttachmentData = async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await oldGetAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n };\n\n const oldFindDocumentsById = instance.findDocumentsById.bind(instance);\n instance.findDocumentsById = (ids, deleted) => {\n return oldFindDocumentsById(ids, deleted).then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n };\n\n const oldGetChangedDocumentsSince = instance.getChangedDocumentsSince.bind(instance);\n instance.getChangedDocumentsSince = (limit, checkpoint) => {\n return oldGetChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n };\n\n const oldChangeStream = instance.changeStream.bind(instance);\n instance.changeStream = () => {\n return oldChangeStream().pipe(\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n })\n );\n };\n\n const oldConflictResultionTasks = instance.conflictResultionTasks.bind(instance);\n instance.conflictResultionTasks = () => {\n return oldConflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n };\n\n const oldResolveConflictResultionTask = instance.resolveConflictResultionTask.bind(instance);\n instance.resolveConflictResultionTask = (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return oldResolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return oldResolveConflictResultionTask(useSolution);\n };\n\n return instance;\n}\n"],"mappings":";;;;;;;AAAA;AAgBA;AAgBA;AACA;AACA;AACA;AACA,IAAMA,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACO,SAASC,6BAA6B;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAI,CAACJ,gCAAgC,CAACK,GAAG,CAACD,YAAY,CAAC,EAAE;IACrDJ,gCAAgC,CAACM,GAAG,CAACF,YAAY,EAAE,IAAIH,GAAG,EAAE,CAAC;EACjE;EACA,IAAMM,eAAe,GAAG,IAAAC,uBAAiB,EAACR,gCAAgC,EAAEI,YAAY,CAAC;EAEzF,SAASK,aAAa,CAClBC,MAAyB,EACR;IACjB,IAAMC,IAAI,GAAG,IAAAC,sBAAgB,EAACC,IAAI,CAACC,SAAS,CAACJ,MAAM,CAAC,CAAC;IACrD,IAAI,CAACH,eAAe,CAACF,GAAG,CAACM,IAAI,CAAC,EAAE;MAC5B,IAAMI,SAAS,GAAGZ,YAAY,CAACO,MAAM,CAAC;MACtCH,eAAe,CAACD,GAAG,CAACK,IAAI,EAAEI,SAAS,CAAC;MACpC,OAAOA,SAAS;IACpB;IACA,OAAO,IAAAP,uBAAiB,EAACD,eAAe,EAAEI,IAAI,CAAC;EACnD;EAEA,OAAO,UAACK,IAAI,EAAK;IACb,OAAOC,MAAM,CAACC,MAAM,CAChB,CAAC,CAAC,EACFF,IAAI,CAACG,OAAO,EACZ;MACUC,qBAAqB,iCACvBC,MAAuD;QAAA,IACzD;UAAA,uBACyBL,IAAI,CAACG,OAAO,CAACC,qBAAqB,CAACC,MAAM,CAAC,iBAA3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AED,IAAME,+BAA+B,GAAGvF,QAAQ,CAACwF,4BAA4B,CAACnF,IAAI,CAACL,QAAQ,CAAC;EAC5FA,QAAQ,CAACwF,4BAA4B,GAAG,UAACC,YAAY,EAAK;IACtD,IAAIA,YAAY,CAACC,MAAM,CAACC,OAAO,EAAE;MAC7B,OAAOJ,+BAA+B,CAACE,YAAY,CAAC;IACxD;IACA,IAAMG,WAAW,GAAG;MAChBb,EAAE,EAAEU,YAAY,CAACV,EAAE;MACnBW,MAAM,EAAE;QACJC,OAAO,EAAE,KAAK;QACdrB,YAAY,EAAEmB,YAAY,CAACC,MAAM,CAACpB;MACtC;IACJ,CAAC;IACD,OAAOiB,+BAA+B,CAACK,WAAW,CAAC;EACvD,CAAC;EAED,OAAO5F,QAAQ;AACnB"} \ No newline at end of file +{"version":3,"file":"plugin-helpers.js","names":["VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","has","set","VALIDATOR_CACHE","getFromMapOrThrow","initValidator","schema","hash","fastUnsecureHash","JSON","stringify","validator","args","Object","assign","storage","createStorageInstance","params","instance","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","requestIdleCallbackIfAvailable","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","flatClone","documentInDb","previous","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","entries","k","v2","err","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","data","findDocumentsById","ids","deleted","findResult","key","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","pipe","mergeMap","eventBulk","events","event","documentData","previousDocumentData","ev","operation","eventId","endTime","startTime","isLocal","useEvents","id","conflictResultionTasks","task","input","assumedMasterState","newDocumentState","realMasterState","resolveConflictResultionTask","taskSolution","output","isEqual","useSolution"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { mergeMap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport { WrappedRxStorageInstance } from './rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentDataById,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n fastUnsecureHash,\n flatClone,\n getFromMapOrThrow,\n requestIdleCallbackIfAvailable\n} from './plugins/utils';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema-hash\n * so we can reuse them when multiple collections have the same schema\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n if (!VALIDATOR_CACHE_BY_VALIDATOR_KEY.has(validatorKey)) {\n VALIDATOR_CACHE_BY_VALIDATOR_KEY.set(validatorKey, new Map());\n }\n const VALIDATOR_CACHE = getFromMapOrThrow(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey);\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n const hash = fastUnsecureHash(JSON.stringify(schema));\n if (!VALIDATOR_CACHE.has(hash)) {\n const validator = getValidator(schema);\n VALIDATOR_CACHE.set(hash, validator);\n return validator;\n }\n return getFromMapOrThrow(VALIDATOR_CACHE, hash);\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ error: {}, success: {} });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error[validationError.documentId] = validationError;\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => Promise> | RxDocumentData,\n modifyFromStorage: (docData: RxDocumentData) => Promise> | RxDocumentData,\n modifyAttachmentFromStorage: (attachmentData: string) => Promise | string = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: instance.schema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n const promises: Promise[] = [];\n Object.entries(writeResult.success).forEach(([k, v]) => {\n promises.push(\n fromStorage(v).then(v2 => ret.success[k] = v2)\n );\n });\n Object.entries(writeResult.error).forEach(([k, error]) => {\n promises.push(\n errorFromStorage(error).then(err => ret.error[k] = err)\n );\n });\n await Promise.all(promises);\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n Object.entries(findResult)\n .map(async ([key, doc]) => {\n ret[key] = await fromStorage(doc);\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: (limit, checkpoint) => {\n return instance.getChangedDocumentsSince(limit, checkpoint)\n .then(async (result) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map(d => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n eventId: event.eventId,\n documentId: event.documentId,\n endTime: event.endTime,\n startTime: event.startTime,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n })\n );\n },\n conflictResultionTasks: () => {\n return instance.conflictResultionTasks().pipe(\n mergeMap(async (task) => {\n const assumedMasterState = await fromStorage(task.input.assumedMasterState);\n const newDocumentState = await fromStorage(task.input.newDocumentState);\n const realMasterState = await fromStorage(task.input.realMasterState);\n return {\n id: task.id,\n context: task.context,\n input: {\n assumedMasterState,\n realMasterState,\n newDocumentState\n }\n };\n })\n );\n },\n resolveConflictResultionTask: (taskSolution) => {\n if (taskSolution.output.isEqual) {\n return instance.resolveConflictResultionTask(taskSolution);\n }\n const useSolution = {\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData: taskSolution.output.documentData\n }\n };\n return instance.resolveConflictResultionTask(useSolution);\n }\n };\n\n return wrappedInstance;\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AAmBA;AAoBA;AACA;AACA;AACA;AACA,IAAMA,gCAA6E,GAAG,IAAIC,GAAG,EAAE;;AAE/F;AACA;AACA;AACA;AACO,SAASC,6BAA6B;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAI,CAACJ,gCAAgC,CAACK,GAAG,CAACD,YAAY,CAAC,EAAE;IACrDJ,gCAAgC,CAACM,GAAG,CAACF,YAAY,EAAE,IAAIH,GAAG,EAAE,CAAC;EACjE;EACA,IAAMM,eAAe,GAAG,IAAAC,wBAAiB,EAACR,gCAAgC,EAAEI,YAAY,CAAC;EAEzF,SAASK,aAAa,CAClBC,MAAyB,EACR;IACjB,IAAMC,IAAI,GAAG,IAAAC,uBAAgB,EAACC,IAAI,CAACC,SAAS,CAACJ,MAAM,CAAC,CAAC;IACrD,IAAI,CAACH,eAAe,CAACF,GAAG,CAACM,IAAI,CAAC,EAAE;MAC5B,IAAMI,SAAS,GAAGZ,YAAY,CAACO,MAAM,CAAC;MACtCH,eAAe,CAACD,GAAG,CAACK,IAAI,EAAEI,SAAS,CAAC;MACpC,OAAOA,SAAS;IACpB;IACA,OAAO,IAAAP,wBAAiB,EAACD,eAAe,EAAEI,IAAI,CAAC;EACnD;EAEA,OAAO,UAACK,IAAI,EAAK;IACb,OAAOC,MAAM,CAACC,MAAM,CAChB,CAAC,CAAC,EACFF,IAAI,CAACG,OAAO,EACZ;MACUC,qBAAqB;QAAA,4HACvBC,MAAuD;UAAA;UAAA;YAAA;cAAA;gBAAA;gBAAA,OAEhCL,IAAI,CAACG,OAAO,CAACC,qBAAqB,CAACC,MAAM,CAAC;cAAA;gBAA3DC,QAAQ;gBACRC,WAAW,GAAG,IAAAC,2CAA2B,EAACH,MAAM,CAACX,MAAM,CA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e,IAAI;UAAA;UAAA;YAAA;cAAA;gBAAA;gBAAA,OACiB5D,WAAW,CAAC4D,IAAI,CAACC,KAAK,CAACC,kBAAkB,CAAC;cAAA;gBAArEA,kBAAkB;gBAAA;gBAAA,OACO9D,WAAW,CAAC4D,IAAI,CAACC,KAAK,CAACE,gBAAgB,CAAC;cAAA;gBAAjEA,gBAAgB;gBAAA;gBAAA,OACQ/D,WAAW,CAAC4D,IAAI,CAACC,KAAK,CAACG,eAAe,CAAC;cAAA;gBAA/DA,eAAe;gBAAA,mCACd;kBACHN,EAAE,EAAEE,IAAI,CAACF,EAAE;kBACXtF,OAAO,EAAEwF,IAAI,CAACxF,OAAO;kBACrByF,KAAK,EAAE;oBACHC,kBAAkB,EAAlBA,kBAAkB;oBAClBE,eAAe,EAAfA,eAAe;oBACfD,gBAAgB,EAAhBA;kBACJ;gBACJ,CAAC;cAAA;cAAA;gBAAA;YAAA;UAAA;QAAA,CACJ;QAAA;UAAA;QAAA;MAAA,IAAC,CACL;IACL,CAAC;IACDE,4BAA4B,EAAE,sCAACC,YAAY,EAAK;MAC5C,IAAIA,YAAY,CAACC,MAAM,CAACC,OAAO,EAAE;QAC7B,OAAO1G,QAAQ,CAACuG,4BAA4B,CAACC,YAAY,CAAC;MAC9D;MACA,IAAMG,WAAW,GAAG;QAChBX,EAAE,EAAEQ,YAAY,CAACR,EAAE;QACnBS,MAAM,EAAE;UACJC,OAAO,EAAE,KAAK;UACdnB,YAAY,EAAEiB,YAAY,CAACC,MAAM,CAAClB;QACtC;MACJ,CAAC;MACD,OAAOvF,QAAQ,CAACuG,4BAA4B,CAACI,WAAW,CAAC;IAC7D;EACJ,CAAC;EAED,OAAO/D,eAAe;AAC1B"} \ No newline at end of file diff --git a/dist/lib/plugin.js b/dist/lib/plugin.js index 6559b5e26c2..537daa94552 100644 --- a/dist/lib/plugin.js +++ b/dist/lib/plugin.js @@ -57,9 +57,8 @@ function addRxPlugin(plugin) { } /** - * Since version 10.0.0 we decoupled pouchdb from - * the rxdb core. Therefore pouchdb plugins must be added - * with the addPouchPlugin() method of the pouchdb plugin. + * To identify broken configurations, + * we only allow RxDB plugins to be passed into addRxPlugin(). */ if (!plugin.rxdb) { throw (0, _rxError.newRxTypeError)('PL1', { diff --git a/dist/lib/plugin.js.map b/dist/lib/plugin.js.map index 31cbd33b95b..d9e481648f1 100644 --- a/dist/lib/plugin.js.map +++ b/dist/lib/plugin.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.js","names":["PROTOTYPES","RxSchema","prototype","RxDocument","RxDocumentPrototype","RxQuery","RxQueryBase","RxCollection","RxCollectionBase","RxDatabase","RxDatabaseBase","ADDED_PLUGINS","Set","ADDED_PLUGIN_NAMES","addRxPlugin","plugin","runPluginHooks","plugins","has","name","newRxError","add","rxdb","newRxTypeError","init","prototypes","Object","entries","forEach","fun","overwritable","assign","hooks","hooksObj","after","HOOKS","push","before","unshift"],"sources":["../../src/plugin.ts"],"sourcesContent":["/**\n * this handles how plugins are added to rxdb\n * basically it changes the internal prototypes\n * by passing them to the plugins-functions\n */\nimport {\n RxSchema\n} from './rx-schema';\nimport {\n basePrototype as RxDocumentPrototype\n} from './rx-document';\nimport {\n RxQueryBase\n} from './rx-query';\nimport {\n RxCollectionBase\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from './rx-database';\nimport type {\n RxPlugin\n} from './types';\n\nimport { overwritable } from './overwritable';\nimport {\n HOOKS,\n runPluginHooks\n} from './hooks';\nimport { newRxError, newRxTypeError } from './rx-error';\n\n/**\n * prototypes that can be manipulated with a plugin\n */\nconst PROTOTYPES: { [k: string]: any; } = {\n RxSchema: RxSchema.prototype,\n RxDocument: RxDocumentPrototype,\n RxQuery: RxQueryBase.prototype,\n RxCollection: RxCollectionBase.prototype,\n RxDatabase: RxDatabaseBase.prototype\n};\n\nconst ADDED_PLUGINS: Set = new Set();\nconst ADDED_PLUGIN_NAMES: Set = new Set();\n\n/**\n * Add a plugin to the RxDB library.\n * Plugins are added globally and cannot be removed.\n */\nexport function addRxPlugin(plugin: RxPlugin) {\n runPluginHooks('preAddRxPlugin', { plugin, plugins: ADDED_PLUGINS });\n\n // do nothing if added before\n if (ADDED_PLUGINS.has(plugin)) {\n return;\n } else {\n\n // ensure no other plugin with the same name was already added\n if (ADDED_PLUGIN_NAMES.has(plugin.name)) {\n throw newRxError('PL3', {\n name: plugin.name,\n plugin,\n });\n }\n\n ADDED_PLUGINS.add(plugin);\n ADDED_PLUGIN_NAMES.add(plugin.name);\n }\n\n /**\n * Since version 10.0.0 we decoupled pouchdb from\n * the rxdb core. Therefore pouchdb plugins must be added\n * with the addPouchPlugin() method of the pouchdb plugin.\n */\n if (!plugin.rxdb) {\n throw newRxTypeError('PL1', {\n plugin\n });\n }\n\n if (plugin.init) {\n plugin.init();\n }\n\n // prototype-overwrites\n if (plugin.prototypes) {\n Object\n .entries(plugin.prototypes)\n .forEach(([name, fun]) => {\n return (fun as any)(PROTOTYPES[name]);\n });\n }\n // overwritable-overwrites\n if (plugin.overwritable) {\n Object.assign(\n overwritable,\n plugin.overwritable\n );\n }\n // extend-hooks\n if (plugin.hooks) {\n Object\n .entries(plugin.hooks)\n .forEach(([name, hooksObj]) => {\n if (hooksObj.after) {\n HOOKS[name].push(hooksObj.after);\n }\n if (hooksObj.before) {\n HOOKS[name].unshift(hooksObj.before);\n }\n });\n }\n}\n"],"mappings":";;;;;;AAKA;AAGA;AAGA;AAGA;AAGA;AAOA;AACA;AAIA;AA7BA;AACA;AACA;AACA;AACA;;AA2BA;AACA;AACA;AACA,IAAMA,UAAiC,GAAG;EACtCC,QAAQ,EAAEA,kBAAQ,CAACC,SAAS;EAC5BC,UAAU,EAAEC,yBAAmB;EAC/BC,OAAO,EAAEC,oBAAW,CAACJ,SAAS;EAC9BK,YAAY,EAAEC,8BAAgB,CAACN,SAAS;EACxCO,UAAU,EAAEC,0BAAc,CAACR;AAC/B,CAAC;AAED,IAAMS,aAAkC,GAAG,IAAIC,GAAG,EAAE;AACpD,IAAMC,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MAAM,CACDC,OAAO,CAACZ,MAAM,CAACiB,KAAK,CAAC,CACrBJ,OAAO,CAAC,iBAAsB;MAAA,IAApBT,IAAI;QAAEc,QAAQ;MACrB,IAAIA,QAAQ,CAACC,KAAK,EAAE;QAChBC,YAAK,CAAChB,IAAI,CAAC,CAACiB,IAAI,CAACH,QAAQ,CAACC,KAAK,CAAC;MACpC;MACA,IAAID,QAAQ,CAACI,MAAM,EAAE;QACjBF,YAAK,CAAChB,IAAI,CAAC,CAACmB,OAAO,CAACL,QAAQ,CAACI,MAAM,CAAC;MACxC;IACJ,CAAC,CAAC;EACV;AACJ"} \ No newline at end of file +{"version":3,"file":"plugin.js","names":["PROTOTYPES","RxSchema","prototype","RxDocument","RxDocumentPrototype","RxQuery","RxQueryBase","RxCollection","RxCollectionBase","RxDatabase","RxDatabaseBase","ADDED_PLUGINS","Set","ADDED_PLUGIN_NAMES","addRxPlugin","plugin","runPluginHooks","plugins","has","name","newRxError","add","rxdb","newRxTypeError","init","prototypes","Object","entries","forEach","fun","overwritable","assign","hooks","hooksObj","after","HOOKS","push","before","unshift"],"sources":["../../src/plugin.ts"],"sourcesContent":["/**\n * this handles how plugins are added to rxdb\n * basically it changes the internal prototypes\n * by passing them to the plugins-functions\n */\nimport {\n RxSchema\n} from './rx-schema';\nimport {\n basePrototype as RxDocumentPrototype\n} from './rx-document';\nimport {\n RxQueryBase\n} from './rx-query';\nimport {\n RxCollectionBase\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from './rx-database';\nimport type {\n RxPlugin\n} from './types';\n\nimport { overwritable } from './overwritable';\nimport {\n HOOKS,\n runPluginHooks\n} from './hooks';\nimport { newRxError, newRxTypeError } from './rx-error';\n\n/**\n * prototypes that can be manipulated with a plugin\n */\nconst PROTOTYPES: { [k: string]: any; } = {\n RxSchema: RxSchema.prototype,\n RxDocument: RxDocumentPrototype,\n RxQuery: RxQueryBase.prototype,\n RxCollection: RxCollectionBase.prototype,\n RxDatabase: RxDatabaseBase.prototype\n};\n\nconst ADDED_PLUGINS: Set = new Set();\nconst ADDED_PLUGIN_NAMES: Set = new Set();\n\n/**\n * Add a plugin to the RxDB library.\n * Plugins are added globally and cannot be removed.\n */\nexport function addRxPlugin(plugin: RxPlugin) {\n runPluginHooks('preAddRxPlugin', { plugin, plugins: ADDED_PLUGINS });\n\n // do nothing if added before\n if (ADDED_PLUGINS.has(plugin)) {\n return;\n } else {\n\n // ensure no other plugin with the same name was already added\n if (ADDED_PLUGIN_NAMES.has(plugin.name)) {\n throw newRxError('PL3', {\n name: plugin.name,\n plugin,\n });\n }\n\n ADDED_PLUGINS.add(plugin);\n ADDED_PLUGIN_NAMES.add(plugin.name);\n }\n\n /**\n * To identify broken configurations,\n * we only allow RxDB plugins to be passed into addRxPlugin().\n */\n if (!plugin.rxdb) {\n throw newRxTypeError('PL1', {\n plugin\n });\n }\n\n if (plugin.init) {\n plugin.init();\n }\n\n // prototype-overwrites\n if (plugin.prototypes) {\n Object\n .entries(plugin.prototypes)\n .forEach(([name, fun]) => {\n return (fun as any)(PROTOTYPES[name]);\n });\n }\n // overwritable-overwrites\n if (plugin.overwritable) {\n Object.assign(\n overwritable,\n plugin.overwritable\n );\n }\n // extend-hooks\n if (plugin.hooks) {\n Object\n .entries(plugin.hooks)\n .forEach(([name, hooksObj]) => {\n if (hooksObj.after) {\n HOOKS[name].push(hooksObj.after);\n }\n if (hooksObj.before) {\n HOOKS[name].unshift(hooksObj.before);\n }\n });\n }\n}\n\n"],"mappings":";;;;;;AAKA;AAGA;AAGA;AAGA;AAGA;AAOA;AACA;AAIA;AA7BA;AACA;AACA;AACA;AACA;;AA2BA;AACA;AACA;AACA,IAAMA,UAAiC,GAAG;EACtCC,QAAQ,EAAEA,kBAAQ,CAACC,SAAS;EAC5BC,UAAU,EAAEC,yBAAmB;EAC/BC,OAAO,EAAEC,oBAAW,CAACJ,SAAS;EAC9BK,YAAY,EAAEC,8BAAgB,CAACN,SAAS;EACxCO,UAAU,EAAEC,0BAAc,CA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AACe,YAAY,CACtB;EACL;EACA;EACA,IAAIf,MAAM,CAACiB,KAAK,EAAE;IACdN,MAAM,CACDC,OAAO,CAACZ,MAAM,CAACiB,KAAK,CAAC,CACrBJ,OAAO,CAAC,iBAAsB;MAAA,IAApBT,IAAI;QAAEc,QAAQ;MACrB,IAAIA,QAAQ,CAACC,KAAK,EAAE;QAChBC,YAAK,CAAChB,IAAI,CAAC,CAACiB,IAAI,CAACH,QAAQ,CAACC,KAAK,CAAC;MACpC;MACA,IAAID,QAAQ,CAACI,MAAM,EAAE;QACjBF,YAAK,CAAChB,IAAI,CAAC,CAACmB,OAAO,CAACL,QAAQ,CAACI,MAAM,CAAC;MACxC;IACJ,CAAC,CAAC;EACV;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/attachments/index.js b/dist/lib/plugins/attachments/index.js index 297e089f610..db0ed8ce715 100644 --- a/dist/lib/plugins/attachments/index.js +++ b/dist/lib/plugins/attachments/index.js @@ -1,5 +1,6 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -8,11 +9,13 @@ exports.allAttachments = allAttachments; exports.fromStorageInstanceResult = fromStorageInstanceResult; exports.getAttachment = getAttachment; exports.postMigrateDocument = postMigrateDocument; -exports.putAttachment = exports.preMigrateDocument = void 0; +exports.preMigrateDocument = preMigrateDocument; +exports.putAttachment = putAttachment; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _operators = require("rxjs/operators"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _rxError = require("../../rx-error"); -var _rxStorageHelper = require("../../rx-storage-helper"); function ensureSchemaSupportsAttachments(doc) { var schemaJson = doc.collection.schema.jsonSchema; if (!schemaJson.attachments) { @@ -21,88 +24,6 @@ function ensureSchemaSupportsAttachments(doc) { }); } } -var preMigrateDocument = function preMigrateDocument(data) { - try { - var attachments = data.docData._attachments; - var _temp = function () { - if (attachments) { - var newAttachments = {}; - return Promise.resolve(Promise.all(Object.keys(attachments).map(function (attachmentId) { - try { - var attachment = attachments[attachmentId]; - var docPrimary = data.docData[data.oldCollection.schema.primaryPath]; - return Promise.resolve(data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId)).then(function (rawAttachmentData) { - newAttachments[attachmentId] = { - length: attachment.length, - type: attachment.type, - data: rawAttachmentData - }; - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - /** - * Hooks mutate the input - * instead of returning stuff - */ - data.docData._attachments = newAttachments; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -exports.preMigrateDocument = preMigrateDocument; -var putAttachment = function putAttachment(attachmentData) { - try { - var _arguments = arguments, - _this4 = this; - var _skipIfSame = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true; - ensureSchemaSupportsAttachments(_this4); - var dataSize = _util.blobBufferUtil.size(attachmentData.data); - return Promise.resolve(_util.blobBufferUtil.toBase64String(attachmentData.data)).then(function (dataString) { - var id = attachmentData.id; - var type = attachmentData.type; - var data = dataString; - _this4._atomicQueue = _this4._atomicQueue.then(function () { - try { - var docWriteData = (0, _rxStorageHelper.flatCloneDocWithMeta)(_this4._data); - docWriteData._attachments = (0, _util.flatClone)(docWriteData._attachments); - docWriteData._attachments[id] = { - length: dataSize, - type: type, - data: data - }; - var writeRow = { - previous: (0, _util.flatClone)(_this4._data), - document: (0, _util.flatClone)(docWriteData) - }; - return Promise.resolve((0, _rxStorageHelper.writeSingle)(_this4.collection.storageInstance, writeRow, 'attachment-put')).then(function (writeResult) { - var attachmentDataOfId = writeResult._attachments[id]; - var attachment = fromStorageInstanceResult(id, attachmentDataOfId, _this4); - var newData = (0, _util.flatClone)(_this4._data); - newData._rev = writeResult._rev; - newData._attachments = writeResult._attachments; - _this4._dataSync$.next(newData); - return attachment; - }); - } catch (e) { - return Promise.reject(e); - } - }); - return _this4._atomicQueue; - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * get an attachment of the document by its id - */ -exports.putAttachment = putAttachment; var _assignMethodsToAttachment = function _assignMethodsToAttachment(attachment) { Object.entries(attachment.doc.collection.attachments).forEach(function (_ref) { var funName = _ref[0], @@ -136,51 +57,69 @@ var RxAttachment = /*#__PURE__*/function () { var _proto = RxAttachment.prototype; _proto.remove = function remove() { var _this = this; - this.doc._atomicQueue = this.doc._atomicQueue.then(function () { - try { - var docWriteData = (0, _rxStorageHelper.flatCloneDocWithMeta)(_this.doc._data); - docWriteData._attachments = (0, _util.flatClone)(docWriteData._attachments); - delete docWriteData._attachments[_this.id]; - return Promise.resolve((0, _rxStorageHelper.writeSingle)(_this.doc.collection.storageInstance, { - previous: (0, _util.flatClone)(_this.doc._data), - // TODO do we need a flatClone here? - document: docWriteData - }, 'attachment-remove')).then(function (writeResult) { - var newData = (0, _util.flatClone)(_this.doc._data); - newData._rev = writeResult._rev; - newData._attachments = writeResult._attachments; - _this.doc._dataSync$.next(newData); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return this.doc._atomicQueue; + return this.doc.collection.incrementalWriteQueue.addWrite(this.doc._data, function (docWriteData) { + delete docWriteData._attachments[_this.id]; + return docWriteData; + }).then(function () {}); } /** * returns the data for the attachment */; - _proto.getData = function getData() { - try { - var _this2 = this; - return Promise.resolve(_this2.doc.collection.storageInstance.getAttachmentData(_this2.doc.primary, _this2.id)).then(function (plainDataBase64) { - return Promise.resolve(_util.blobBufferUtil.createBlobBufferFromBase64(plainDataBase64, _this2.type)); - }); - } catch (e) { - return Promise.reject(e); + _proto.getData = + /*#__PURE__*/ + function () { + var _getData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var plainDataBase64, ret; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.doc.collection.storageInstance.getAttachmentData(this.doc.primary, this.id); + case 2: + plainDataBase64 = _context.sent; + _context.next = 5; + return _utils.blobBufferUtil.createBlobBufferFromBase64(plainDataBase64, this.type); + case 5: + ret = _context.sent; + return _context.abrupt("return", ret); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function getData() { + return _getData.apply(this, arguments); } - }; - _proto.getStringData = function getStringData() { - try { - var _this3 = this; - return Promise.resolve(_this3.getData()).then(function (data) { - return Promise.resolve(_util.blobBufferUtil.toString(data)); - }); - } catch (e) { - return Promise.reject(e); + return getData; + }(); + _proto.getStringData = /*#__PURE__*/function () { + var _getStringData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var data, asString; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.getData(); + case 2: + data = _context2.sent; + _context2.next = 5; + return _utils.blobBufferUtil.toString(data); + case 5: + asString = _context2.sent; + return _context2.abrupt("return", asString); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function getStringData() { + return _getStringData.apply(this, arguments); } - }; + return getStringData; + }(); return RxAttachment; }(); exports.RxAttachment = RxAttachment; @@ -193,9 +132,53 @@ function fromStorageInstanceResult(id, attachmentData, rxDocument) { digest: attachmentData.digest }); } +function putAttachment(_x) { + return _putAttachment.apply(this, arguments); +} +/** + * get an attachment of the document by its id + */ +function _putAttachment() { + _putAttachment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(attachmentData) { + var _this4 = this; + var dataSize, dataString, id, type, data; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + ensureSchemaSupportsAttachments(this); + dataSize = _utils.blobBufferUtil.size(attachmentData.data); + _context3.next = 4; + return _utils.blobBufferUtil.toBase64String(attachmentData.data); + case 4: + dataString = _context3.sent; + id = attachmentData.id; + type = attachmentData.type; + data = dataString; + return _context3.abrupt("return", this.collection.incrementalWriteQueue.addWrite(this._data, function (docWriteData) { + docWriteData._attachments = (0, _utils.flatClone)(docWriteData._attachments); + docWriteData._attachments[id] = { + length: dataSize, + type: type, + data: data + }; + return docWriteData; + }).then(function (writeResult) { + var newDocument = _this4.collection._docCache.getCachedRxDocument(writeResult); + var attachmentDataOfId = writeResult._attachments[id]; + var attachment = fromStorageInstanceResult(id, attachmentDataOfId, newDocument); + return attachment; + })); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + return _putAttachment.apply(this, arguments); +} function getAttachment(id) { ensureSchemaSupportsAttachments(this); - var docData = this._dataSync$.getValue(); + var docData = this._data; if (!docData._attachments || !docData._attachments[id]) return null; var attachmentData = docData._attachments[id]; var attachment = fromStorageInstanceResult(id, attachmentData, this); @@ -206,24 +189,81 @@ function getAttachment(id) { * returns all attachments of the document */ function allAttachments() { - var _this5 = this; + var _this2 = this; ensureSchemaSupportsAttachments(this); - var docData = this._dataSync$.getValue(); + var docData = this._data; // if there are no attachments, the field is missing if (!docData._attachments) { return []; } return Object.keys(docData._attachments).map(function (id) { - return fromStorageInstanceResult(id, docData._attachments[id], _this5); + return fromStorageInstanceResult(id, docData._attachments[id], _this2); }); } +function preMigrateDocument(_x2) { + return _preMigrateDocument.apply(this, arguments); +} +function _preMigrateDocument() { + _preMigrateDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(data) { + var attachments, newAttachments; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + attachments = data.docData._attachments; + if (!attachments) { + _context5.next = 6; + break; + } + newAttachments = {}; + _context5.next = 5; + return Promise.all(Object.keys(attachments).map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(attachmentId) { + var attachment, docPrimary, rawAttachmentData; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + attachment = attachments[attachmentId]; + docPrimary = data.docData[data.oldCollection.schema.primaryPath]; + _context4.next = 4; + return data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId); + case 4: + rawAttachmentData = _context4.sent; + newAttachments[attachmentId] = { + length: attachment.length, + type: attachment.type, + data: rawAttachmentData + }; + case 6: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return function (_x3) { + return _ref4.apply(this, arguments); + }; + }())); + case 5: + /** + * Hooks mutate the input + * instead of returning stuff + */ + data.docData._attachments = newAttachments; + case 6: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _preMigrateDocument.apply(this, arguments); +} function postMigrateDocument(_action) { /** * No longer needed because * we store the attachments data buffers directly in the document. */ - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } var RxDBAttachmentsPlugin = { name: 'attachments', @@ -235,19 +275,14 @@ var RxDBAttachmentsPlugin = { proto.allAttachments = allAttachments; Object.defineProperty(proto, 'allAttachments$', { get: function allAttachments$() { - var _this6 = this; - return this._dataSync$.pipe((0, _operators.map)(function (data) { - if (!data['_attachments']) { - return {}; - } - return data['_attachments']; - }), (0, _operators.map)(function (attachmentsData) { - return Object.entries(attachmentsData); + var _this3 = this; + return this.$.pipe((0, _operators.map)(function (data) { + return Object.entries(data._attachments); }), (0, _operators.map)(function (entries) { return entries.map(function (_ref3) { var id = _ref3[0], attachmentData = _ref3[1]; - return fromStorageInstanceResult(id, attachmentData, _this6); + return fromStorageInstanceResult(id, attachmentData, _this3); }); })); } diff --git a/dist/lib/plugins/attachments/index.js.map b/dist/lib/plugins/attachments/index.js.map index 04e975b2d14..baa3b0bb349 100644 --- a/dist/lib/plugins/attachments/index.js.map +++ b/dist/lib/plugins/attachments/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ensureSchemaSupportsAttachments","doc","schemaJson","collection","schema","jsonSchema","attachments","newRxError","link","preMigrateDocument","data","docData","_attachments","newAttachments","Promise","all","Object","keys","map","attachmentId","attachment","docPrimary","oldCollection","primaryPath","storageInstance","getAttachmentData","rawAttachmentData","length","type","putAttachment","attachmentData","_skipIfSame","dataSize","blobBufferUtil","size","toBase64String","dataString","id","_atomicQueue","then","docWriteData","flatCloneDocWithMeta","_data","flatClone","writeRow","previous","document","writeSingle","writeResult","attachmentDataOfId","fromStorageInstanceResult","newData","_rev","_dataSync$","next","_assignMethodsToAttachment","entries","forEach","funName","fun","defineProperty","get","bind","RxAttachment","digest","remove","getData","primary","plainDataBase64","createBlobBufferFromBase64","getStringData","toString","rxDocument","getAttachment","getValue","allAttachments","postMigrateDocument","_action","PROMISE_RESOLVE_VOID","RxDBAttachmentsPlugin","name","rxdb","prototypes","RxDocument","proto","allAttachments$","pipe","attachmentsData","overwritable","hooks","after"],"sources":["../../../../src/plugins/attachments/index.ts"],"sourcesContent":["import {\n map\n} from 'rxjs/operators';\n\nimport {\n blobBufferUtil,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDocument,\n RxPlugin,\n BlobBuffer,\n OldRxCollection,\n RxDocumentWriteData,\n RxAttachmentData,\n RxDocumentData,\n RxAttachmentCreator,\n RxAttachmentWriteData\n} from '../../types';\nimport { flatCloneDocWithMeta, writeSingle } from '../../rx-storage-helper';\n\n\n\nfunction ensureSchemaSupportsAttachments(doc: any) {\n const schemaJson = doc.collection.schema.jsonSchema;\n if (!schemaJson.attachments) {\n throw newRxError('AT1', {\n link: 'https://pubkey.github.io/rxdb/rx-attachment.html'\n });\n }\n}\n\nconst _assignMethodsToAttachment = function (attachment: any) {\n Object\n .entries(attachment.doc.collection.attachments)\n .forEach(([funName, fun]) => {\n Object.defineProperty(attachment, funName, {\n get: () => (fun as any).bind(attachment)\n });\n });\n};\n\n/**\n * an RxAttachment is basically just the attachment-stub\n * wrapped so that you can access the attachment-data\n */\nexport class RxAttachment {\n public doc: RxDocument;\n public id: string;\n public type: string;\n public length: number;\n public digest: string;\n constructor({\n doc,\n id,\n type,\n length,\n digest\n }: any) {\n this.doc = doc;\n this.id = id;\n this.type = type;\n this.length = length;\n this.digest = digest;\n\n _assignMethodsToAttachment(this);\n }\n\n remove(): Promise {\n this.doc._atomicQueue = this.doc._atomicQueue\n .then(async () => {\n const docWriteData: RxDocumentWriteData<{}> = flatCloneDocWithMeta(this.doc._data);\n docWriteData._attachments = flatClone(docWriteData._attachments);\n delete docWriteData._attachments[this.id];\n const writeResult: RxDocumentData = await writeSingle(\n this.doc.collection.storageInstance,\n {\n previous: flatClone(this.doc._data), // TODO do we need a flatClone here?\n document: docWriteData\n },\n 'attachment-remove'\n );\n\n const newData = flatClone(this.doc._data);\n newData._rev = writeResult._rev;\n newData._attachments = writeResult._attachments;\n this.doc._dataSync$.next(newData);\n\n });\n return this.doc._atomicQueue;\n }\n\n /**\n * returns the data for the attachment\n */\n async getData(): Promise {\n const plainDataBase64 = await this.doc.collection.storageInstance.getAttachmentData(\n this.doc.primary,\n this.id\n );\n const ret = await blobBufferUtil.createBlobBufferFromBase64(\n plainDataBase64,\n this.type as any\n );\n return ret;\n }\n\n async getStringData(): Promise {\n const data = await this.getData();\n const asString = await blobBufferUtil.toString(data);\n return asString;\n }\n}\n\nexport function fromStorageInstanceResult(\n id: string,\n attachmentData: RxAttachmentData,\n rxDocument: RxDocument\n) {\n return new RxAttachment({\n doc: rxDocument,\n id,\n type: attachmentData.type,\n length: attachmentData.length,\n digest: attachmentData.digest\n });\n}\n\nexport async function putAttachment(\n this: RxDocument,\n attachmentData: RxAttachmentCreator,\n /**\n * If set to true, the write will be skipped\n * when the attachment already contains the same data.\n * @deprecated The check if the data has changed is now performed\n * inside of the RxStorage, no longer by RxDB itself. So we do\n * no longer need 'skipIfSame'.\n */\n _skipIfSame: boolean = true\n): Promise {\n ensureSchemaSupportsAttachments(this);\n\n const dataSize = blobBufferUtil.size(attachmentData.data);\n const dataString = await blobBufferUtil.toBase64String(attachmentData.data);\n\n const id = attachmentData.id;\n const type = attachmentData.type;\n const data = dataString;\n\n this._atomicQueue = this._atomicQueue\n .then(async () => {\n const docWriteData: RxDocumentWriteData<{}> = flatCloneDocWithMeta(this._data);\n docWriteData._attachments = flatClone(docWriteData._attachments);\n\n docWriteData._attachments[id] = {\n length: dataSize,\n type,\n data\n };\n const writeRow = {\n previous: flatClone(this._data),\n document: flatClone(docWriteData)\n };\n\n const writeResult = await writeSingle(\n this.collection.storageInstance,\n writeRow,\n 'attachment-put'\n );\n\n const attachmentDataOfId = writeResult._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentDataOfId,\n this\n );\n\n const newData = flatClone(this._data);\n newData._rev = writeResult._rev;\n newData._attachments = writeResult._attachments;\n this._dataSync$.next(newData);\n\n return attachment;\n });\n return this._atomicQueue;\n}\n\n/**\n * get an attachment of the document by its id\n */\nexport function getAttachment(\n this: RxDocument,\n id: string\n): RxAttachment | null {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._dataSync$.getValue();\n if (!docData._attachments || !docData._attachments[id])\n return null;\n\n const attachmentData = docData._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n return attachment;\n}\n\n/**\n * returns all attachments of the document\n */\nexport function allAttachments(\n this: RxDocument\n): RxAttachment[] {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._dataSync$.getValue();\n\n // if there are no attachments, the field is missing\n if (!docData._attachments) {\n return [];\n }\n return Object.keys(docData._attachments)\n .map(id => {\n return fromStorageInstanceResult(\n id,\n docData._attachments[id],\n this\n );\n });\n}\n\nexport async function preMigrateDocument(\n data: {\n docData: RxDocumentData;\n oldCollection: OldRxCollection;\n }\n): Promise {\n const attachments = data.docData._attachments;\n if (attachments) {\n const newAttachments: { [attachmentId: string]: RxAttachmentWriteData; } = {};\n await Promise.all(\n Object.keys(attachments).map(async (attachmentId) => {\n const attachment: RxAttachmentData = attachments[attachmentId];\n const docPrimary: string = (data.docData as any)[data.oldCollection.schema.primaryPath];\n const rawAttachmentData = await data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId);\n newAttachments[attachmentId] = {\n length: attachment.length,\n type: attachment.type,\n data: rawAttachmentData\n };\n })\n );\n\n /**\n * Hooks mutate the input\n * instead of returning stuff\n */\n (data.docData as RxDocumentWriteData)._attachments = newAttachments;\n }\n}\n\nexport function postMigrateDocument(_action: any): Promise {\n /**\n * No longer needed because\n * we store the attachments data buffers directly in the document.\n */\n return PROMISE_RESOLVE_VOID;\n}\n\nexport const RxDBAttachmentsPlugin: RxPlugin = {\n name: 'attachments',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.putAttachment = putAttachment;\n proto.getAttachment = getAttachment;\n proto.allAttachments = allAttachments;\n Object.defineProperty(proto, 'allAttachments$', {\n get: function allAttachments$() {\n return this._dataSync$\n .pipe(\n map((data: any) => {\n if (!data['_attachments']) {\n return {};\n }\n return data['_attachments'];\n }),\n map((attachmentsData: any) => Object.entries(\n attachmentsData\n )),\n map(entries => {\n return (entries as any)\n .map(([id, attachmentData]: any) => {\n return fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n });\n })\n );\n }\n });\n }\n },\n overwritable: {},\n hooks: {\n preMigrateDocument: {\n after: preMigrateDocument\n },\n postMigrateDocument: {\n after: postMigrateDocument\n }\n }\n};\n"],"mappings":";;;;;;;;;;;AAAA;AAIA;AAKA;AAcA;AAIA,SAASA,+BAA+B,CAACC,GAAQ,EAAE;EAC/C,IAAMC,UAAU,GAAGD,GAAG,CAACE,UAAU,CAACC,MAAM,CAACC,UAAU;EACnD,IAAI,CAACH,UAAU,CAACI,WAAW,EAAE;IACzB,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;MACpBC,IAAI,EAAE;IACV,CAAC,CAAC;EACN;AACJ;AAAC,IAyMqBC,kBAAkB,YAAlBA,kBAAkB,CACpCC,IAGC;EAAA,IACY;IACb,IAAMJ,WAAW,GAAGI,IAAI,CAACC,OAAO,CAACC,YAAY;IAAC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D,MAAM,CAAC4C,cAAc,CAACwB,KAAK,EAAE,iBAAiB,EAAE;QAC5CvB,GAAG,EAAE,SAASwB,eAAe,GAAG;UAAA;UAC5B,OAAO,IAAI,CAAChC,UAAU,CACjBiC,IAAI,CACD,IAAApE,cAAG,EAAC,UAACR,IAAS,EAAK;YACf,IAAI,CAACA,IAAI,CAAC,cAAc,CAAC,EAAE;cACvB,OAAO,CAAC,CAAC;YACb;YACA,OAAOA,IAAI,CAAC,cAAc,CAAC;UAC/B,CAAC,CAAC,EACF,IAAAQ,cAAG,EAAC,UAACqE,eAAoB;YAAA,OAAKvE,MAAM,CAACwC,OAAO,CACxC+B,eAAe,CAClB;UAAA,EAAC,EACF,IAAArE,cAAG,EAAC,UAAAsC,OAAO,EAAI;YACX,OAAQA,OAAO,CACVtC,GAAG,CAAC,iBAA+B;cAAA,IAA7BmB,EAAE;gBAAEP,cAAc;cACrB,OAAOoB,yBAAyB,CAC5Bb,EAAE,EACFP,cAAc,EACd,MAAI,CACP;YACL,CAAC,CAAC;UACV,CAAC,CAAC,CACL;QACT;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;EACD0D,YAAY,EAAE,CAAC,CAAC;EAChBC,KAAK,EAAE;IACHhF,kBAAkB,EAAE;MAChBiF,KAAK,EAAEjF;IACX,CAAC;IACDmE,mBAAmB,EAAE;MACjBc,KAAK,EAAEd;IACX;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ensureSchemaSupportsAttachments","doc","schemaJson","collection","schema","jsonSchema","attachments","newRxError","link","_assignMethodsToAttachment","attachment","Object","entries","forEach","funName","fun","defineProperty","get","bind","RxAttachment","id","type","length","digest","remove","incrementalWriteQueue","addWrite","_data","docWriteData","_attachments","then","getData","storageInstance","getAttachmentData","primary","plainDataBase64","blobBufferUtil","createBlobBufferFromBase64","ret","getStringData","data","toString","asString","fromStorageInstanceResult","attachmentData","rxDocument","putAttachment","dataSize","size","toBase64String","dataString","flatClone","writeResult","newDocument","_docCache","getCachedRxDocument","attachmentDataOfId","getAttachment","docData","allAttachments","keys","map","preMigrateDocument","newAttachments","Promise","all","attachmentId","docPrimary","oldCollection","primaryPath","rawAttachmentData","postMigrateDocument","_action","PROMISE_RESOLVE_VOID","RxDBAttachmentsPlugin","name","rxdb","prototypes","RxDocument","proto","allAttachments$","$","pipe","overwritable","hooks","after"],"sources":["../../../../src/plugins/attachments/index.ts"],"sourcesContent":["import {\n map\n} from 'rxjs/operators';\n\nimport {\n blobBufferUtil,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDocument,\n RxPlugin,\n BlobBuffer,\n OldRxCollection,\n RxDocumentWriteData,\n RxAttachmentData,\n RxDocumentData,\n RxAttachmentCreator,\n RxAttachmentWriteData\n} from '../../types';\n\nfunction ensureSchemaSupportsAttachments(doc: any) {\n const schemaJson = doc.collection.schema.jsonSchema;\n if (!schemaJson.attachments) {\n throw newRxError('AT1', {\n link: 'https://pubkey.github.io/rxdb/rx-attachment.html'\n });\n }\n}\n\nconst _assignMethodsToAttachment = function (attachment: any) {\n Object\n .entries(attachment.doc.collection.attachments)\n .forEach(([funName, fun]) => {\n Object.defineProperty(attachment, funName, {\n get: () => (fun as any).bind(attachment)\n });\n });\n};\n\n/**\n * an RxAttachment is basically just the attachment-stub\n * wrapped so that you can access the attachment-data\n */\nexport class RxAttachment {\n public doc: RxDocument;\n public id: string;\n public type: string;\n public length: number;\n public digest: string;\n constructor({\n doc,\n id,\n type,\n length,\n digest\n }: any) {\n this.doc = doc;\n this.id = id;\n this.type = type;\n this.length = length;\n this.digest = digest;\n\n _assignMethodsToAttachment(this);\n }\n\n remove(): Promise {\n return this.doc.collection.incrementalWriteQueue.addWrite(\n this.doc._data,\n docWriteData => {\n delete docWriteData._attachments[this.id];\n return docWriteData;\n }\n ).then(() => { });\n }\n\n /**\n * returns the data for the attachment\n */\n async getData(): Promise {\n const plainDataBase64 = await this.doc.collection.storageInstance.getAttachmentData(\n this.doc.primary,\n this.id\n );\n const ret = await blobBufferUtil.createBlobBufferFromBase64(\n plainDataBase64,\n this.type as any\n );\n return ret;\n }\n\n async getStringData(): Promise {\n const data = await this.getData();\n const asString = await blobBufferUtil.toString(data);\n return asString;\n }\n}\n\nexport function fromStorageInstanceResult(\n id: string,\n attachmentData: RxAttachmentData,\n rxDocument: RxDocument\n) {\n return new RxAttachment({\n doc: rxDocument,\n id,\n type: attachmentData.type,\n length: attachmentData.length,\n digest: attachmentData.digest\n });\n}\n\nexport async function putAttachment(\n this: RxDocument,\n attachmentData: RxAttachmentCreator\n): Promise {\n ensureSchemaSupportsAttachments(this);\n\n const dataSize = blobBufferUtil.size(attachmentData.data);\n const dataString = await blobBufferUtil.toBase64String(attachmentData.data);\n\n const id = attachmentData.id;\n const type = attachmentData.type;\n const data = dataString;\n\n return this.collection.incrementalWriteQueue.addWrite(\n this._data,\n (docWriteData: RxDocumentWriteData) => {\n docWriteData._attachments = flatClone(docWriteData._attachments);\n\n docWriteData._attachments[id] = {\n length: dataSize,\n type,\n data\n };\n return docWriteData;\n }).then(writeResult => {\n const newDocument = this.collection._docCache.getCachedRxDocument(writeResult);\n const attachmentDataOfId = writeResult._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentDataOfId,\n newDocument\n );\n return attachment;\n });\n}\n\n/**\n * get an attachment of the document by its id\n */\nexport function getAttachment(\n this: RxDocument,\n id: string\n): RxAttachment | null {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._data;\n if (!docData._attachments || !docData._attachments[id])\n return null;\n\n const attachmentData = docData._attachments[id];\n const attachment = fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n return attachment;\n}\n\n/**\n * returns all attachments of the document\n */\nexport function allAttachments(\n this: RxDocument\n): RxAttachment[] {\n ensureSchemaSupportsAttachments(this);\n const docData: any = this._data;\n\n // if there are no attachments, the field is missing\n if (!docData._attachments) {\n return [];\n }\n return Object.keys(docData._attachments)\n .map(id => {\n return fromStorageInstanceResult(\n id,\n docData._attachments[id],\n this\n );\n });\n}\n\nexport async function preMigrateDocument(\n data: {\n docData: RxDocumentData;\n oldCollection: OldRxCollection;\n }\n): Promise {\n const attachments = data.docData._attachments;\n if (attachments) {\n const newAttachments: { [attachmentId: string]: RxAttachmentWriteData; } = {};\n await Promise.all(\n Object.keys(attachments).map(async (attachmentId) => {\n const attachment: RxAttachmentData = attachments[attachmentId];\n const docPrimary: string = (data.docData as any)[data.oldCollection.schema.primaryPath];\n const rawAttachmentData = await data.oldCollection.storageInstance.getAttachmentData(docPrimary, attachmentId);\n newAttachments[attachmentId] = {\n length: attachment.length,\n type: attachment.type,\n data: rawAttachmentData\n };\n })\n );\n\n /**\n * Hooks mutate the input\n * instead of returning stuff\n */\n (data.docData as RxDocumentWriteData)._attachments = newAttachments;\n }\n}\n\nexport function postMigrateDocument(_action: any): Promise {\n /**\n * No longer needed because\n * we store the attachments data buffers directly in the document.\n */\n return PROMISE_RESOLVE_VOID;\n}\n\nexport const RxDBAttachmentsPlugin: RxPlugin = {\n name: 'attachments',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.putAttachment = putAttachment;\n proto.getAttachment = getAttachment;\n proto.allAttachments = allAttachments;\n Object.defineProperty(proto, 'allAttachments$', {\n get: function allAttachments$(this: RxDocument) {\n return this.$\n .pipe(\n map(data => Object.entries(\n data._attachments\n )),\n map(entries => {\n return (entries as any)\n .map(([id, attachmentData]: any) => {\n return fromStorageInstanceResult(\n id,\n attachmentData,\n this\n );\n });\n })\n );\n }\n });\n }\n },\n overwritable: {},\n hooks: {\n preMigrateDocument: {\n after: preMigrateDocument\n },\n postMigrateDocument: {\n after: postMigrateDocument\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAIA;AAKA;AAeA,SAASA,+BAA+B,CAACC,GAAQ,EAAE;EAC/C,IAAMC,UAAU,GAAGD,GAAG,CAACE,UAAU,CAACC,MAAM,CAAC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ACFwB,cAAc,EACd,MAAI,CACP;YACL,CAAC,CAAC;UACV,CAAC,CAAC,CACL;QACT;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;EACDuC,YAAY,EAAE,CAAC,CAAC;EAChBC,KAAK,EAAE;IACHtB,kBAAkB,EAAE;MAChBuB,KAAK,EAAEvB;IACX,CAAC;IACDS,mBAAmB,EAAE;MACjBc,KAAK,EAAEd;IACX;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/backup/file-util.js b/dist/lib/plugins/backup/file-util.js index 1dd3f57ec1b..e0acbdaf319 100644 --- a/dist/lib/plugins/backup/file-util.js +++ b/dist/lib/plugins/backup/file-util.js @@ -1,5 +1,6 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -12,38 +13,14 @@ exports.metaFileLocation = metaFileLocation; exports.prepareFolders = prepareFolders; exports.setMeta = setMeta; exports.writeJsonToFile = writeJsonToFile; -exports.writeToFile = void 0; +exports.writeToFile = writeToFile; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var fs = _interopRequireWildcard(require("fs")); var path = _interopRequireWildcard(require("path")); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -var writeToFile = function writeToFile(location, data) { - try { - var _temp2 = function _temp2() { - return new Promise(function (res, rej) { - fs.writeFile(location, data, 'utf-8', function (err) { - if (err) { - rej(err); - } else { - res(); - } - }); - }); - }; - var _temp = function () { - if (typeof data !== 'string') { - return Promise.resolve(_util.blobBufferUtil.toString(data)).then(function (_blobBufferUtil$toStr) { - data = _blobBufferUtil$toStr; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } -}; -exports.writeToFile = writeToFile; /** * ensure that the given folder exists */ @@ -74,7 +51,7 @@ function prepareFolders(database, options) { ensureFolderExists(options.directory); var metaLoc = metaFileLocation(options); if (!fs.existsSync(metaLoc)) { - var currentTime = (0, _util.now)(); + var currentTime = (0, _utils.now)(); var metaData = { createdAt: currentTime, updatedAt: currentTime, @@ -86,6 +63,40 @@ function prepareFolders(database, options) { ensureFolderExists(path.join(options.directory, collectionName)); }); } +function writeToFile(_x, _x2) { + return _writeToFile.apply(this, arguments); +} +function _writeToFile() { + _writeToFile = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(location, data) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(typeof data !== 'string')) { + _context.next = 4; + break; + } + _context.next = 3; + return _utils.blobBufferUtil.toString(data); + case 3: + data = _context.sent; + case 4: + return _context.abrupt("return", new Promise(function (res, rej) { + fs.writeFile(location, data, 'utf-8', function (err) { + if (err) { + rej(err); + } else { + res(); + } + }); + })); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _writeToFile.apply(this, arguments); +} function writeJsonToFile(location, data) { return writeToFile(location, JSON.stringify(data)); } diff --git a/dist/lib/plugins/backup/file-util.js.map b/dist/lib/plugins/backup/file-util.js.map index 0c54333f7ba..a3f19ec663f 100644 --- a/dist/lib/plugins/backup/file-util.js.map +++ b/dist/lib/plugins/backup/file-util.js.map @@ -1 +1 @@ -{"version":3,"file":"file-util.js","names":["writeToFile","location","data","Promise","res","rej","fs","writeFile","err","blobBufferUtil","toString","ensureFolderExists","folderPath","existsSync","mkdirSync","recursive","clearFolder","deleteFolder","rmdirSync","prepareFolders","database","options","directory","metaLoc","metaFileLocation","currentTime","now","metaData","createdAt","updatedAt","collectionStates","writeFileSync","JSON","stringify","Object","keys","collections","forEach","collectionName","path","join","writeJsonToFile","getMeta","loc","readFile","metaContent","parse","setMeta","meta","documentFolder","docId"],"sources":["../../../../src/plugins/backup/file-util.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n BackupMetaFileContent,\n BackupOptions,\n BlobBuffer,\n RxDatabase\n} from '../../types';\nimport { blobBufferUtil, now } from '../../util';\n\n/**\n * ensure that the given folder exists\n */\nexport function ensureFolderExists(folderPath: string): void {\n if (!fs.existsSync(folderPath)) {\n fs.mkdirSync(folderPath, { recursive: true });\n }\n}\n\n/**\n * deletes and recreates the folder\n */\nexport function clearFolder(folderPath: string): void {\n deleteFolder(folderPath);\n ensureFolderExists(folderPath);\n}\n\nexport function deleteFolder(folderPath: string): void {\n // only remove if exists to not raise warning\n if (fs.existsSync(folderPath)) {\n fs.rmdirSync(folderPath, { recursive: true });\n }\n}\n\nexport function prepareFolders(\n database: RxDatabase,\n options: BackupOptions\n) {\n ensureFolderExists(options.directory);\n\n const metaLoc = metaFileLocation(options);\n\n if (!fs.existsSync(metaLoc)) {\n const currentTime = now();\n const metaData: BackupMetaFileContent = {\n createdAt: currentTime,\n updatedAt: currentTime,\n collectionStates: {}\n };\n fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8');\n }\n\n Object.keys(database.collections).forEach(collectionName => {\n ensureFolderExists(\n path.join(\n options.directory,\n collectionName\n )\n );\n });\n}\n\nexport async function writeToFile(\n location: string,\n data: string | BlobBuffer\n): Promise {\n if (typeof data !== 'string') {\n data = await blobBufferUtil.toString(data);\n }\n return new Promise(function (res, rej) {\n fs.writeFile(\n location,\n data as string,\n 'utf-8',\n (err) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n }\n );\n });\n}\n\nexport function writeJsonToFile(\n location: string,\n data: any\n): Promise {\n return writeToFile(\n location,\n JSON.stringify(data)\n );\n}\n\nexport function metaFileLocation(options: BackupOptions): string {\n return path.join(\n options.directory,\n 'backup_meta.json'\n );\n}\n\nexport function getMeta(options: BackupOptions): Promise {\n const loc = metaFileLocation(options);\n return new Promise((res, rej) => {\n fs.readFile(loc, 'utf-8', (err, data) => {\n if (err) {\n rej(err);\n } else {\n const metaContent = JSON.parse(data);\n res(metaContent);\n }\n });\n });\n}\n\nexport function setMeta(\n options: BackupOptions,\n meta: BackupMetaFileContent\n): Promise {\n const loc = metaFileLocation(options);\n return writeJsonToFile(loc, meta);\n}\n\nexport function documentFolder(\n options: BackupOptions,\n docId: string\n): string {\n return path.join(\n options.directory,\n docId\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AAOA;AAAiD;AAAA;AAAA,IAsD3BA,WAAW,YAAXA,WAAW,CAC7BC,QAAgB,EAChBC,IAAyB;EAAA,IACZ;IAAA;MAIb,OAAO,IAAIC,OAAO,CAAC,UAAUC,GAAG,EAAEC,GAAG,EAAE;QACnCC,EAAE,CAACC,SAAS,CACRN,QAAQ,EACRC,IAAI,EACJ,OAAO,EACP,UAACM,GAAG,EAAK;UACL,IAAIA,GAAG,EAAE;YACLH,GAAG,CAACG,GAAG,CAAC;UACZ,CAAC,MAAM;YACHJ,GAAG,EAAE;UACT;QACJ,CAAC,CACJ;MACL,CAAC,CAAC;IAAC;IAAA;M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,WAAW,CAAC,CAACC,OAAO,CAAC,UAAAC,cAAc,EAAI;IACxD3B,kBAAkB,CACd4B,IAAI,CAACC,IAAI,CACLnB,OAAO,CAACC,SAAS,EACjBgB,cAAc,CACjB,CACJ;EACL,CAAC,CAAC;AACN;AAyBO,SAASG,eAAe,CAC3BxC,QAAgB,EAChBC,IAAS,EACI;EACb,OAAOF,WAAW,CACdC,QAAQ,EACR+B,IAAI,CAACC,SAAS,CAAC/B,IAAI,CAAC,CACvB;AACL;AAEO,SAASsB,gBAAgB,CAACH,OAAsB,EAAU;EAC7D,OAAOkB,IAAI,CAACC,IAAI,CACZnB,OAAO,CAACC,SAAS,EACjB,kBAAkB,CACrB;AACL;AAEO,SAASoB,OAAO,CAACrB,OAAsB,EAAkC;EAC5E,IAAMsB,GAAG,GAAGnB,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAO,IAAIlB,OAAO,CAAC,UAACC,GAAG,EAAEC,GAAG,EAAK;IAC7BC,EAAE,CAACsC,QAAQ,CAACD,GAAG,EAAE,OAAO,EAAE,UAACnC,GAAG,EAAEN,IAAI,EAAK;MACrC,IAAIM,GAAG,EAAE;QACLH,GAAG,CAACG,GAAG,CAAC;MACZ,CAAC,MAAM;QACH,IAAMqC,WAAW,GAAGb,IAAI,CAACc,KAAK,CAAC5C,IAAI,CAAC;QACpCE,GAAG,CAACyC,WAAW,CAAC;MACpB;IACJ,CAAC,CAAC;EACN,CAAC,CAAC;AACN;AAEO,SAASE,OAAO,CACnB1B,OAAsB,EACtB2B,IAA2B,EACd;EACb,IAAML,GAAG,GAAGnB,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAOoB,eAAe,CAACE,GAAG,EAAEK,IAAI,CAAC;AACrC;AAEO,SAASC,cAAc,CAC1B5B,OAAsB,EACtB6B,KAAa,EACP;EACN,OAAOX,IAAI,CAACC,IAAI,CACZnB,OAAO,CAACC,SAAS,EACjB4B,KAAK,CACR;AACL"} \ No newline at end of file +{"version":3,"file":"file-util.js","names":["ensureFolderExists","folderPath","fs","existsSync","mkdirSync","recursive","clearFolder","deleteFolder","rmdirSync","prepareFolders","database","options","directory","metaLoc","metaFileLocation","currentTime","now","metaData","createdAt","updatedAt","collectionStates","writeFileSync","JSON","stringify","Object","keys","collections","forEach","collectionName","path","join","writeToFile","location","data","blobBufferUtil","toString","Promise","res","rej","writeFile","err","writeJsonToFile","getMeta","loc","readFile","metaContent","parse","setMeta","meta","documentFolder","docId"],"sources":["../../../../src/plugins/backup/file-util.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n BackupMetaFileContent,\n BackupOptions,\n BlobBuffer,\n RxDatabase\n} from '../../types';\nimport { blobBufferUtil, now } from '../../plugins/utils';\n\n/**\n * ensure that the given folder exists\n */\nexport function ensureFolderExists(folderPath: string): void {\n if (!fs.existsSync(folderPath)) {\n fs.mkdirSync(folderPath, { recursive: true });\n }\n}\n\n/**\n * deletes and recreates the folder\n */\nexport function clearFolder(folderPath: string): void {\n deleteFolder(folderPath);\n ensureFolderExists(folderPath);\n}\n\nexport function deleteFolder(folderPath: string): void {\n // only remove if exists to not raise warning\n if (fs.existsSync(folderPath)) {\n fs.rmdirSync(folderPath, { recursive: true });\n }\n}\n\nexport function prepareFolders(\n database: RxDatabase,\n options: BackupOptions\n) {\n ensureFolderExists(options.directory);\n\n const metaLoc = metaFileLocation(options);\n\n if (!fs.existsSync(metaLoc)) {\n const currentTime = now();\n const metaData: BackupMetaFileContent = {\n createdAt: currentTime,\n updatedAt: currentTime,\n collectionStates: {}\n };\n fs.writeFileSync(metaLoc, JSON.stringify(metaData), 'utf-8');\n }\n\n Object.keys(database.collections).forEach(collectionName => {\n ensureFolderExists(\n path.join(\n options.directory,\n collectionName\n )\n );\n });\n}\n\nexport async function writeToFile(\n location: string,\n data: string | BlobBuffer\n): Promise {\n if (typeof data !== 'string') {\n data = await blobBufferUtil.toString(data);\n }\n return new Promise(function (res, rej) {\n fs.writeFile(\n location,\n data as string,\n 'utf-8',\n (err) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n }\n );\n });\n}\n\nexport function writeJsonToFile(\n location: string,\n data: any\n): Promise {\n return writeToFile(\n location,\n JSON.stringify(data)\n );\n}\n\nexport function metaFileLocation(options: BackupOptions): string {\n return path.join(\n options.directory,\n 'backup_meta.json'\n );\n}\n\nexport function getMeta(options: BackupOptions): Promise {\n const loc = metaFileLocation(options);\n return new Promise((res, rej) => {\n fs.readFile(loc, 'utf-8', (err, data) => {\n if (err) {\n rej(err);\n } else {\n const metaContent = JSON.parse(data);\n res(metaContent);\n }\n });\n });\n}\n\nexport function setMeta(\n options: BackupOptions,\n meta: BackupMetaFileContent\n): Promise {\n const loc = metaFileLocation(options);\n return writeJsonToFile(loc, meta);\n}\n\nexport function documentFolder(\n options: BackupOptions,\n docId: string\n): string {\n return path.join(\n options.directory,\n docId\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AACA;AAOA;AAA0D;AAAA;AAE1D;AACA;AACA;AACO,SAASA,kBAAkB,CAACC,UAAkB,EAAQ;EACzD,IAAI,CAACC,EAAE,CAACC,UAAU,CAACF,UAAU,CAAC,EAAE;IAC5BC,EAAE,CAACE,SAAS,CAACH,UAAU,EAAE;MAAEI,SAAS,EAAE;IAAK,CAAC,CAAC;EACjD;AACJ;;AAEA;AACA;AACA;AACO,SAASC,WAAW,CAACL,UAAkB,EAAQ;EAClDM,YAAY,CAACN,UAAU,CAAC;EACxBD,kBAAkB,CAACC,UAAU,CAAC;AAClC;AAEO,SAASM,YAAY,CAACN,UAAkB,EAAQ;EACnD;EACA,IAAIC,EAAE,CAACC,UAAU,CAACF,UAAU,CAAC,EAAE;IAC3BC,EAAE,CAACM,SAAS,CAACP,UAAU,EAAE;MAAEI,SAAS,EAAE;IAAK,CAAC,CAAC;EACjD;AACJ;AAEO,SAASI,cAAc,CAC1BC,QAAoB,EACpBC,OAAsB,EACxB;EACEX,kBAAkB,CAACW,OAAO,CAACC,SAAS,CAAC;EA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WAAW,CACdC,QAAQ,EACRV,IAAI,CAACC,SAAS,CAACU,IAAI,CAAC,CACvB;AACL;AAEO,SAASnB,gBAAgB,CAACH,OAAsB,EAAU;EAC7D,OAAOkB,IAAI,CAACC,IAAI,CACZnB,OAAO,CAACC,SAAS,EACjB,kBAAkB,CACrB;AACL;AAEO,SAAS8B,OAAO,CAAC/B,OAAsB,EAAkC;EAC5E,IAAMgC,GAAG,GAAG7B,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAO,IAAIyB,OAAO,CAAC,UAACC,GAAG,EAAEC,GAAG,EAAK;IAC7BpC,EAAE,CAAC0C,QAAQ,CAACD,GAAG,EAAE,OAAO,EAAE,UAACH,GAAG,EAAEP,IAAI,EAAK;MACrC,IAAIO,GAAG,EAAE;QACLF,GAAG,CAACE,GAAG,CAAC;MACZ,CAAC,MAAM;QACH,IAAMK,WAAW,GAAGvB,IAAI,CAACwB,KAAK,CAACb,IAAI,CAAC;QACpCI,GAAG,CAACQ,WAAW,CAAC;MACpB;IACJ,CAAC,CAAC;EACN,CAAC,CAAC;AACN;AAEO,SAASE,OAAO,CACnBpC,OAAsB,EACtBqC,IAA2B,EACd;EACb,IAAML,GAAG,GAAG7B,gBAAgB,CAACH,OAAO,CAAC;EACrC,OAAO8B,eAAe,CAACE,GAAG,EAAEK,IAAI,CAAC;AACrC;AAEO,SAASC,cAAc,CAC1BtC,OAAsB,EACtBuC,KAAa,EACP;EACN,OAAOrB,IAAI,CAACC,IAAI,CACZnB,OAAO,CAACC,SAAS,EACjBsC,KAAK,CACR;AACL"} \ No newline at end of file diff --git a/dist/lib/plugins/backup/index.js b/dist/lib/plugins/backup/index.js index bd46d346820..29c3ec6e0d9 100644 --- a/dist/lib/plugins/backup/index.js +++ b/dist/lib/plugins/backup/index.js @@ -1,5 +1,6 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -11,12 +12,14 @@ var _exportNames = { }; exports.RxDBBackupPlugin = exports.RxBackupState = void 0; exports.backup = backup; -exports.backupSingleDocument = void 0; +exports.backupSingleDocument = backupSingleDocument; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var path = _interopRequireWildcard(require("path")); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); var _rxError = require("../../rx-error"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _fileUtil = require("./file-util"); Object.keys(_fileUtil).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -29,205 +32,81 @@ Object.keys(_fileUtil).forEach(function (key) { } }); }); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * Backups a single documents, * returns the paths to all written files */ -var backupSingleDocument = function backupSingleDocument(rxDocument, options) { - try { - var data = rxDocument.toJSON(true); - var writtenFiles = []; - var docFolder = (0, _fileUtil.documentFolder)(options, rxDocument.primary); - return Promise.resolve((0, _fileUtil.clearFolder)(docFolder)).then(function () { - var fileLocation = path.join(docFolder, 'document.json'); - return Promise.resolve((0, _fileUtil.writeJsonToFile)(fileLocation, data)).then(function () { - writtenFiles.push(fileLocation); - var _temp = function () { - if (options.attachments) { - var attachmentsFolder = path.join(docFolder, 'attachments'); - (0, _fileUtil.ensureFolderExists)(attachmentsFolder); - var attachments = rxDocument.allAttachments(); - return Promise.resolve(Promise.all(attachments.map(function (attachment) { - try { - return Promise.resolve(attachment.getData()).then(function (content) { - var attachmentFileLocation = path.join(attachmentsFolder, attachment.id); - return Promise.resolve((0, _fileUtil.writeToFile)(attachmentFileLocation, content)).then(function () { - writtenFiles.push(attachmentFileLocation); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); +function backupSingleDocument(_x, _x2) { + return _backupSingleDocument.apply(this, arguments); +} +function _backupSingleDocument() { + _backupSingleDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(rxDocument, options) { + var data, writtenFiles, docFolder, fileLocation, attachmentsFolder, attachments; + return _regenerator["default"].wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + data = rxDocument.toJSON(true); + writtenFiles = []; + docFolder = (0, _fileUtil.documentFolder)(options, rxDocument.primary); + _context7.next = 5; + return (0, _fileUtil.clearFolder)(docFolder); + case 5: + fileLocation = path.join(docFolder, 'document.json'); + _context7.next = 8; + return (0, _fileUtil.writeJsonToFile)(fileLocation, data); + case 8: + writtenFiles.push(fileLocation); + if (!options.attachments) { + _context7.next = 15; + break; } - }(); - return _temp && _temp.then ? _temp.then(function () { - return writtenFiles; - }) : writtenFiles; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.backupSingleDocument = backupSingleDocument; + attachmentsFolder = path.join(docFolder, 'attachments'); + (0, _fileUtil.ensureFolderExists)(attachmentsFolder); + attachments = rxDocument.allAttachments(); + _context7.next = 15; + return Promise.all(attachments.map( /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(attachment) { + var content, attachmentFileLocation; + return _regenerator["default"].wrap(function _callee5$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return attachment.getData(); + case 2: + content = _context6.sent; + attachmentFileLocation = path.join(attachmentsFolder, attachment.id); + _context6.next = 6; + return (0, _fileUtil.writeToFile)(attachmentFileLocation, content); + case 6: + writtenFiles.push(attachmentFileLocation); + case 7: + case "end": + return _context6.stop(); + } + }, _callee5); + })); + return function (_x6) { + return _ref5.apply(this, arguments); + }; + }())); + case 15: + return _context7.abrupt("return", writtenFiles); + case 16: + case "end": + return _context7.stop(); + } + }, _callee6); + })); + return _backupSingleDocument.apply(this, arguments); +} var BACKUP_STATES_BY_DB = new WeakMap(); function addToBackupStates(db, state) { if (!BACKUP_STATES_BY_DB.has(db)) { BACKUP_STATES_BY_DB.set(db, []); } - var ar = (0, _util.getFromMapOrThrow)(BACKUP_STATES_BY_DB, db); + var ar = (0, _utils.getFromMapOrThrow)(BACKUP_STATES_BY_DB, db); if (!ar) { throw (0, _rxError.newRxError)('SNH'); } @@ -237,7 +116,7 @@ var RxBackupState = /*#__PURE__*/function () { function RxBackupState(database, options) { this.isStopped = false; this.subs = []; - this.persistRunning = _util.PROMISE_RESOLVE_VOID; + this.persistRunning = _utils.PROMISE_RESOLVE_VOID; this.initialReplicationDone$ = new _rxjs.BehaviorSubject(false); this.internalWriteEvents$ = new _rxjs.Subject(); this.writeEvents$ = this.internalWriteEvents$.asObservable(); @@ -264,103 +143,181 @@ var RxBackupState = /*#__PURE__*/function () { return _this._persistOnce(); }); }; - _proto._persistOnce = function _persistOnce() { - try { + _proto._persistOnce = /*#__PURE__*/function () { + var _persistOnce2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { var _this2 = this; - return Promise.resolve((0, _fileUtil.getMeta)(_this2.options)).then(function (meta) { - return Promise.resolve(Promise.all(Object.entries(_this2.database.collections).map(function (_ref) { - try { - var collectionName = _ref[0], - collection = _ref[1]; - var primaryKey = collection.schema.primaryPath; - var processedDocuments = new Set(); - return Promise.resolve(_this2.database.requestIdlePromise()).then(function () { - function _temp3() { - meta.collectionStates[collectionName].checkpoint = lastCheckpoint; - return Promise.resolve((0, _fileUtil.setMeta)(_this2.options, meta)).then(function () {}); - } - if (!meta.collectionStates[collectionName]) { - meta.collectionStates[collectionName] = {}; - } - var lastCheckpoint = meta.collectionStates[collectionName].checkpoint; - var hasMore = true; - var _temp2 = _for(function () { - return !!hasMore && !_this2.isStopped; - }, void 0, function () { - return Promise.resolve(_this2.database.requestIdlePromise()).then(function () { - return Promise.resolve(collection.storageInstance.getChangedDocumentsSince(_this2.options.batchSize ? _this2.options.batchSize : 0, lastCheckpoint)).then(function (changesResult) { - lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint; - meta.collectionStates[collectionName].checkpoint = lastCheckpoint; - var docIds = changesResult.documents.map(function (doc) { - return doc[primaryKey]; - }).filter(function (id) { - if (processedDocuments.has(id)) { - return false; - } else { - processedDocuments.add(id); - return true; + var meta; + return _regenerator["default"].wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return (0, _fileUtil.getMeta)(this.options); + case 2: + meta = _context5.sent; + _context5.next = 5; + return Promise.all(Object.entries(this.database.collections).map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(_ref) { + var collectionName, collection, primaryKey, processedDocuments, lastCheckpoint, hasMore, _loop, _ret; + return _regenerator["default"].wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + collectionName = _ref[0], collection = _ref[1]; + primaryKey = collection.schema.primaryPath; + processedDocuments = new Set(); + _context4.next = 5; + return _this2.database.requestIdlePromise(); + case 5: + if (!meta.collectionStates[collectionName]) { + meta.collectionStates[collectionName] = {}; } - }).filter(function (elem, pos, arr) { - return arr.indexOf(elem) === pos; - }); // unique - return Promise.resolve(_this2.database.requestIdlePromise()).then(function () { - return Promise.resolve(collection.findByIds(docIds)).then(function (docs) { - if (docs.size === 0) { - hasMore = false; - return; - } - return Promise.resolve(Promise.all(Array.from(docs.values()).map(function (doc) { - try { - return Promise.resolve(backupSingleDocument(doc, _this2.options)).then(function (writtenFiles) { - _this2.internalWriteEvents$.next({ - collectionName: collection.name, - documentId: doc.primary, - files: writtenFiles, - deleted: false - }); - }); - } catch (e) { - return Promise.reject(e); + lastCheckpoint = meta.collectionStates[collectionName].checkpoint; + hasMore = true; + _loop = /*#__PURE__*/_regenerator["default"].mark(function _loop() { + var changesResult, docIds, docs; + return _regenerator["default"].wrap(function _loop$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return _this2.database.requestIdlePromise(); + case 2: + _context3.next = 4; + return collection.storageInstance.getChangedDocumentsSince(_this2.options.batchSize ? _this2.options.batchSize : 0, lastCheckpoint); + case 4: + changesResult = _context3.sent; + lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint; + meta.collectionStates[collectionName].checkpoint = lastCheckpoint; + docIds = changesResult.documents.map(function (doc) { + return doc[primaryKey]; + }).filter(function (id) { + if (processedDocuments.has(id)) { + return false; + } else { + processedDocuments.add(id); + return true; + } + }).filter(function (elem, pos, arr) { + return arr.indexOf(elem) === pos; + }); // unique + _context3.next = 10; + return _this2.database.requestIdlePromise(); + case 10: + _context3.next = 12; + return collection.findByIds(docIds).exec(); + case 12: + docs = _context3.sent; + if (!(docs.size === 0)) { + _context3.next = 16; + break; + } + hasMore = false; + return _context3.abrupt("return", "continue"); + case 16: + _context3.next = 18; + return Promise.all(Array.from(docs.values()).map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(doc) { + var writtenFiles; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return backupSingleDocument(doc, _this2.options); + case 2: + writtenFiles = _context.sent; + _this2.internalWriteEvents$.next({ + collectionName: collection.name, + documentId: doc.primary, + files: writtenFiles, + deleted: false + }); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 18: + _context3.next = 20; + return Promise.all(docIds.filter(function (docId) { + return !docs.has(docId); + }).map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(docId) { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, _fileUtil.deleteFolder)((0, _fileUtil.documentFolder)(_this2.options, docId)); + case 2: + _this2.internalWriteEvents$.next({ + collectionName: collection.name, + documentId: docId, + files: [], + deleted: true + }); + case 3: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x5) { + return _ref4.apply(this, arguments); + }; + }())); + case 20: + case "end": + return _context3.stop(); } - }))).then(function () { - // handle deleted documents - return Promise.resolve(Promise.all(docIds.filter(function (docId) { - return !docs.has(docId); - }).map(function (docId) { - try { - return Promise.resolve((0, _fileUtil.deleteFolder)((0, _fileUtil.documentFolder)(_this2.options, docId))).then(function () { - _this2.internalWriteEvents$.next({ - collectionName: collection.name, - documentId: docId, - files: [], - deleted: true - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - }); + }, _loop); }); - }); - }); - }); - }); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - if (!_this2.initialReplicationDone$.getValue()) { - _this2.initialReplicationDone$.next(true); - } - }); - }); - } catch (e) { - return Promise.reject(e); + case 9: + if (!(hasMore && !_this2.isStopped)) { + _context4.next = 16; + break; + } + return _context4.delegateYield(_loop(), "t0", 11); + case 11: + _ret = _context4.t0; + if (!(_ret === "continue")) { + _context4.next = 14; + break; + } + return _context4.abrupt("continue", 9); + case 14: + _context4.next = 9; + break; + case 16: + meta.collectionStates[collectionName].checkpoint = lastCheckpoint; + _context4.next = 19; + return (0, _fileUtil.setMeta)(_this2.options, meta); + case 19: + case "end": + return _context4.stop(); + } + }, _callee3); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }())); + case 5: + if (!this.initialReplicationDone$.getValue()) { + this.initialReplicationDone$.next(true); + } + case 6: + case "end": + return _context5.stop(); + } + }, _callee4, this); + })); + function _persistOnce() { + return _persistOnce2.apply(this, arguments); } - }; + return _persistOnce; + }(); _proto.watchForChanges = function watchForChanges() { var _this3 = this; var collections = Object.values(this.database.collections); @@ -386,13 +343,13 @@ var RxBackupState = /*#__PURE__*/function () { }; _proto.cancel = function cancel() { if (this.isStopped) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } this.isStopped = true; this.subs.forEach(function (sub) { return sub.unsubscribe(); }); - return _util.PROMISE_RESOLVE_TRUE; + return _utils.PROMISE_RESOLVE_TRUE; }; return RxBackupState; }(); diff --git a/dist/lib/plugins/backup/index.js.map b/dist/lib/plugins/backup/index.js.map index 93f4e255b7f..960b04bb3fd 100644 --- a/dist/lib/plugins/backup/index.js.map +++ b/dist/lib/plugins/backup/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","backupSingleDocument","rxDocument","options","data","toJSON","writtenFiles","docFolder","documentFolder","primary","clearFolder","fileLocation","path","join","writeJsonToFile","push","attachments","attachmentsFolder","ensureFolderExists","allAttachments","Promise","all","map","attachment","getData","content","attachmentFileLocation","id","writeToFile","BACKUP_STATES_BY_DB","WeakMap","addToBackupStates","db","has","set","ar","getFromMapOrThrow","newRxError","RxBackupState","database","isStopped","subs","persistRunning","PROMISE_RESOLVE_VOID","initialReplicationDone$","BehaviorSubject","internalWriteEvents$","Subject","writeEvents$","asObservable","batchSize","prepareFolders","persistOnce","_persistOnce","getMeta","meta","Object","entries","collections","collectionName","collection","primaryKey","schema","primaryPath","processedDocuments","Set","requestIdlePromise","collectionStates","checkpoint","lastCheckpoint","setMeta","hasMore","storageInstance","getChangedDocumentsSince","changesResult","documents","length","docIds","doc","filter","add","elem","pos","arr","indexOf","findByIds","docs","size","Array","from","values","next","name","documentId","files","deleted","docId","deleteFolder","getValue","watchForChanges","forEach","changes$","changeStream","sub","subscribe","awaitInitialBackup","firstValueFrom","pipe","cancel","PROMISE_RESOLVE_FALSE","unsubscribe","PROMISE_RESOLVE_TRUE","backup","backupState","live","RxDBBackupPlugin","rxdb","prototypes","RxDatabase","proto","hooks","preDestroyRxDatabase","after","states","get"],"sources":["../../../../src/plugins/backup/index.ts"],"sourcesContent":["import * as path from 'path';\nimport {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n filter,\n map\n} from 'rxjs/operators';\nimport { newRxError } from '../../rx-error';\nimport type {\n BackupOptions,\n RxBackupWriteEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxPlugin\n} from '../../types';\nimport {\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport {\n clearFolder,\n deleteFolder,\n documentFolder,\n ensureFolderExists,\n getMeta,\n prepareFolders,\n setMeta,\n writeJsonToFile,\n writeToFile\n} from './file-util';\n\n\n/**\n * Backups a single documents,\n * returns the paths to all written files\n */\nexport async function backupSingleDocument(\n rxDocument: RxDocument,\n options: BackupOptions\n): Promise {\n const data = rxDocument.toJSON(true);\n const writtenFiles: string[] = [];\n\n const docFolder = documentFolder(options, rxDocument.primary);\n await clearFolder(docFolder);\n\n const fileLocation = path.join(\n docFolder,\n 'document.json'\n );\n await writeJsonToFile(fileLocation, data);\n writtenFiles.push(fileLocation);\n\n if (options.attachments) {\n const attachmentsFolder = path.join(\n docFolder,\n 'attachments'\n );\n ensureFolderExists(attachmentsFolder);\n const attachments = (rxDocument as RxDocument).allAttachments();\n await Promise.all(\n attachments\n .map(async (attachment) => {\n const content = await attachment.getData();\n const attachmentFileLocation = path.join(\n attachmentsFolder,\n attachment.id\n );\n await writeToFile(attachmentFileLocation, content);\n writtenFiles.push(attachmentFileLocation);\n })\n );\n }\n\n return writtenFiles;\n}\n\nconst BACKUP_STATES_BY_DB: WeakMap = new WeakMap();\nfunction addToBackupStates(db: RxDatabase, state: RxBackupState) {\n if (!BACKUP_STATES_BY_DB.has(db)) {\n BACKUP_STATES_BY_DB.set(db, []);\n }\n const ar = getFromMapOrThrow(BACKUP_STATES_BY_DB, db);\n if (!ar) {\n throw newRxError('SNH');\n }\n ar.push(state);\n}\n\nexport class RxBackupState {\n public isStopped: boolean = false;\n private subs: Subscription[] = [];\n private persistRunning: Promise = PROMISE_RESOLVE_VOID;\n private initialReplicationDone$: BehaviorSubject = new BehaviorSubject(false as any);\n\n private readonly internalWriteEvents$: Subject = new Subject();\n public readonly writeEvents$: Observable = this.internalWriteEvents$.asObservable();\n\n constructor(\n public readonly database: RxDatabase,\n public readonly options: BackupOptions\n ) {\n if (!this.options.batchSize) {\n this.options.batchSize = 10;\n }\n addToBackupStates(database, this);\n prepareFolders(database, options);\n }\n\n /**\n * Persists all data from all collections,\n * beginning from the oldest sequence checkpoint\n * to the newest one.\n * Do not call this while it is already running.\n * Returns true if there are more documents to process\n */\n public persistOnce() {\n return this.persistRunning = this.persistRunning.then(() => this._persistOnce());\n }\n\n public async _persistOnce() {\n const meta = await getMeta(this.options);\n\n await Promise.all(\n Object\n .entries(this.database.collections)\n .map(async ([collectionName, collection]) => {\n const primaryKey = collection.schema.primaryPath;\n const processedDocuments: Set = new Set();\n\n await this.database.requestIdlePromise();\n\n if (!meta.collectionStates[collectionName]) {\n meta.collectionStates[collectionName] = {};\n }\n let lastCheckpoint = meta.collectionStates[collectionName].checkpoint;\n\n let hasMore = true;\n while (hasMore && !this.isStopped) {\n await this.database.requestIdlePromise();\n const changesResult = await collection.storageInstance.getChangedDocumentsSince(\n this.options.batchSize ? this.options.batchSize : 0,\n lastCheckpoint\n );\n lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint;\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n\n const docIds: string[] = changesResult.documents\n .map(doc => doc[primaryKey])\n .filter(id => {\n if (\n processedDocuments.has(id)\n ) {\n return false;\n } else {\n processedDocuments.add(id);\n return true;\n }\n })\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique\n await this.database.requestIdlePromise();\n\n const docs: Map = await collection.findByIds(docIds);\n if (docs.size === 0) {\n hasMore = false;\n continue;\n }\n await Promise.all(\n Array\n .from(docs.values())\n .map(async (doc) => {\n const writtenFiles = await backupSingleDocument(doc, this.options);\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: doc.primary,\n files: writtenFiles,\n deleted: false\n });\n })\n );\n // handle deleted documents\n await Promise.all(\n docIds\n .filter(docId => !docs.has(docId))\n .map(async (docId) => {\n await deleteFolder(documentFolder(this.options, docId));\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: docId,\n files: [],\n deleted: true\n });\n })\n );\n }\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n await setMeta(this.options, meta);\n })\n );\n\n if (!this.initialReplicationDone$.getValue()) {\n this.initialReplicationDone$.next(true);\n }\n }\n\n public watchForChanges() {\n const collections: RxCollection[] = Object.values(this.database.collections);\n collections.forEach(collection => {\n const changes$ = collection.storageInstance.changeStream();\n const sub = changes$.subscribe(() => {\n this.persistOnce();\n });\n this.subs.push(sub);\n });\n }\n\n /**\n * Returns a promise that resolves when the initial backup is done\n * and the filesystem is in sync with the database state\n */\n public awaitInitialBackup(): Promise {\n return firstValueFrom(\n this.initialReplicationDone$.pipe(\n filter(v => !!v),\n map(() => true)\n )\n );\n }\n\n cancel(): Promise {\n if (this.isStopped) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.isStopped = true;\n this.subs.forEach(sub => sub.unsubscribe());\n return PROMISE_RESOLVE_TRUE;\n }\n}\n\n\nexport function backup(\n this: RxDatabase,\n options: BackupOptions\n): RxBackupState {\n const backupState = new RxBackupState(this, options);\n backupState.persistOnce();\n\n if (options.live) {\n backupState.watchForChanges();\n }\n\n return backupState;\n}\n\nexport * from './file-util';\nexport const RxDBBackupPlugin: RxPlugin = {\n name: 'backup',\n rxdb: true,\n prototypes: {\n RxDatabase(proto: any) {\n proto.backup = backup;\n }\n },\n hooks: {\n preDestroyRxDatabase: {\n after: function preDestroyRxDatabase(db: RxDatabase) {\n const states = BACKUP_STATES_BY_DB.get(db);\n if (states) {\n states.forEach(state => state.cancel());\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AAOA;AAIA;AASA;AAMA;AA2OA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AA/NO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,K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;UACRA,MAAM,CAACvB,OAAO,CAAC,UAAA7H,KAAK;YAAA,OAAIA,KAAK,CAACqI,MAAM,EAAE;UAAA,EAAC;QAC3C;MACJ;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["backupSingleDocument","rxDocument","options","data","toJSON","writtenFiles","docFolder","documentFolder","primary","clearFolder","fileLocation","path","join","writeJsonToFile","push","attachments","attachmentsFolder","ensureFolderExists","allAttachments","Promise","all","map","attachment","getData","content","attachmentFileLocation","id","writeToFile","BACKUP_STATES_BY_DB","WeakMap","addToBackupStates","db","state","has","set","ar","getFromMapOrThrow","newRxError","RxBackupState","database","isStopped","subs","persistRunning","PROMISE_RESOLVE_VOID","initialReplicationDone$","BehaviorSubject","internalWriteEvents$","Subject","writeEvents$","asObservable","batchSize","prepareFolders","persistOnce","then","_persistOnce","getMeta","meta","Object","entries","collections","collectionName","collection","primaryKey","schema","primaryPath","processedDocuments","Set","requestIdlePromise","collectionStates","lastCheckpoint","checkpoint","hasMore","storageInstance","getChangedDocumentsSince","changesResult","documents","length","docIds","doc","filter","add","elem","pos","arr","indexOf","findByIds","exec","docs","size","Array","from","values","next","name","documentId","files","deleted","docId","deleteFolder","setMeta","getValue","watchForChanges","forEach","changes$","changeStream","sub","subscribe","awaitInitialBackup","firstValueFrom","pipe","v","cancel","PROMISE_RESOLVE_FALSE","unsubscribe","PROMISE_RESOLVE_TRUE","backup","backupState","live","RxDBBackupPlugin","rxdb","prototypes","RxDatabase","proto","hooks","preDestroyRxDatabase","after","states","get"],"sources":["../../../../src/plugins/backup/index.ts"],"sourcesContent":["import * as path from 'path';\nimport {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n filter,\n map\n} from 'rxjs/operators';\nimport { newRxError } from '../../rx-error';\nimport type {\n BackupOptions,\n RxBackupWriteEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxPlugin\n} from '../../types';\nimport {\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils';\nimport {\n clearFolder,\n deleteFolder,\n documentFolder,\n ensureFolderExists,\n getMeta,\n prepareFolders,\n setMeta,\n writeJsonToFile,\n writeToFile\n} from './file-util';\n\n\n/**\n * Backups a single documents,\n * returns the paths to all written files\n */\nexport async function backupSingleDocument(\n rxDocument: RxDocument,\n options: BackupOptions\n): Promise {\n const data = rxDocument.toJSON(true);\n const writtenFiles: string[] = [];\n\n const docFolder = documentFolder(options, rxDocument.primary);\n await clearFolder(docFolder);\n\n const fileLocation = path.join(\n docFolder,\n 'document.json'\n );\n await writeJsonToFile(fileLocation, data);\n writtenFiles.push(fileLocation);\n\n if (options.attachments) {\n const attachmentsFolder = path.join(\n docFolder,\n 'attachments'\n );\n ensureFolderExists(attachmentsFolder);\n const attachments = (rxDocument as RxDocument).allAttachments();\n await Promise.all(\n attachments\n .map(async (attachment) => {\n const content = await attachment.getData();\n const attachmentFileLocation = path.join(\n attachmentsFolder,\n attachment.id\n );\n await writeToFile(attachmentFileLocation, content);\n writtenFiles.push(attachmentFileLocation);\n })\n );\n }\n\n return writtenFiles;\n}\n\nconst BACKUP_STATES_BY_DB: WeakMap = new WeakMap();\nfunction addToBackupStates(db: RxDatabase, state: RxBackupState) {\n if (!BACKUP_STATES_BY_DB.has(db)) {\n BACKUP_STATES_BY_DB.set(db, []);\n }\n const ar = getFromMapOrThrow(BACKUP_STATES_BY_DB, db);\n if (!ar) {\n throw newRxError('SNH');\n }\n ar.push(state);\n}\n\nexport class RxBackupState {\n public isStopped: boolean = false;\n private subs: Subscription[] = [];\n private persistRunning: Promise = PROMISE_RESOLVE_VOID;\n private initialReplicationDone$: BehaviorSubject = new BehaviorSubject(false as any);\n\n private readonly internalWriteEvents$: Subject = new Subject();\n public readonly writeEvents$: Observable = this.internalWriteEvents$.asObservable();\n\n constructor(\n public readonly database: RxDatabase,\n public readonly options: BackupOptions\n ) {\n if (!this.options.batchSize) {\n this.options.batchSize = 10;\n }\n addToBackupStates(database, this);\n prepareFolders(database, options);\n }\n\n /**\n * Persists all data from all collections,\n * beginning from the oldest sequence checkpoint\n * to the newest one.\n * Do not call this while it is already running.\n * Returns true if there are more documents to process\n */\n public persistOnce() {\n return this.persistRunning = this.persistRunning.then(() => this._persistOnce());\n }\n\n public async _persistOnce() {\n const meta = await getMeta(this.options);\n\n await Promise.all(\n Object\n .entries(this.database.collections)\n .map(async ([collectionName, collection]) => {\n const primaryKey = collection.schema.primaryPath;\n const processedDocuments: Set = new Set();\n\n await this.database.requestIdlePromise();\n\n if (!meta.collectionStates[collectionName]) {\n meta.collectionStates[collectionName] = {};\n }\n let lastCheckpoint = meta.collectionStates[collectionName].checkpoint;\n\n let hasMore = true;\n while (hasMore && !this.isStopped) {\n await this.database.requestIdlePromise();\n const changesResult = await collection.storageInstance.getChangedDocumentsSince(\n this.options.batchSize ? this.options.batchSize : 0,\n lastCheckpoint\n );\n lastCheckpoint = changesResult.documents.length > 0 ? changesResult.checkpoint : lastCheckpoint;\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n\n const docIds: string[] = changesResult.documents\n .map(doc => doc[primaryKey])\n .filter(id => {\n if (\n processedDocuments.has(id)\n ) {\n return false;\n } else {\n processedDocuments.add(id);\n return true;\n }\n })\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique\n await this.database.requestIdlePromise();\n\n const docs: Map = await collection.findByIds(docIds).exec();\n if (docs.size === 0) {\n hasMore = false;\n continue;\n }\n await Promise.all(\n Array\n .from(docs.values())\n .map(async (doc) => {\n const writtenFiles = await backupSingleDocument(doc, this.options);\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: doc.primary,\n files: writtenFiles,\n deleted: false\n });\n })\n );\n // handle deleted documents\n await Promise.all(\n docIds\n .filter(docId => !docs.has(docId))\n .map(async (docId) => {\n await deleteFolder(documentFolder(this.options, docId));\n this.internalWriteEvents$.next({\n collectionName: collection.name,\n documentId: docId,\n files: [],\n deleted: true\n });\n })\n );\n }\n meta.collectionStates[collectionName].checkpoint = lastCheckpoint;\n await setMeta(this.options, meta);\n })\n );\n\n if (!this.initialReplicationDone$.getValue()) {\n this.initialReplicationDone$.next(true);\n }\n }\n\n public watchForChanges() {\n const collections: RxCollection[] = Object.values(this.database.collections);\n collections.forEach(collection => {\n const changes$ = collection.storageInstance.changeStream();\n const sub = changes$.subscribe(() => {\n this.persistOnce();\n });\n this.subs.push(sub);\n });\n }\n\n /**\n * Returns a promise that resolves when the initial backup is done\n * and the filesystem is in sync with the database state\n */\n public awaitInitialBackup(): Promise {\n return firstValueFrom(\n this.initialReplicationDone$.pipe(\n filter(v => !!v),\n map(() => true)\n )\n );\n }\n\n cancel(): Promise {\n if (this.isStopped) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.isStopped = true;\n this.subs.forEach(sub => sub.unsubscribe());\n return PROMISE_RESOLVE_TRUE;\n }\n}\n\n\nexport function backup(\n this: RxDatabase,\n options: BackupOptions\n): RxBackupState {\n const backupState = new RxBackupState(this, options);\n backupState.persistOnce();\n\n if (options.live) {\n backupState.watchForChanges();\n }\n\n return backupState;\n}\n\nexport * from './file-util';\nexport const RxDBBackupPlugin: RxPlugin = {\n name: 'backup',\n rxdb: true,\n prototypes: {\n RxDatabase(proto: any) {\n proto.backup = backup;\n }\n },\n hooks: {\n preDestroyRxDatabase: {\n after: function preDestroyRxDatabase(db: RxDatabase) {\n const states = BACKUP_STATES_BY_DB.get(db);\n if (states) {\n states.forEach(state => state.cancel());\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AACA;AAOA;AAIA;AASA;AAMA;AA2OA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAA4B;AAAA;AA9N5B;AACA;AACA;AACA;AAHA,SAIsBA,oBAAoB;EAAA;AAAA;AAAA;EAAA,sGAAnC,kBACH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;EAAA;AAAA;AAAA;AAIE,SAASC,MAAM,CAElBjH,OAAsB,EACT;EACb,IAAMkH,WAAW,GAAG,IAAI9E,aAAa,CAAC,IAAI,EAAEpC,OAAO,CAAC;EACpDkH,WAAW,CAAChE,WAAW,EAAE;EAEzB,IAAIlD,OAAO,CAACmH,IAAI,EAAE;IACdD,WAAW,CAACf,eAAe,EAAE;EACjC;EAEA,OAAOe,WAAW;AACtB;AAGO,IAAME,gBAA0B,GAAG;EACtCzB,IAAI,EAAE,QAAQ;EACd0B,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,sBAACC,KAAU,EAAE;MACnBA,KAAK,CAACP,MAAM,GAAGA,MAAM;IACzB;EACJ,CAAC;EACDQ,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAE,SAASD,oBAAoB,CAAC7F,EAAc,EAAE;QACjD,IAAM+F,MAAM,GAAGlG,mBAAmB,CAACmG,GAAG,CAAChG,EAAE,CAAC;QAC1C,IAAI+F,MAAM,EAAE;UACRA,MAAM,CAACxB,OAAO,CAAC,UAAAtE,KAAK;YAAA,OAAIA,KAAK,CAAC+E,MAAM,EAAE;UAAA,EAAC;QAC3C;MACJ;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/cleanup/cleanup.js b/dist/lib/plugins/cleanup/cleanup.js index c36d956468f..f6b69e98b39 100644 --- a/dist/lib/plugins/cleanup/cleanup.js +++ b/dist/lib/plugins/cleanup/cleanup.js @@ -1,279 +1,172 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.startCleanupForRxCollection = exports.runCleanupAfterDelete = exports.cleanupRxCollection = void 0; -var _util = require("../../util"); +exports.cleanupRxCollection = cleanupRxCollection; +exports.runCleanupAfterDelete = runCleanupAfterDelete; +exports.startCleanupForRxCollection = startCleanupForRxCollection; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utils = require("../../plugins/utils"); var _replication = require("../replication"); var _cleanupHelper = require("./cleanup-helper"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } +/** + * Even on multiple databases, + * the calls to RxStorage().cleanup() + * must never run in parallel. + * The cleanup is a background task which should + * not affect the performance of other, more important tasks. + */ +var RXSOTRAGE_CLEANUP_QUEUE = _utils.PROMISE_RESOLVE_TRUE; +function startCleanupForRxCollection(_x) { + return _startCleanupForRxCollection.apply(this, arguments); } -var runCleanupAfterDelete = function runCleanupAfterDelete(rxCollection, cleanupPolicy) { - try { - var _exit2 = false; - return Promise.resolve(_for(function () { - return !_exit2 && !rxCollection.destroyed; - }, void 0, function () { - return Promise.resolve(rxCollection.promiseWait(cleanupPolicy.runEach)).then(function () { - if (rxCollection.destroyed) { - _exit2 = true; - return; - } - return Promise.resolve(cleanupRxCollection(rxCollection, cleanupPolicy)).then(function () {}); - }); - })); - } catch (e) { - return Promise.reject(e); - } -}; -exports.runCleanupAfterDelete = runCleanupAfterDelete; /** * Runs the cleanup for a single RxCollection */ -var cleanupRxCollection = function cleanupRxCollection(rxCollection, cleanupPolicy) { - try { - var _exit = false; - var rxDatabase = rxCollection.database; - var storageInstance = rxCollection.storageInstance; - - // run cleanup() until it returns true - var isDone = false; - return Promise.resolve(_for(function () { - return !_exit && !isDone && !rxCollection.destroyed; - }, void 0, function () { - function _temp5() { - return Promise.resolve(rxDatabase.requestIdlePromise()).then(function () { - if (rxCollection.destroyed) { - _exit = true; - return; +function _startCleanupForRxCollection() { + _startCleanupForRxCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(rxCollection) { + var rxDatabase, cleanupPolicy; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + rxDatabase = rxCollection.database; + cleanupPolicy = Object.assign({}, _cleanupHelper.DEFAULT_CLEANUP_POLICY, rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}); + /** + * Wait until minimumDatabaseInstanceAge is reached + * or collection is destroyed. + */ + _context.next = 4; + return rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge); + case 4: + if (!rxCollection.destroyed) { + _context.next = 6; + break; + } + return _context.abrupt("return"); + case 6: + if (!cleanupPolicy.waitForLeadership) { + _context.next = 9; + break; + } + _context.next = 9; + return rxDatabase.waitForLeadership(); + case 9: + if (!rxCollection.destroyed) { + _context.next = 11; + break; } + return _context.abrupt("return"); + case 11: + _context.next = 13; + return cleanupRxCollection(rxCollection, cleanupPolicy); + case 13: + _context.next = 15; + return runCleanupAfterDelete(rxCollection, cleanupPolicy); + case 15: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _startCleanupForRxCollection.apply(this, arguments); +} +function cleanupRxCollection(_x2, _x3) { + return _cleanupRxCollection.apply(this, arguments); +} +function _cleanupRxCollection() { + _cleanupRxCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxCollection, cleanupPolicy) { + var rxDatabase, storageInstance, isDone, replicationStates; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + rxDatabase = rxCollection.database; + storageInstance = rxCollection.storageInstance; // run cleanup() until it returns true + isDone = false; + case 3: + if (!(!isDone && !rxCollection.destroyed)) { + _context2.next = 19; + break; + } + if (!cleanupPolicy.awaitReplicationsInSync) { + _context2.next = 9; + break; + } + replicationStates = _replication.REPLICATION_STATE_BY_COLLECTION.get(rxCollection); + if (!replicationStates) { + _context2.next = 9; + break; + } + _context2.next = 9; + return Promise.all(replicationStates.map(function (replicationState) { + if (!replicationState.isStopped()) { + return replicationState.awaitInSync(); + } + })); + case 9: + _context2.next = 11; + return rxDatabase.requestIdlePromise(); + case 11: + if (!rxCollection.destroyed) { + _context2.next = 13; + break; + } + return _context2.abrupt("return"); + case 13: RXSOTRAGE_CLEANUP_QUEUE = RXSOTRAGE_CLEANUP_QUEUE.then(function () { if (rxCollection.destroyed) { return true; } return storageInstance.cleanup(cleanupPolicy.minimumDeletedTime); }); - return Promise.resolve(RXSOTRAGE_CLEANUP_QUEUE).then(function (_RXSOTRAGE_CLEANUP_QU) { - isDone = _RXSOTRAGE_CLEANUP_QU; - }); - }); - } - var _temp4 = function () { - if (cleanupPolicy.awaitReplicationsInSync) { - var replicationStates = _replication.REPLICATION_STATE_BY_COLLECTION.get(rxCollection); - var _temp3 = function () { - if (replicationStates) { - return Promise.resolve(Promise.all(replicationStates.map(function (replicationState) { - if (!replicationState.isStopped()) { - return replicationState.awaitInSync(); - } - }))).then(function () {}); - } - }(); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - } - }(); - return _temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4); - })); - } catch (e) { - return Promise.reject(e); - } -}; -exports.cleanupRxCollection = cleanupRxCollection; -var startCleanupForRxCollection = function startCleanupForRxCollection(rxCollection) { - try { - var rxDatabase = rxCollection.database; - var cleanupPolicy = Object.assign({}, _cleanupHelper.DEFAULT_CLEANUP_POLICY, rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}); - - /** - * Wait until minimumDatabaseInstanceAge is reached - * or collection is destroyed. - */ - return Promise.resolve(rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge)).then(function () { - function _temp2() { - if (rxCollection.destroyed) { - return; - } - - // initially cleanup the collection - return Promise.resolve(cleanupRxCollection(rxCollection, cleanupPolicy)).then(function () { - /** - * Afterwards we listen to deletes - * and only re-run the cleanup after - * minimumDeletedTime is reached. - */ - return Promise.resolve(runCleanupAfterDelete(rxCollection, cleanupPolicy)).then(function () {}); - }); + _context2.next = 16; + return RXSOTRAGE_CLEANUP_QUEUE; + case 16: + isDone = _context2.sent; + _context2.next = 3; + break; + case 19: + case "end": + return _context2.stop(); } - if (rxCollection.destroyed) { - return; + }, _callee2); + })); + return _cleanupRxCollection.apply(this, arguments); +} +function runCleanupAfterDelete(_x4, _x5) { + return _runCleanupAfterDelete.apply(this, arguments); +} +function _runCleanupAfterDelete() { + _runCleanupAfterDelete = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(rxCollection, cleanupPolicy) { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (rxCollection.destroyed) { + _context3.next = 9; + break; + } + _context3.next = 3; + return rxCollection.promiseWait(cleanupPolicy.runEach); + case 3: + if (!rxCollection.destroyed) { + _context3.next = 5; + break; + } + return _context3.abrupt("return"); + case 5: + _context3.next = 7; + return cleanupRxCollection(rxCollection, cleanupPolicy); + case 7: + _context3.next = 0; + break; + case 9: + case "end": + return _context3.stop(); } - var _temp = function () { - if (cleanupPolicy.waitForLeadership) { - return Promise.resolve(rxDatabase.waitForLeadership()).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.startCleanupForRxCollection = startCleanupForRxCollection; -/** - * Even on multiple databases, - * the calls to RxStorage().cleanup() - * must never run in parallel. - * The cleanup is a background task which should - * not affect the performance of other, more important tasks. - */ -var RXSOTRAGE_CLEANUP_QUEUE = _util.PROMISE_RESOLVE_TRUE; + }, _callee3); + })); + return _runCleanupAfterDelete.apply(this, arguments); +} //# sourceMappingURL=cleanup.js.map \ No newline at end of file diff --git a/dist/lib/plugins/cleanup/cleanup.js.map b/dist/lib/plugins/cleanup/cleanup.js.map index a479149e1c2..c2382cca3ef 100644 --- a/dist/lib/plugins/cleanup/cleanup.js.map +++ b/dist/lib/plugins/cleanup/cleanup.js.map @@ -1 +1 @@ -{"version":3,"file":"cleanup.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","runCleanupAfterDelete","rxCollection","cleanupPolicy","destroyed","promiseWait","runEach","cleanupRxCollection","rxDatabase","database","storageInstance","isDone","requestIdlePromise","RXSOTRAGE_CLEANUP_QUEUE","cleanup","minimumDeletedTime","awaitReplicationsInSync","replicationStates","REPLICATION_STATE_BY_COLLECTION","get","Promise","all","map","replicationState","isStopped","awaitInSync","startCleanupForRxCollection","Object","assign","DEFAULT_CLEANUP_POLICY","minimumCollectionAge","waitForLeadership","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/cleanup/cleanup.ts"],"sourcesContent":["import type { RxCleanupPolicy, RxCollection } from '../../types';\nimport { PROMISE_RESOLVE_TRUE } from '../../util';\nimport { REPLICATION_STATE_BY_COLLECTION } from '../replication';\nimport { DEFAULT_CLEANUP_POLICY } from './cleanup-helper';\n\n/**\n * Even on multiple databases,\n * the calls to RxStorage().cleanup()\n * must never run in parallel.\n * The cleanup is a background task which should\n * not affect the performance of other, more important tasks.\n */\nlet RXSOTRAGE_CLEANUP_QUEUE: Promise = PROMISE_RESOLVE_TRUE;\n\nexport async function startCleanupForRxCollection(\n rxCollection: RxCollection\n) {\n const rxDatabase = rxCollection.database;\n const cleanupPolicy = Object.assign(\n {},\n DEFAULT_CLEANUP_POLICY,\n rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}\n );\n\n /**\n * Wait until minimumDatabaseInstanceAge is reached\n * or collection is destroyed.\n */\n await rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge);\n if (rxCollection.destroyed) {\n return;\n }\n\n if (cleanupPolicy.waitForLeadership) {\n await rxDatabase.waitForLeadership();\n }\n if (rxCollection.destroyed) {\n return;\n }\n\n // initially cleanup the collection\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n\n /**\n * Afterwards we listen to deletes\n * and only re-run the cleanup after\n * minimumDeletedTime is reached.\n */\n await runCleanupAfterDelete(rxCollection, cleanupPolicy);\n}\n\n/**\n * Runs the cleanup for a single RxCollection\n */\nexport async function cleanupRxCollection(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n const rxDatabase = rxCollection.database;\n const storageInstance = rxCollection.storageInstance;\n\n // run cleanup() until it returns true\n let isDone = false;\n while (!isDone && !rxCollection.destroyed) {\n if (cleanupPolicy.awaitReplicationsInSync) {\n const replicationStates = REPLICATION_STATE_BY_COLLECTION.get(rxCollection);\n if (replicationStates) {\n await Promise.all(\n replicationStates.map(replicationState => {\n if (!replicationState.isStopped()) {\n return replicationState.awaitInSync();\n }\n })\n );\n }\n }\n\n await rxDatabase.requestIdlePromise();\n if (rxCollection.destroyed) {\n return;\n }\n RXSOTRAGE_CLEANUP_QUEUE = RXSOTRAGE_CLEANUP_QUEUE\n .then(() => {\n if (rxCollection.destroyed) {\n return true;\n }\n return storageInstance.cleanup(cleanupPolicy.minimumDeletedTime);\n });\n isDone = await RXSOTRAGE_CLEANUP_QUEUE;\n }\n}\n\nexport async function runCleanupAfterDelete(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n while (!rxCollection.destroyed) {\n await rxCollection.promiseWait(cleanupPolicy.runEach);\n if (rxCollection.destroyed) {\n return;\n }\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n }\n}\n"],"mappings":";;;;;;AACA;AACA;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BAAgB,CAACC,SAAS,EAAE,EAAE;kBAC/B,OAAOD,gBAAgB,CAACE,WAAW,EAAE;gBACzC;cACJ,CAAC,CAAC,CACL;YAAA;UAAA;UAAA;QAAA;MAAA;MAAA;IAgBb,CAAC;EACL,CAAC;IAAA;EAAA;AAAA;AAAA;AAAA,IA5EqBC,2BAA2B,YAA3BA,2BAA2B,CAC7CxB,YAA0B;EAAA,IAC5B;IACE,IAAMM,UAAU,GAAGN,YAAY,CAACO,QAAQ;IACxC,IAAMN,aAAa,GAAGwB,MAAM,CAACC,MAAM,CAC/B,CAAC,CAAC,EACFC,qCAAsB,EACtBrB,UAAU,CAACL,aAAa,GAAGK,UAAU,CAACL,aAAa,GAAG,CAAC,CAAC,CAC3D;;IAED;AACJ;AACA;AACA;IAHI,uBAIMD,YAAY,CAACG,WAAW,CAACF,aAAa,CAAC2B,oBAAoB,CAAC;MAAA;QAQlE,IAAI5B,YAAY,CAACE,SAAS,EAAE;UACxB;QACJ;;QAEA;QAAA,uBACMG,mBAAmB,CAACL,YAAY,EAAEC,aAAa,CAAC;UAEtD;AACJ;AACA;AACA;AACA;UAJI,uBAKMF,qBAAqB,CAACC,YAAY,EAAEC,aAAa,CAAC;QAAA;MAAA;MAnBxD,IAAID,YAAY,CAACE,SAAS,EAAE;QACxB;MACJ;MAAC;QAAA,IAEGD,aAAa,CAAC4B,iBAAiB;UAAA,uBACzBvB,UAAU,CAACuB,iBAAiB,EAAE;QAAA;MAAA;MAAA;IAAA;EAe5C,CAAC;IAAA;EAAA;AAAA;AAAA;AA5CD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIlB,uBAAyC,GAAGmB,0BAAoB"} \ No newline at end of file +{"version":3,"file":"cleanup.js","names":["RXSOTRAGE_CLEANUP_QUEUE","PROMISE_RESOLVE_TRUE","startCleanupForRxCollection","rxCollection","rxDatabase","database","cleanupPolicy","Object","assign","DEFAULT_CLEANUP_POLICY","promiseWait","minimumCollectionAge","destroyed","waitForLeadership","cleanupRxCollection","runCleanupAfterDelete","storageInstance","isDone","awaitReplicationsInSync","replicationStates","REPLICATION_STATE_BY_COLLECTION","get","Promise","all","map","replicationState","isStopped","awaitInSync","requestIdlePromise","then","cleanup","minimumDeletedTime","runEach"],"sources":["../../../../src/plugins/cleanup/cleanup.ts"],"sourcesContent":["import type { RxCleanupPolicy, RxCollection } from '../../types';\nimport { PROMISE_RESOLVE_TRUE } from '../../plugins/utils';\nimport { REPLICATION_STATE_BY_COLLECTION } from '../replication';\nimport { DEFAULT_CLEANUP_POLICY } from './cleanup-helper';\n\n/**\n * Even on multiple databases,\n * the calls to RxStorage().cleanup()\n * must never run in parallel.\n * The cleanup is a background task which should\n * not affect the performance of other, more important tasks.\n */\nlet RXSOTRAGE_CLEANUP_QUEUE: Promise = PROMISE_RESOLVE_TRUE;\n\nexport async function startCleanupForRxCollection(\n rxCollection: RxCollection\n) {\n const rxDatabase = rxCollection.database;\n const cleanupPolicy = Object.assign(\n {},\n DEFAULT_CLEANUP_POLICY,\n rxDatabase.cleanupPolicy ? rxDatabase.cleanupPolicy : {}\n );\n\n /**\n * Wait until minimumDatabaseInstanceAge is reached\n * or collection is destroyed.\n */\n await rxCollection.promiseWait(cleanupPolicy.minimumCollectionAge);\n if (rxCollection.destroyed) {\n return;\n }\n\n if (cleanupPolicy.waitForLeadership) {\n await rxDatabase.waitForLeadership();\n }\n if (rxCollection.destroyed) {\n return;\n }\n\n // initially cleanup the collection\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n\n /**\n * Afterwards we listen to deletes\n * and only re-run the cleanup after\n * minimumDeletedTime is reached.\n */\n await runCleanupAfterDelete(rxCollection, cleanupPolicy);\n}\n\n/**\n * Runs the cleanup for a single RxCollection\n */\nexport async function cleanupRxCollection(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n const rxDatabase = rxCollection.database;\n const storageInstance = rxCollection.storageInstance;\n\n // run cleanup() until it returns true\n let isDone = false;\n while (!isDone && !rxCollection.destroyed) {\n if (cleanupPolicy.awaitReplicationsInSync) {\n const replicationStates = REPLICATION_STATE_BY_COLLECTION.get(rxCollection);\n if (replicationStates) {\n await Promise.all(\n replicationStates.map(replicationState => {\n if (!replicationState.isStopped()) {\n return replicationState.awaitInSync();\n }\n })\n );\n }\n }\n\n await rxDatabase.requestIdlePromise();\n if (rxCollection.destroyed) {\n return;\n }\n RXSOTRAGE_CLEANUP_QUEUE = RXSOTRAGE_CLEANUP_QUEUE\n .then(() => {\n if (rxCollection.destroyed) {\n return true;\n }\n return storageInstance.cleanup(cleanupPolicy.minimumDeletedTime);\n });\n isDone = await RXSOTRAGE_CLEANUP_QUEUE;\n }\n}\n\nexport async function runCleanupAfterDelete(\n rxCollection: RxCollection,\n cleanupPolicy: RxCleanupPolicy\n) {\n while (!rxCollection.destroyed) {\n await rxCollection.promiseWait(cleanupPolicy.runEach);\n if (rxCollection.destroyed) {\n return;\n }\n await cleanupRxCollection(rxCollection, cleanupPolicy);\n }\n}\n"],"mappings":";;;;;;;;;;;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIA,uBAAyC,GAAGC,2BAAoB;AAAC,SAE/CC,2BAA2B;EAAA;AAAA;AAqCjD;AACA;AACA;AAFA;EAAA,6GArCO,iBACHC,YAA0B;IAAA;IAAA;MAAA;QAAA;UAEpBC,UAAU,GAAGD,YAAY,CAACE,QAAQ;UAClCC,aAAa,GAAGC,MAAM,CAACC,MAAM,CAC/B,CAAC,CAAC,EACFC,qCAAsB,EACtBL,UAAU,CAACE,aAAa,GAAGF,UAAU,CAACE,aAAa,GAAG,CAAC,CAAC,CAC3D;UAED;AACJ;AACA;AACA;UAHI;UAAA,OAIMH,YAAY,CAACO,WAAW,CAACJ,aAAa,CAACK,oBAAoB,CAAC;QAAA;UAAA,KAC9DR,YAAY,CAACS,SAAS;YAAA;YAAA;UAAA;UAAA;QAAA;UAAA,KAItBN,aAAa,CAACO,iBAAiB;YAAA;YAAA;UAAA;UAA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,CAACxB,aAAa,CAACyB,kBAAkB,CAAC;UACpE,CAAC,CAAC;UAAC;UAAA,OACQ/B,uBAAuB;QAAA;UAAtCiB,MAAM;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAEb;EAAA;AAAA;AAAA,SAEqBF,qBAAqB;EAAA;AAAA;AAAA;EAAA,uGAApC,kBACHZ,YAA0B,EAC1BG,aAA8B;IAAA;MAAA;QAAA;UAAA,IAEtBH,YAAY,CAACS,SAAS;YAAA;YAAA;UAAA;UAAA;UAAA,OACpBT,YAAY,CAACO,WAAW,CAACJ,aAAa,CAAC0B,OAAO,CAAC;QAAA;UAAA,KACjD7B,YAAY,CAACS,SAAS;YAAA;YAAA;UAAA;UAAA;QAAA;UAAA;UAAA,OAGpBE,mBAAmB,CAACX,YAAY,EAAEG,aAAa,CAAC;QAAA;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAE7D;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/crdt/index.js b/dist/lib/plugins/crdt/index.js index 20289715f25..162d41cc268 100644 --- a/dist/lib/plugins/crdt/index.js +++ b/dist/lib/plugins/crdt/index.js @@ -8,112 +8,152 @@ exports.RxDBcrdtPlugin = exports.RX_CRDT_CONTEXT = void 0; exports.getCRDTConflictHandler = getCRDTConflictHandler; exports.getCRDTSchemaPart = getCRDTSchemaPart; exports.hashCRDTOperations = hashCRDTOperations; -exports.insertCRDT = void 0; +exports.insertCRDT = insertCRDT; exports.mergeCRDTFields = mergeCRDTFields; exports.rebuildFromCRDT = rebuildFromCRDT; exports.sortOperationComparator = sortOperationComparator; -exports.updateCRDT = void 0; +exports.updateCRDT = updateCRDT; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxError = require("../../rx-error"); var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); var _objectPath = _interopRequireDefault(require("object-path")); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _modifyjs = _interopRequireDefault(require("modifyjs")); var _ = require("../.."); -var insertCRDT = function insertCRDT(entry) { - try { - var _this2 = this; - entry = _.overwritable.deepFreezeWhenDevMode(entry); - var jsonSchema = _this2.schema.jsonSchema; - if (!jsonSchema.crdt) { - throw (0, _rxError.newRxError)('CRDT1', { - schema: jsonSchema, - queryObj: entry - }); - } - var crdtOptions = (0, _util.ensureNotFalsy)(jsonSchema.crdt); - return Promise.resolve(_this2.database.storageToken).then(function (storageToken) { - var operation = { - body: Array.isArray(entry) ? entry : [entry], - creator: storageToken, - time: (0, _util.now)() - }; - var insertData = {}; - insertData = runOperationOnDocument(_this2.database.storage.statics, _this2.schema.jsonSchema, insertData, operation); - var crdtDocField = { - operations: [], - hash: '' - }; - _objectPath["default"].set(insertData, crdtOptions.field, crdtDocField); - var lastAr = [operation]; - crdtDocField.operations.push(lastAr); - crdtDocField.hash = hashCRDTOperations(_this2.database.hashFunction, crdtDocField); - return Promise.resolve(_this2.insert(insertData)["catch"](function (err) { - try { - if (err.code === 'COL19') { - // was a conflict, update document instead of inserting - return Promise.resolve(_this2.findOne(err.parameters.id).exec(true)).then(function (doc) { - return doc.updateCRDT(entry); - }); - } else { - throw err; - } - } catch (e) { - return Promise.reject(e); - } - })); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.insertCRDT = insertCRDT; -var updateCRDT = function updateCRDT(entry) { - try { +function updateCRDT(_x) { + return _updateCRDT.apply(this, arguments); +} +function _updateCRDT() { + _updateCRDT = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(entry) { var _this = this; - entry = _.overwritable.deepFreezeWhenDevMode(entry); - var jsonSchema = _this.collection.schema.jsonSchema; - if (!jsonSchema.crdt) { - throw (0, _rxError.newRxError)('CRDT1', { - schema: jsonSchema, - queryObj: entry - }); - } - var crdtOptions = (0, _util.ensureNotFalsy)(jsonSchema.crdt); - return Promise.resolve(_this.collection.database.storageToken).then(function (storageToken) { - return _this.atomicUpdate(function (docData, rxDoc) { - var crdtDocField = (0, _util.clone)(_objectPath["default"].get(docData, crdtOptions.field)); - var operation = { - body: Array.isArray(entry) ? entry : [entry], - creator: storageToken, - time: (0, _util.now)() - }; - - /** - * A new write will ALWAYS be an operation in the last - * array which was non existing before. - */ - var lastAr = [operation]; - crdtDocField.operations.push(lastAr); - crdtDocField.hash = hashCRDTOperations(_this.collection.database.hashFunction, crdtDocField); - var newDocData = (0, _util.clone)(rxDoc.toJSON()); - newDocData._deleted = rxDoc._data._deleted; - newDocData = runOperationOnDocument(_this.collection.database.storage.statics, _this.collection.schema.jsonSchema, newDocData, operation); - _objectPath["default"].set(newDocData, crdtOptions.field, crdtDocField); + var jsonSchema, crdtOptions, storageToken; + return _regenerator["default"].wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + entry = _.overwritable.deepFreezeWhenDevMode(entry); + jsonSchema = this.collection.schema.jsonSchema; + if (jsonSchema.crdt) { + _context3.next = 4; + break; + } + throw (0, _rxError.newRxError)('CRDT1', { + schema: jsonSchema, + queryObj: entry + }); + case 4: + crdtOptions = (0, _utils.ensureNotFalsy)(jsonSchema.crdt); + _context3.next = 7; + return this.collection.database.storageToken; + case 7: + storageToken = _context3.sent; + return _context3.abrupt("return", this.incrementalModify(function (docData) { + var crdtDocField = (0, _utils.clone)(_objectPath["default"].get(docData, crdtOptions.field)); + var operation = { + body: (0, _utils.toArray)(entry), + creator: storageToken, + time: (0, _utils.now)() + }; - // add other internal fields - var fullDocData = Object.assign({ - _attachments: rxDoc._data._attachments, - _meta: rxDoc._data._meta, - _rev: rxDoc._data._rev - }, newDocData); - return fullDocData; - }, RX_CRDT_CONTEXT); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.updateCRDT = updateCRDT; + /** + * A new write will ALWAYS be an operation in the last + * array which was non existing before. + */ + var lastAr = [operation]; + crdtDocField.operations.push(lastAr); + crdtDocField.hash = hashCRDTOperations(_this.collection.database.hashFunction, crdtDocField); + docData = runOperationOnDocument(_this.collection.database.storage.statics, _this.collection.schema.jsonSchema, docData, operation); + _objectPath["default"].set(docData, crdtOptions.field, crdtDocField); + return docData; + }, RX_CRDT_CONTEXT)); + case 9: + case "end": + return _context3.stop(); + } + }, _callee2, this); + })); + return _updateCRDT.apply(this, arguments); +} +function insertCRDT(_x2) { + return _insertCRDT.apply(this, arguments); +} +function _insertCRDT() { + _insertCRDT = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(entry) { + var _this2 = this; + var jsonSchema, crdtOptions, storageToken, operation, insertData, crdtDocField, lastAr, result; + return _regenerator["default"].wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + entry = _.overwritable.deepFreezeWhenDevMode(entry); + jsonSchema = this.schema.jsonSchema; + if (jsonSchema.crdt) { + _context5.next = 4; + break; + } + throw (0, _rxError.newRxError)('CRDT1', { + schema: jsonSchema, + queryObj: entry + }); + case 4: + crdtOptions = (0, _utils.ensureNotFalsy)(jsonSchema.crdt); + _context5.next = 7; + return this.database.storageToken; + case 7: + storageToken = _context5.sent; + operation = { + body: Array.isArray(entry) ? entry : [entry], + creator: storageToken, + time: (0, _utils.now)() + }; + insertData = {}; + insertData = runOperationOnDocument(this.database.storage.statics, this.schema.jsonSchema, insertData, operation); + crdtDocField = { + operations: [], + hash: '' + }; + _objectPath["default"].set(insertData, crdtOptions.field, crdtDocField); + lastAr = [operation]; + crdtDocField.operations.push(lastAr); + crdtDocField.hash = hashCRDTOperations(this.database.hashFunction, crdtDocField); + _context5.next = 18; + return this.insert(insertData)["catch"]( /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(err) { + var doc; + return _regenerator["default"].wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(err.code === 'CONFLICT')) { + _context4.next = 7; + break; + } + _context4.next = 3; + return _this2.findOne(err.parameters.id).exec(true); + case 3: + doc = _context4.sent; + return _context4.abrupt("return", doc.updateCRDT(entry)); + case 7: + throw err; + case 8: + case "end": + return _context4.stop(); + } + }, _callee3); + })); + return function (_x4) { + return _ref6.apply(this, arguments); + }; + }()); + case 18: + result = _context5.sent; + return _context5.abrupt("return", result); + case 20: + case "end": + return _context5.stop(); + } + }, _callee4, this); + })); + return _insertCRDT.apply(this, arguments); +} function sortOperationComparator(a, b) { return a.creator > b.creator ? 1 : -1; } @@ -123,7 +163,7 @@ function runOperationOnDocument(storageStatics, schema, docData, operation) { var isMatching; if (entryPart.selector) { var preparedQuery = storageStatics.prepareQuery(schema, { - selector: (0, _util.ensureNotFalsy)(entryPart.selector), + selector: (0, _utils.ensureNotFalsy)(entryPart.selector), sort: [], skip: 0 }); @@ -246,7 +286,7 @@ function rebuildFromCRDT(storageStatics, schema, docData, crdts) { var base = { _deleted: false }; - _objectPath["default"].set(base, (0, _util.ensureNotFalsy)(schema.crdt).field, crdts); + _objectPath["default"].set(base, (0, _utils.ensureNotFalsy)(schema.crdt).field, crdts); crdts.operations.forEach(function (operations) { operations.forEach(function (op) { base = runOperationOnDocument(storageStatics, schema, base, op); @@ -255,9 +295,9 @@ function rebuildFromCRDT(storageStatics, schema, docData, crdts) { return base; } function getCRDTConflictHandler(hashFunction, storageStatics, schema) { - var crdtOptions = (0, _util.ensureNotFalsy)(schema.crdt); + var crdtOptions = (0, _utils.ensureNotFalsy)(schema.crdt); var crdtField = crdtOptions.field; - var getCRDTValue = (0, _util.objectPathMonad)(crdtField); + var getCRDTValue = (0, _utils.objectPathMonad)(crdtField); var conflictHandler = function conflictHandler(i, _context) { var newDocCrdt = getCRDTValue(i.newDocumentState); var masterDocCrdt = getCRDTValue(i.realMasterState); @@ -296,10 +336,10 @@ var RxDBcrdtPlugin = { } }); }; - var oldAtomicPatch = proto.atomicPatch; - proto.atomicPatch = function (patch) { + var oldincrementalPatch = proto.incrementalPatch; + proto.incrementalPatch = function (patch) { if (!this.collection.schema.jsonSchema.crdt) { - return oldAtomicPatch.bind(this)(patch); + return oldincrementalPatch.bind(this)(patch); } return this.updateCRDT({ ifMatch: { @@ -307,13 +347,13 @@ var RxDBcrdtPlugin = { } }); }; - var oldAtomicUpdate = proto.atomicUpdate; - proto.atomicUpdate = function (fn, context) { + var oldincrementalModify = proto.incrementalModify; + proto.incrementalModify = function (fn, context) { if (!this.collection.schema.jsonSchema.crdt) { - return oldAtomicUpdate.bind(this)(fn); + return oldincrementalModify.bind(this)(fn); } if (context === RX_CRDT_CONTEXT) { - return oldAtomicUpdate.bind(this)(fn); + return oldincrementalModify.bind(this)(fn); } else { throw (0, _rxError.newRxError)('CRDT2', { id: this.primary, @@ -350,9 +390,9 @@ var RxDBcrdtPlugin = { if (!collection.schema.jsonSchema.crdt) { return; } - var crdtOptions = (0, _util.ensureNotFalsy)(collection.schema.jsonSchema.crdt); + var crdtOptions = (0, _utils.ensureNotFalsy)(collection.schema.jsonSchema.crdt); var crdtField = crdtOptions.field; - var getCrdt = (0, _util.objectPathMonad)(crdtOptions.field); + var getCrdt = (0, _utils.objectPathMonad)(crdtOptions.field); /** * In dev-mode we have to ensure that all document writes @@ -363,7 +403,7 @@ var RxDBcrdtPlugin = { var bulkWriteBefore = collection.storageInstance.bulkWrite.bind(collection.storageInstance); collection.storageInstance.bulkWrite = function (writes, context) { writes.forEach(function (write) { - var newDocState = (0, _util.clone)(write.document); + var newDocState = (0, _utils.clone)(write.document); var crdts = getCrdt(newDocState); var rebuild = rebuildFromCRDT(collection.database.storage.statics, collection.schema.jsonSchema, newDocState, crdts); function docWithoutMeta(doc) { @@ -397,40 +437,52 @@ var RxDBcrdtPlugin = { }; } var bulkInsertBefore = collection.bulkInsert.bind(collection); - collection.bulkInsert = function (docsData) { - try { - return Promise.resolve(collection.database.storageToken).then(function (storageToken) { - var useDocsData = docsData.map(function (docData) { - var setMe = {}; - Object.entries(docData).forEach(function (_ref4) { - var key = _ref4[0], - value = _ref4[1]; - if (!key.startsWith('_') && key !== crdtField) { - setMe[key] = value; - } - }); - var crdtOperations = { - operations: [[{ - creator: storageToken, - body: [{ - ifMatch: { - $set: setMe + collection.bulkInsert = /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(docsData) { + var storageToken, useDocsData; + return _regenerator["default"].wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return collection.database.storageToken; + case 2: + storageToken = _context2.sent; + useDocsData = docsData.map(function (docData) { + var setMe = {}; + Object.entries(docData).forEach(function (_ref5) { + var key = _ref5[0], + value = _ref5[1]; + if (!key.startsWith('_') && key !== crdtField) { + setMe[key] = value; } - }], - time: (0, _util.now)() - }]], - hash: '' - }; - crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations); - _objectPath["default"].set(docData, crdtOptions.field, crdtOperations); - return docData; - }); - return bulkInsertBefore(useDocsData); - }); - } catch (e) { - return Promise.reject(e); - } - }; + }); + var crdtOperations = { + operations: [[{ + creator: storageToken, + body: [{ + ifMatch: { + $set: setMe + } + }], + time: (0, _utils.now)() + }]], + hash: '' + }; + crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations); + _objectPath["default"].set(docData, crdtOptions.field, crdtOperations); + return docData; + }); + return _context2.abrupt("return", bulkInsertBefore(useDocsData)); + case 5: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return function (_x3) { + return _ref4.apply(this, arguments); + }; + }(); } } } diff --git a/dist/lib/plugins/crdt/index.js.map b/dist/lib/plugins/crdt/index.js.map index a44ee247feb..773229fdf0a 100644 --- a/dist/lib/plugins/crdt/index.js.map +++ b/dist/lib/plugins/crdt/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["insertCRDT","entry","overwritable","deepFreezeWhenDevMode","jsonSchema","schema","crdt","newRxError","queryObj","crdtOptions","ensureNotFalsy","database","storageToken","operation","body","Array","isArray","creator","time","now","insertData","runOperationOnDocument","storage","statics","crdtDocField","operations","hash","objectPath","set","field","lastAr","push","hashCRDTOperations","hashFunction","insert","err","code","findOne","parameters","id","exec","doc","updateCRDT","collection","atomicUpdate","docData","rxDoc","clone","get","newDocData","toJSON","_deleted","_data","fullDocData","Object","assign","_attachments","_meta","_rev","RX_CRDT_CONTEXT","sortOperationComparator","a","b","storageStatics","entryParts","forEach","entryPart","isMatching","selector","preparedQuery","prepareQuery","sort","skip","matcher","getQueryMatcher","ifMatch","modifyjs","ifNotMatch","crdts","hashObj","map","op","JSON","stringify","getCRDTSchemaPart","operationSchema","type","properties","items","additionalProperties","minItems","minimum","maximum","multipleOf","required","minLength","mergeCRDTFields","crdtsA","crdtsB","length","ret","row","index","mergedOps","ids","Set","add","has","rebuildFromCRDT","base","getCRDTConflictHandler","crdtField","getCRDTValue","objectPathMonad","conflictHandler","i","_context","newDocCrdt","newDocumentState","masterDocCrdt","realMasterState","Promise","resolve","isEqual","mergedCrdt","mergedDoc","documentData","RxDBcrdtPlugin","name","rxdb","prototypes","RxDocument","proto","oldRemove","remove","bind","$set","oldAtomicPatch","atomicPatch","patch","oldAtomicUpdate","fn","context","primary","args","RxCollection","hooks","preCreateRxCollection","after","data","createRxCollection","getCrdt","isDevMode","bulkWriteBefore","storageInstance","bulkWrite","writes","write","newDocState","document","rebuild","docWithoutMeta","entries","k","v","startsWith","deepEqual","recalculatedHash","bulkInsertBefore","bulkInsert","docsData","useDocsData","setMe","key","value","crdtOperations"],"sources":["../../../../src/plugins/crdt/index.ts"],"sourcesContent":["import { newRxError } from '../../rx-error';\nimport deepEqual from 'fast-deep-equal';\nimport objectPath from 'object-path';\nimport type {\n CRDTDocumentField,\n CRDTEntry,\n CRDTOperation,\n HashFunction,\n JsonSchema,\n RxConflictHandler,\n RxConflictHandlerInput,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n RxPlugin,\n RxStorageStatics,\n WithDeleted\n} from '../../types';\nimport {\n clone,\n ensureNotFalsy,\n now,\n objectPathMonad\n} from '../../util';\nimport modifyjs from 'modifyjs';\nimport {\n overwritable,\n RxCollection,\n RxDocumentWriteData,\n RxError\n} from '../..';\n\n\n\nexport async function updateCRDT(\n this: RxDocument,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.collection.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.collection.database.storageToken;\n\n return this.atomicUpdate((docData, rxDoc) => {\n const crdtDocField: CRDTDocumentField = clone(objectPath.get(docData as any, crdtOptions.field));\n const operation: CRDTOperation = {\n body: Array.isArray(entry) ? entry : [entry],\n creator: storageToken,\n time: now()\n };\n\n /**\n * A new write will ALWAYS be an operation in the last\n * array which was non existing before.\n */\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.collection.database.hashFunction, crdtDocField);\n\n let newDocData: WithDeleted = clone(rxDoc.toJSON()) as any;\n newDocData._deleted = rxDoc._data._deleted;\n newDocData = runOperationOnDocument(\n this.collection.database.storage.statics,\n this.collection.schema.jsonSchema,\n newDocData,\n operation\n );\n objectPath.set(newDocData, crdtOptions.field, crdtDocField);\n\n // add other internal fields\n const fullDocData: RxDocumentData = Object.assign({\n _attachments: rxDoc._data._attachments,\n _meta: rxDoc._data._meta,\n _rev: rxDoc._data._rev\n }, newDocData);\n\n return fullDocData;\n }, RX_CRDT_CONTEXT);\n}\n\n\nexport async function insertCRDT(\n this: RxCollection,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.database.storageToken;\n const operation: CRDTOperation = {\n body: Array.isArray(entry) ? entry : [entry],\n creator: storageToken,\n time: now()\n };\n\n let insertData: RxDocumentWriteData = {} as any;\n insertData = runOperationOnDocument(\n this.database.storage.statics,\n this.schema.jsonSchema,\n insertData as any,\n operation\n ) as any;\n const crdtDocField: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n objectPath.set(insertData as any, crdtOptions.field, crdtDocField);\n\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.database.hashFunction, crdtDocField);\n\n const result = await this.insert(insertData).catch(async (err: RxError) => {\n if (err.code === 'COL19') {\n // was a conflict, update document instead of inserting\n const doc = await this.findOne(err.parameters.id).exec(true);\n return doc.updateCRDT(entry);\n } else {\n throw err;\n }\n });\n return result;\n}\n\n\nexport function sortOperationComparator(a: CRDTOperation, b: CRDTOperation) {\n return a.creator > b.creator ? 1 : -1;\n}\n\n\nfunction runOperationOnDocument(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n operation: CRDTOperation\n): WithDeleted {\n const entryParts = operation.body;\n entryParts.forEach(entryPart => {\n let isMatching: boolean;\n if (entryPart.selector) {\n const preparedQuery = storageStatics.prepareQuery(schema, {\n selector: ensureNotFalsy(entryPart.selector),\n sort: [],\n skip: 0\n });\n const matcher = storageStatics.getQueryMatcher(schema, preparedQuery);\n isMatching = matcher(docData as any);\n } else {\n isMatching = true;\n }\n if (isMatching) {\n if (entryPart.ifMatch) {\n docData = modifyjs(docData, entryPart.ifMatch);\n }\n } else {\n if (entryPart.ifNotMatch) {\n docData = modifyjs(docData, entryPart.ifNotMatch);\n }\n }\n });\n return docData;\n}\n\nexport function hashCRDTOperations(\n hashFunction: HashFunction,\n crdts: CRDTDocumentField\n): string {\n const hashObj = crdts.operations.map((operations) => {\n return operations.map(op => op.creator);\n });\n const hash = hashFunction(JSON.stringify(hashObj));\n return hash;\n}\n\nexport function getCRDTSchemaPart(): JsonSchema> {\n const operationSchema: JsonSchema> = {\n type: 'object',\n properties: {\n body: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n selector: {\n type: 'object'\n },\n ifMatch: {\n type: 'object'\n },\n ifNotMatch: {\n type: 'object'\n }\n },\n additionalProperties: false\n },\n minItems: 1\n },\n creator: {\n type: 'string'\n },\n time: {\n type: 'number',\n minimum: 1,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n additionalProperties: false,\n required: [\n 'body',\n 'creator',\n 'time'\n ]\n };\n return {\n type: 'object',\n properties: {\n operations: {\n type: 'array',\n items: {\n type: 'array',\n items: operationSchema\n }\n },\n hash: {\n type: 'string',\n // set a minLength to not accidentally store an empty string\n minLength: 2\n }\n },\n additionalProperties: false,\n required: ['operations', 'hash']\n };\n}\n\n\nexport function mergeCRDTFields(\n hashFunction: HashFunction,\n crdtsA: CRDTDocumentField,\n crdtsB: CRDTDocumentField\n): CRDTDocumentField {\n\n // the value with most operations must be A to\n // ensure we not miss out rows when iterating over both fields.\n if (crdtsA.operations.length < crdtsB.operations.length) {\n [crdtsA, crdtsB] = [crdtsB, crdtsA];\n }\n\n const ret: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n crdtsA.operations.forEach((row, index) => {\n let mergedOps: CRDTOperation[] = [];\n const ids = new Set(); // used to deduplicate\n\n row.forEach(op => {\n ids.add(op.creator);\n mergedOps.push(op);\n });\n if (crdtsB.operations[index]) {\n crdtsB.operations[index].forEach(op => {\n if (!ids.has(op.creator)) {\n mergedOps.push(op);\n }\n });\n }\n mergedOps = mergedOps.sort(sortOperationComparator);\n ret.operations[index] = mergedOps;\n });\n\n\n ret.hash = hashCRDTOperations(hashFunction, ret);\n return ret;\n}\n\nexport function rebuildFromCRDT(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n crdts: CRDTDocumentField\n): WithDeleted {\n let base: WithDeleted = {\n _deleted: false\n } as any;\n objectPath.set(base, ensureNotFalsy(schema.crdt).field, crdts);\n crdts.operations.forEach(operations => {\n operations.forEach(op => {\n base = runOperationOnDocument(\n storageStatics,\n schema,\n base,\n op\n );\n });\n });\n return base;\n}\n\n\nexport function getCRDTConflictHandler(\n hashFunction: HashFunction,\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>\n): RxConflictHandler {\n const crdtOptions = ensureNotFalsy(schema.crdt);\n const crdtField = crdtOptions.field;\n const getCRDTValue = objectPathMonad, CRDTDocumentField>(crdtField);\n\n const conflictHandler: RxConflictHandler = (\n i: RxConflictHandlerInput,\n _context: string\n ) => {\n const newDocCrdt = getCRDTValue(i.newDocumentState);\n const masterDocCrdt = getCRDTValue(i.realMasterState);\n\n if (newDocCrdt.hash === masterDocCrdt.hash) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n const mergedCrdt = mergeCRDTFields(hashFunction, newDocCrdt, masterDocCrdt);\n const mergedDoc = rebuildFromCRDT(\n storageStatics,\n schema,\n i.newDocumentState,\n mergedCrdt\n );\n return Promise.resolve({\n isEqual: false,\n documentData: mergedDoc\n });\n };\n\n return conflictHandler;\n}\n\n\nexport const RX_CRDT_CONTEXT = 'rx-crdt';\n\nexport const RxDBcrdtPlugin: RxPlugin = {\n name: 'crdt',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.updateCRDT = updateCRDT;\n\n const oldRemove = proto.remove;\n proto.remove = function (this: RxDocument) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldRemove.bind(this)();\n }\n return this.updateCRDT({\n ifMatch: {\n $set: {\n _deleted: true\n }\n }\n });\n };\n\n const oldAtomicPatch = proto.atomicPatch;\n proto.atomicPatch = function (this: RxDocument, patch: any) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldAtomicPatch.bind(this)(patch);\n }\n return this.updateCRDT({\n ifMatch: {\n $set: patch\n }\n });\n };\n const oldAtomicUpdate = proto.atomicUpdate;\n proto.atomicUpdate = function (fn: any, context: string) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldAtomicUpdate.bind(this)(fn);\n }\n if (context === RX_CRDT_CONTEXT) {\n return oldAtomicUpdate.bind(this)(fn);\n } else {\n throw newRxError('CRDT2', {\n id: this.primary,\n args: { context }\n });\n }\n };\n },\n RxCollection: (proto: any) => {\n proto.insertCRDT = insertCRDT;\n }\n },\n overwritable: {},\n hooks: {\n preCreateRxCollection: {\n after: (data) => {\n if (!data.schema.crdt) {\n return;\n }\n if (data.conflictHandler) {\n throw newRxError('CRDT3', {\n collection: data.name,\n schema: data.schema\n });\n }\n data.conflictHandler = getCRDTConflictHandler(\n data.database.hashFunction,\n data.database.storage.statics,\n data.schema\n );\n }\n },\n createRxCollection: {\n after: ({ collection }) => {\n if (!collection.schema.jsonSchema.crdt) {\n return;\n }\n\n const crdtOptions = ensureNotFalsy(collection.schema.jsonSchema.crdt);\n const crdtField = crdtOptions.field;\n const getCrdt = objectPathMonad>(crdtOptions.field);\n\n /**\n * In dev-mode we have to ensure that all document writes\n * have the correct crdt state so that nothing is missed out\n * or could accidentally do non-crdt writes to the document.\n */\n if (overwritable.isDevMode()) {\n const bulkWriteBefore = collection.storageInstance.bulkWrite.bind(collection.storageInstance);\n collection.storageInstance.bulkWrite = function (writes, context) {\n\n writes.forEach(write => {\n const newDocState: typeof write.document = clone(write.document);\n const crdts = getCrdt(newDocState);\n\n const rebuild = rebuildFromCRDT(\n collection.database.storage.statics,\n collection.schema.jsonSchema,\n newDocState,\n crdts\n );\n\n function docWithoutMeta(doc: any) {\n const ret: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (!k.startsWith('_')) {\n ret[k] = v;\n }\n });\n return ret;\n }\n if (!deepEqual(docWithoutMeta(newDocState), docWithoutMeta(rebuild))) {\n throw newRxError('SNH', {\n document: newDocState\n });\n }\n const recalculatedHash = hashCRDTOperations(collection.database.hashFunction, crdts);\n if (crdts.hash !== recalculatedHash) {\n throw newRxError('SNH', {\n document: newDocState,\n args: { hash: crdts.hash, recalculatedHash }\n });\n }\n });\n\n return bulkWriteBefore(writes, context);\n };\n }\n\n\n const bulkInsertBefore = collection.bulkInsert.bind(collection);\n collection.bulkInsert = async function (docsData: any[]) {\n const storageToken = await collection.database.storageToken;\n const useDocsData = docsData.map(docData => {\n const setMe: Partial> = {};\n Object.entries(docData).forEach(([key, value]) => {\n if (\n !key.startsWith('_') &&\n key !== crdtField\n ) {\n setMe[key] = value;\n }\n });\n\n const crdtOperations: CRDTDocumentField = {\n operations: [\n [{\n creator: storageToken,\n body: [{\n ifMatch: {\n $set: setMe\n }\n }],\n time: now()\n }]\n ],\n hash: ''\n };\n crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations);\n objectPath.set(docData, crdtOptions.field, crdtOperations);\n return docData;\n });\n return bulkInsertBefore(useDocsData);\n };\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AACA;AAgBA;AAMA;AACA;AAKe,IA0DOA,UAAU,YAAVA,UAAU,CAE5BC,KAAoD;EAAA,IACtD;IAAA,aAGqB,IAAI;IAFvBA,KAAK,GAAGC,cAAY,CAACC,qBAAqB,CAACF,KAAK,CAAQ;IAExD,IAAMG,UAAU,GAAG,OAAKC,MAAM,CAACD,UAAU;IACzC,IAAI,CAACA,UAAU,CAACE,IAAI,EAAE;MAClB,MAAM,IAAAC,mBAAU,EAAC,OAAO,EAAE;QACtBF,MAAM,EAAED,UAAU;QAClBI,QAAQ,EAAEP;MACd,CAAC,CAAC;IACN;IACA,IAAMQ,WAAW,GAAG,IAAAC,oBAAc,EAACN,UAAU,CAACE,IAAI,CAAC;IAAC,uBACzB,OAAKK,QAAQ,CAACC,YAAY,iBAA/CA,YAAY;MAClB,IAAMC,SAAmC,GAAG;QACxCC,IAAI,EAAEC,KAAK,CAACC,OAAO,CAACf,KAAK,CAAC,GAAGA,KAAK,GAAG,CAACA,KAAK,CAAC;QAC5CgB,OAAO,EAAEL,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CAAC;QAC/DA,UAAU,CAAC8H,UAAU,aAAmBC,QAAe;UAAA,IAAE;YAAA,uBAC1B/H,UAAU,CAAChC,QAAQ,CAACC,YAAY,iBAArDA,YAAY;cAClB,IAAM+J,WAAW,GAAGD,QAAQ,CAAC1F,GAAG,CAAC,UAAAnC,OAAO,EAAI;gBACxC,IAAM+H,KAAmC,GAAG,CAAC,CAAC;gBAC9CtH,MAAM,CAAC4G,OAAO,CAACrH,OAAO,CAAC,CAACoB,OAAO,CAAC,iBAAkB;kBAAA,IAAhB4G,GAAG;oBAAEC,KAAK;kBACxC,IACI,CAACD,GAAG,CAACR,UAAU,CAAC,GAAG,CAAC,IACpBQ,GAAG,KAAK9D,SAAS,EACnB;oBACE6D,KAAK,CAACC,GAAG,CAAC,GAAGC,KAAK;kBACtB;gBACJ,CAAC,CAAC;gBAEF,IAAMC,cAAsC,GAAG;kBAC3CtJ,UAAU,EAAE,CACR,CAAC;oBACGR,OAAO,EAAEL,YAAY;oBACrBE,IAAI,EAAE,CAAC;sBACH6D,OAAO,EAAE;wBACL6D,IAAI,EAAEoC;sBACV;oBACJ,CAAC,CAAC;oBACF1J,IAAI,EAAE,IAAAC,SAAG;kBACb,CAAC,CAAC,CACL;kBACDO,IAAI,EAAE;gBACV,CAAC;gBACDqJ,cAAc,CAACrJ,IAAI,GAAGM,kBAAkB,CAACW,UAAU,CAAChC,QAAQ,CAACsB,YAAY,EAAE8I,cAAc,CAAC;gBAC1FpJ,sBAAU,CAACC,GAAG,CAACiB,OAAO,EAAEpC,WAAW,CAACoB,KAAK,EAAEkJ,cAAc,CAAC;gBAC1D,OAAOlI,OAAO;cAClB,CAAC,CAAC;cACF,OAAO2H,gBAAgB,CAACG,WAAW,CAAC;YAAC;UACzC,CAAC;YAAA;UAAA;QAAA;MACL;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["updateCRDT","entry","overwritable","deepFreezeWhenDevMode","jsonSchema","collection","schema","crdt","newRxError","queryObj","crdtOptions","ensureNotFalsy","database","storageToken","incrementalModify","docData","crdtDocField","clone","objectPath","get","field","operation","body","toArray","creator","time","now","lastAr","operations","push","hash","hashCRDTOperations","hashFunction","runOperationOnDocument","storage","statics","set","RX_CRDT_CONTEXT","insertCRDT","Array","isArray","insertData","insert","err","code","findOne","parameters","id","exec","doc","result","sortOperationComparator","a","b","storageStatics","entryParts","forEach","entryPart","isMatching","selector","preparedQuery","prepareQuery","sort","skip","matcher","getQueryMatcher","ifMatch","modifyjs","ifNotMatch","crdts","hashObj","map","op","JSON","stringify","getCRDTSchemaPart","operationSchema","type","properties","items","additionalProperties","minItems","minimum","maximum","multipleOf","required","minLength","mergeCRDTFields","crdtsA","crdtsB","length","ret","row","index","mergedOps","ids","Set","add","has","rebuildFromCRDT","base","_deleted","getCRDTConflictHandler","crdtField","getCRDTValue","objectPathMonad","conflictHandler","i","_context","newDocCrdt","newDocumentState","masterDocCrdt","realMasterState","Promise","resolve","isEqual","mergedCrdt","mergedDoc","documentData","RxDBcrdtPlugin","name","rxdb","prototypes","RxDocument","proto","oldRemove","remove","bind","$set","oldincrementalPatch","incrementalPatch","patch","oldincrementalModify","fn","context","primary","args","RxCollection","hooks","preCreateRxCollection","after","data","createRxCollection","getCrdt","isDevMode","bulkWriteBefore","storageInstance","bulkWrite","writes","write","newDocState","document","rebuild","docWithoutMeta","Object","entries","k","v","startsWith","deepEqual","recalculatedHash","bulkInsertBefore","bulkInsert","docsData","useDocsData","setMe","key","value","crdtOperations"],"sources":["../../../../src/plugins/crdt/index.ts"],"sourcesContent":["import { newRxError } from '../../rx-error';\nimport deepEqual from 'fast-deep-equal';\nimport objectPath from 'object-path';\nimport type {\n CRDTDocumentField,\n CRDTEntry,\n CRDTOperation,\n HashFunction,\n JsonSchema,\n RxConflictHandler,\n RxConflictHandlerInput,\n RxDocument,\n RxDocumentData,\n RxJsonSchema,\n RxPlugin,\n RxStorageStatics,\n WithDeleted\n} from '../../types';\nimport {\n clone,\n ensureNotFalsy,\n now,\n objectPathMonad,\n toArray\n} from '../../plugins/utils';\nimport modifyjs from 'modifyjs';\nimport {\n overwritable,\n RxCollection,\n RxDocumentWriteData,\n RxError\n} from '../..';\n\n\n\nexport async function updateCRDT(\n this: RxDocument,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.collection.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.collection.database.storageToken;\n\n return this.incrementalModify((docData) => {\n const crdtDocField: CRDTDocumentField = clone(objectPath.get(docData as any, crdtOptions.field));\n const operation: CRDTOperation = {\n body: toArray(entry),\n creator: storageToken,\n time: now()\n };\n\n /**\n * A new write will ALWAYS be an operation in the last\n * array which was non existing before.\n */\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.collection.database.hashFunction, crdtDocField);\n\n docData = runOperationOnDocument(\n this.collection.database.storage.statics,\n this.collection.schema.jsonSchema,\n docData,\n operation\n );\n objectPath.set(docData, crdtOptions.field, crdtDocField);\n return docData;\n }, RX_CRDT_CONTEXT);\n}\n\n\nexport async function insertCRDT(\n this: RxCollection,\n entry: CRDTEntry | CRDTEntry[]\n) {\n entry = overwritable.deepFreezeWhenDevMode(entry) as any;\n\n const jsonSchema = this.schema.jsonSchema;\n if (!jsonSchema.crdt) {\n throw newRxError('CRDT1', {\n schema: jsonSchema,\n queryObj: entry\n });\n }\n const crdtOptions = ensureNotFalsy(jsonSchema.crdt);\n const storageToken = await this.database.storageToken;\n const operation: CRDTOperation = {\n body: Array.isArray(entry) ? entry : [entry],\n creator: storageToken,\n time: now()\n };\n\n let insertData: RxDocumentWriteData = {} as any;\n insertData = runOperationOnDocument(\n this.database.storage.statics,\n this.schema.jsonSchema,\n insertData as any,\n operation\n ) as any;\n const crdtDocField: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n objectPath.set(insertData as any, crdtOptions.field, crdtDocField);\n\n const lastAr: CRDTOperation[] = [operation];\n crdtDocField.operations.push(lastAr);\n crdtDocField.hash = hashCRDTOperations(this.database.hashFunction, crdtDocField);\n\n const result = await this.insert(insertData).catch(async (err: RxError) => {\n if (err.code === 'CONFLICT') {\n // was a conflict, update document instead of inserting\n const doc = await this.findOne(err.parameters.id).exec(true);\n return doc.updateCRDT(entry);\n } else {\n throw err;\n }\n });\n return result;\n}\n\n\nexport function sortOperationComparator(a: CRDTOperation, b: CRDTOperation) {\n return a.creator > b.creator ? 1 : -1;\n}\n\n\nfunction runOperationOnDocument(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n operation: CRDTOperation\n): WithDeleted {\n const entryParts = operation.body;\n entryParts.forEach(entryPart => {\n let isMatching: boolean;\n if (entryPart.selector) {\n const preparedQuery = storageStatics.prepareQuery(schema, {\n selector: ensureNotFalsy(entryPart.selector),\n sort: [],\n skip: 0\n });\n const matcher = storageStatics.getQueryMatcher(schema, preparedQuery);\n isMatching = matcher(docData as any);\n } else {\n isMatching = true;\n }\n if (isMatching) {\n if (entryPart.ifMatch) {\n docData = modifyjs(docData, entryPart.ifMatch);\n }\n } else {\n if (entryPart.ifNotMatch) {\n docData = modifyjs(docData, entryPart.ifNotMatch);\n }\n }\n });\n return docData;\n}\n\nexport function hashCRDTOperations(\n hashFunction: HashFunction,\n crdts: CRDTDocumentField\n): string {\n const hashObj = crdts.operations.map((operations) => {\n return operations.map(op => op.creator);\n });\n const hash = hashFunction(JSON.stringify(hashObj));\n return hash;\n}\n\nexport function getCRDTSchemaPart(): JsonSchema> {\n const operationSchema: JsonSchema> = {\n type: 'object',\n properties: {\n body: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n selector: {\n type: 'object'\n },\n ifMatch: {\n type: 'object'\n },\n ifNotMatch: {\n type: 'object'\n }\n },\n additionalProperties: false\n },\n minItems: 1\n },\n creator: {\n type: 'string'\n },\n time: {\n type: 'number',\n minimum: 1,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n additionalProperties: false,\n required: [\n 'body',\n 'creator',\n 'time'\n ]\n };\n return {\n type: 'object',\n properties: {\n operations: {\n type: 'array',\n items: {\n type: 'array',\n items: operationSchema\n }\n },\n hash: {\n type: 'string',\n // set a minLength to not accidentally store an empty string\n minLength: 2\n }\n },\n additionalProperties: false,\n required: ['operations', 'hash']\n };\n}\n\n\nexport function mergeCRDTFields(\n hashFunction: HashFunction,\n crdtsA: CRDTDocumentField,\n crdtsB: CRDTDocumentField\n): CRDTDocumentField {\n\n // the value with most operations must be A to\n // ensure we not miss out rows when iterating over both fields.\n if (crdtsA.operations.length < crdtsB.operations.length) {\n [crdtsA, crdtsB] = [crdtsB, crdtsA];\n }\n\n const ret: CRDTDocumentField = {\n operations: [],\n hash: ''\n };\n crdtsA.operations.forEach((row, index) => {\n let mergedOps: CRDTOperation[] = [];\n const ids = new Set(); // used to deduplicate\n\n row.forEach(op => {\n ids.add(op.creator);\n mergedOps.push(op);\n });\n if (crdtsB.operations[index]) {\n crdtsB.operations[index].forEach(op => {\n if (!ids.has(op.creator)) {\n mergedOps.push(op);\n }\n });\n }\n mergedOps = mergedOps.sort(sortOperationComparator);\n ret.operations[index] = mergedOps;\n });\n\n\n ret.hash = hashCRDTOperations(hashFunction, ret);\n return ret;\n}\n\nexport function rebuildFromCRDT(\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>,\n docData: WithDeleted,\n crdts: CRDTDocumentField\n): WithDeleted {\n let base: WithDeleted = {\n _deleted: false\n } as any;\n objectPath.set(base, ensureNotFalsy(schema.crdt).field, crdts);\n crdts.operations.forEach(operations => {\n operations.forEach(op => {\n base = runOperationOnDocument(\n storageStatics,\n schema,\n base,\n op\n );\n });\n });\n return base;\n}\n\n\nexport function getCRDTConflictHandler(\n hashFunction: HashFunction,\n storageStatics: RxStorageStatics,\n schema: RxJsonSchema>\n): RxConflictHandler {\n const crdtOptions = ensureNotFalsy(schema.crdt);\n const crdtField = crdtOptions.field;\n const getCRDTValue = objectPathMonad, CRDTDocumentField>(crdtField);\n\n const conflictHandler: RxConflictHandler = (\n i: RxConflictHandlerInput,\n _context: string\n ) => {\n const newDocCrdt = getCRDTValue(i.newDocumentState);\n const masterDocCrdt = getCRDTValue(i.realMasterState);\n\n if (newDocCrdt.hash === masterDocCrdt.hash) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n const mergedCrdt = mergeCRDTFields(hashFunction, newDocCrdt, masterDocCrdt);\n const mergedDoc = rebuildFromCRDT(\n storageStatics,\n schema,\n i.newDocumentState,\n mergedCrdt\n );\n return Promise.resolve({\n isEqual: false,\n documentData: mergedDoc\n });\n };\n\n return conflictHandler;\n}\n\n\nexport const RX_CRDT_CONTEXT = 'rx-crdt';\n\nexport const RxDBcrdtPlugin: RxPlugin = {\n name: 'crdt',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.updateCRDT = updateCRDT;\n\n const oldRemove = proto.remove;\n proto.remove = function (this: RxDocument) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldRemove.bind(this)();\n }\n return this.updateCRDT({\n ifMatch: {\n $set: {\n _deleted: true\n }\n }\n });\n };\n\n const oldincrementalPatch = proto.incrementalPatch;\n proto.incrementalPatch = function (this: RxDocument, patch: any) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldincrementalPatch.bind(this)(patch);\n }\n return this.updateCRDT({\n ifMatch: {\n $set: patch\n }\n });\n };\n const oldincrementalModify = proto.incrementalModify;\n proto.incrementalModify = function (fn: any, context: string) {\n if (!this.collection.schema.jsonSchema.crdt) {\n return oldincrementalModify.bind(this)(fn);\n }\n if (context === RX_CRDT_CONTEXT) {\n return oldincrementalModify.bind(this)(fn);\n } else {\n throw newRxError('CRDT2', {\n id: this.primary,\n args: { context }\n });\n }\n };\n },\n RxCollection: (proto: any) => {\n proto.insertCRDT = insertCRDT;\n }\n },\n overwritable: {},\n hooks: {\n preCreateRxCollection: {\n after: (data) => {\n if (!data.schema.crdt) {\n return;\n }\n if (data.conflictHandler) {\n throw newRxError('CRDT3', {\n collection: data.name,\n schema: data.schema\n });\n }\n data.conflictHandler = getCRDTConflictHandler(\n data.database.hashFunction,\n data.database.storage.statics,\n data.schema\n );\n }\n },\n createRxCollection: {\n after: ({ collection }) => {\n if (!collection.schema.jsonSchema.crdt) {\n return;\n }\n\n const crdtOptions = ensureNotFalsy(collection.schema.jsonSchema.crdt);\n const crdtField = crdtOptions.field;\n const getCrdt = objectPathMonad>(crdtOptions.field);\n\n /**\n * In dev-mode we have to ensure that all document writes\n * have the correct crdt state so that nothing is missed out\n * or could accidentally do non-crdt writes to the document.\n */\n if (overwritable.isDevMode()) {\n const bulkWriteBefore = collection.storageInstance.bulkWrite.bind(collection.storageInstance);\n collection.storageInstance.bulkWrite = function (writes, context) {\n\n writes.forEach(write => {\n const newDocState: typeof write.document = clone(write.document);\n const crdts = getCrdt(newDocState);\n\n const rebuild = rebuildFromCRDT(\n collection.database.storage.statics,\n collection.schema.jsonSchema,\n newDocState,\n crdts\n );\n\n function docWithoutMeta(doc: any) {\n const ret: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (!k.startsWith('_')) {\n ret[k] = v;\n }\n });\n return ret;\n }\n if (!deepEqual(docWithoutMeta(newDocState), docWithoutMeta(rebuild))) {\n throw newRxError('SNH', {\n document: newDocState\n });\n }\n const recalculatedHash = hashCRDTOperations(collection.database.hashFunction, crdts);\n if (crdts.hash !== recalculatedHash) {\n throw newRxError('SNH', {\n document: newDocState,\n args: { hash: crdts.hash, recalculatedHash }\n });\n }\n });\n\n return bulkWriteBefore(writes, context);\n };\n }\n\n\n const bulkInsertBefore = collection.bulkInsert.bind(collection);\n collection.bulkInsert = async function (docsData: any[]) {\n const storageToken = await collection.database.storageToken;\n const useDocsData = docsData.map(docData => {\n const setMe: Partial> = {};\n Object.entries(docData).forEach(([key, value]) => {\n if (\n !key.startsWith('_') &&\n key !== crdtField\n ) {\n setMe[key] = value;\n }\n });\n\n const crdtOperations: CRDTDocumentField = {\n operations: [\n [{\n creator: storageToken,\n body: [{\n ifMatch: {\n $set: setMe\n }\n }],\n time: now()\n }]\n ],\n hash: ''\n };\n crdtOperations.hash = hashCRDTOperations(collection.database.hashFunction, crdtOperations);\n objectPath.set(docData, crdtOptions.field, crdtOperations);\n return docData;\n });\n return bulkInsertBefore(useDocsData);\n };\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAgBA;AAOA;AACA;AAKe,SAIOA,UAAU;EAAA;AAAA;AAAA;EAAA,4FAAzB,kBAEHC,KAAoD;IAAA;IAAA;IAAA;MAAA;QAAA;UAEpDA,KAAK,GAAGC,cAAY,CAACC,qBAAqB,CAACF,KAAK,CAAQ;UAElDG,UAAU,GAAG,IAAI,CAACC,UAAU,CAACC,MAAM,CAACF,UAAU;UAAA,IAC/CA,UAAU,CAACG,IAAI;YAAA;YAAA;UAAA;UAAA,MACV,IAAAC,mBAAU,EAAC,OAAO,EAAE;YACtBF,MAAM,EAAEF,UAAU;YAClBK,QAAQ,EAAER;UACd,CAAC,CAAC;QAAA;UAEAS,WAAW,GAAG,IAAAC,qBAAc,EAACP,UAAU,CAACG,IAAI,CAAC;UAAA;UAAA,OACxB,IAAI,CAACF,UAAU,CAACO,QAAQ,CAACC,YAAY;QAAA;UAA1DA,YAAY;UAAA,kCAEX,IAAI,CAACC,iBAAiB,CAAC,UAACC,OAAO,EAAK;YACvC,IAAMC,YAA0C,GAAG,IAAAC,YAAK,EAACC,sBAAU,CAACC,GAAG,CAACJ,OAAO,EAASL,WAAW,CAACU,KAAK,CAAC,CAAC;YAC3G,IAAMC,SAAmC,GAAG;cACxCC,IAAI,EAAE,IAAAC,cAAO,EAACtB,KAAK,CAAC;cACpBuB,OAAO,EAAEX,YAAY;cACrBY,IAAI,EAAE,I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AAG,CAAC,CAAC;oBAC9CX,MAAM,CAACC,OAAO,CAAC5I,OAAO,CAAC,CAACyC,OAAO,CAAC,iBAAkB;sBAAA,IAAhB8G,GAAG;wBAAEC,KAAK;sBACxC,IACI,CAACD,GAAG,CAACR,UAAU,CAAC,GAAG,CAAC,IACpBQ,GAAG,KAAK/D,SAAS,EACnB;wBACE8D,KAAK,CAACC,GAAG,CAAC,GAAGC,KAAK;sBACtB;oBACJ,CAAC,CAAC;oBAEF,IAAMC,cAAsC,GAAG;sBAC3C5I,UAAU,EAAE,CACR,CAAC;wBACGJ,OAAO,EAAEX,YAAY;wBACrBS,IAAI,EAAE,CAAC;0BACH4C,OAAO,EAAE;4BACL8D,IAAI,EAAEqC;0BACV;wBACJ,CAAC,CAAC;wBACF5I,IAAI,EAAE,IAAAC,UAAG;sBACb,CAAC,CAAC,CACL;sBACDI,IAAI,EAAE;oBACV,CAAC;oBACD0I,cAAc,CAAC1I,IAAI,GAAGC,kBAAkB,CAAC1B,UAAU,CAACO,QAAQ,CAACoB,YAAY,EAAEwI,cAAc,CAAC;oBAC1FtJ,sBAAU,CAACkB,GAAG,CAACrB,OAAO,EAAEL,WAAW,CAACU,KAAK,EAAEoJ,cAAc,CAAC;oBAC1D,OAAOzJ,OAAO;kBAClB,CAAC,CAAC;kBAAA,kCACKkJ,gBAAgB,CAACG,WAAW,CAAC;gBAAA;gBAAA;kBAAA;cAAA;YAAA;UAAA,CACvC;UAAA;YAAA;UAAA;QAAA;MACL;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/dev-mode/check-query.js b/dist/lib/plugins/dev-mode/check-query.js index b89990d4f2e..99a2792ace0 100644 --- a/dist/lib/plugins/dev-mode/check-query.js +++ b/dist/lib/plugins/dev-mode/check-query.js @@ -10,7 +10,7 @@ exports.checkQuery = checkQuery; var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); var _rxError = require("../../rx-error"); var _pouchdbSelectorCore = require("pouchdb-selector-core"); -var _dexie = require("../dexie"); +var _storageDexie = require("../storage-dexie"); /** * accidentally passing a non-valid object into the query params * is very hard to debug especially when queries are observed @@ -74,6 +74,7 @@ function checkMangoQuery(args) { }); } }); + /** * ensure if custom index is set, * it is also defined in the schema @@ -105,9 +106,29 @@ function checkMangoQuery(args) { }); } } + + /** + * Ensure that sort only runs on known fields + * TODO also check nested fields + */ + if (args.mangoQuery.sort) { + args.mangoQuery.sort.map(function (sortPart) { + return Object.keys(sortPart)[0]; + }).filter(function (field) { + return !field.includes('.'); + }).forEach(function (field) { + if (!schemaTopLevelFields.includes(field)) { + throw (0, _rxError.newRxError)('QU13', { + schema: schema, + field: field, + query: args.mangoQuery + }); + } + }); + } } function areSelectorsSatisfiedByIndex(schema, query) { - var preparedQuery = _dexie.RxStorageDexieStatics.prepareQuery(schema, query); + var preparedQuery = _storageDexie.RxStorageDexieStatics.prepareQuery(schema, query); return preparedQuery.queryPlan.selectorSatisfiedByIndex; } //# sourceMappingURL=check-query.js.map \ No newline at end of file diff --git a/dist/lib/plugins/dev-mode/check-query.js.map b/dist/lib/plugins/dev-mode/check-query.js.map index 70e2de55c87..4171724b6ad 100644 --- a/dist/lib/plugins/dev-mode/check-query.js.map +++ b/dist/lib/plugins/dev-mode/check-query.js.map @@ -1 +1 @@ -{"version":3,"file":"check-query.js","names":["checkQuery","args","isPlainObject","Object","prototype","toString","call","queryObj","newRxTypeError","op","collection","name","validKeys","keys","forEach","key","includes","limit","skip","newRxError","query","checkMangoQuery","schema","rxQuery","jsonSchema","massagedSelector","massageSelector","mangoQuery","selector","schemaTopLevelFields","properties","filter","fieldOrOperator","startsWith","field","schemaIndexes","indexes","index","isInSchema","find","schemaIndex","deepEqual","areSelectorsSatisfiedByIndex","database","allowSlowCount","preparedQuery","RxStorageDexieStatics","prepareQuery","queryPlan","selectorSatisfiedByIndex"],"sources":["../../../../src/plugins/dev-mode/check-query.ts"],"sourcesContent":["import type {\n RxPluginPreCreateRxQueryArgs,\n MangoQuery,\n RxPluginPrePrepareQueryArgs,\n DexiePreparedQuery,\n FilledMangoQuery,\n RxJsonSchema,\n RxDocumentData,\n MangoQuerySelector\n} from '../../types';\nimport deepEqual from 'fast-deep-equal';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport {\n massageSelector\n} from 'pouchdb-selector-core';\nimport { RxStorageDexieStatics } from '../dexie';\n\n/**\n * accidentally passing a non-valid object into the query params\n * is very hard to debug especially when queries are observed\n * This is why we do some checks here in dev-mode\n */\nexport function checkQuery(args: RxPluginPreCreateRxQueryArgs) {\n const isPlainObject = Object.prototype.toString.call(args.queryObj) === '[object Object]';\n if (!isPlainObject) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj\n });\n }\n\n const validKeys: (keyof MangoQuery)[] = [\n 'selector',\n 'limit',\n 'skip',\n 'sort',\n 'index'\n ];\n Object.keys(args.queryObj).forEach(key => {\n if (!(validKeys as string[]).includes(key)) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj,\n key,\n args: {\n validKeys\n }\n });\n }\n });\n\n // do not allow skip or limit for count queries\n if (\n args.op === 'count' &&\n (\n args.queryObj.limit ||\n args.queryObj.skip\n )\n ) {\n throw newRxError(\n 'QU15',\n {\n collection: args.collection.name,\n query: args.queryObj\n }\n );\n }\n}\n\n\nexport function checkMangoQuery(args: RxPluginPrePrepareQueryArgs) {\n const schema = args.rxQuery.collection.schema.jsonSchema;\n\n /**\n * Ensure that all top level fields are included in the schema.\n * TODO this check can be augmented to also check sub-fields.\n */\n const massagedSelector: MangoQuerySelector = massageSelector(args.mangoQuery.selector);\n const schemaTopLevelFields = Object.keys(schema.properties);\n Object.keys(massagedSelector)\n // do not check operators\n .filter(fieldOrOperator => !fieldOrOperator.startsWith('$'))\n // skip this check on non-top-level fields\n .filter(field => !field.includes('.'))\n .forEach(field => {\n if (!schemaTopLevelFields.includes(field)) {\n throw newRxError('QU13', {\n schema,\n field,\n query: args.mangoQuery,\n });\n }\n });\n /**\n * ensure if custom index is set,\n * it is also defined in the schema\n */\n const schemaIndexes = schema.indexes ? schema.indexes : [];\n const index = args.mangoQuery.index;\n if (index) {\n const isInSchema = schemaIndexes.find(schemaIndex => deepEqual(schemaIndex, index));\n if (!isInSchema) {\n throw newRxError(\n 'QU12',\n {\n collection: args.rxQuery.collection.name,\n query: args.mangoQuery,\n schema\n }\n );\n }\n }\n\n\n /**\n * Ensure that a count() query can only be used\n * with selectors that are fully satisfied by the used index.\n */\n if (args.rxQuery.op === 'count') {\n if (\n !areSelectorsSatisfiedByIndex(\n args.rxQuery.collection.schema.jsonSchema,\n args.mangoQuery\n ) &&\n !args.rxQuery.collection.database.allowSlowCount\n ) {\n throw newRxError('QU14', {\n collection: args.rxQuery.collection,\n query: args.mangoQuery\n });\n }\n }\n}\n\n\nexport function areSelectorsSatisfiedByIndex(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): boolean {\n const preparedQuery: DexiePreparedQuery = RxStorageDexieStatics.prepareQuery(\n schema,\n query\n );\n return preparedQuery.queryPlan.selectorSatisfiedByIndex;\n}\n"],"mappings":";;;;;;;;;AAUA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AACA;AACO,SAASA,UAAU,CAACC,IAAkC,EAAE;EAC3D,IAAMC,aAAa,GAAGC,MAAM,CAACC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACL,IAAI,CAACM,QAAQ,CAAC,KAAK,iBAAiB;EACzF,IAAI,CAACL,aAAa,EAAE;IAChB,MAAM,IAAAM,uBAAc,EAAC,MAAM,EAAE;MACzBC,EAAE,EAAER,IAAI,CAACQ,EAAE;MACXC,UAAU,EAAET,IAAI,CAACS,UAAU,CAACC,IAAI;MAChCJ,QAAQ,EAAEN,IAAI,CAACM;IACnB,CAAC,CAAC;EACN;EAEA,IAAMK,SAA+B,GAAG,CACpC,UAAU,EACV,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,CACV;E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,UAAU,EAAET,IAAI,CAACsB,OAAO,CAACb,UAAU;QACnCU,KAAK,EAAEnB,IAAI,CAAC0B;MAChB,CAAC,CAAC;IACN;EACJ;AACJ;AAGO,SAASe,4BAA4B,CACxCpB,MAA+C,EAC/CF,KAAkC,EAC3B;EACP,IAAMyB,aAAsC,GAAGC,4BAAqB,CAACC,YAAY,CAC7EzB,MAAM,EACNF,KAAK,CACR;EACD,OAAOyB,aAAa,CAACG,SAAS,CAACC,wBAAwB;AAC3D"} \ No newline at end of file +{"version":3,"file":"check-query.js","names":["checkQuery","args","isPlainObject","Object","prototype","toString","call","queryObj","newRxTypeError","op","collection","name","validKeys","keys","forEach","key","includes","limit","skip","newRxError","query","checkMangoQuery","schema","rxQuery","jsonSchema","massagedSelector","massageSelector","mangoQuery","selector","schemaTopLevelFields","properties","filter","fieldOrOperator","startsWith","field","schemaIndexes","indexes","index","isInSchema","find","schemaIndex","deepEqual","areSelectorsSatisfiedByIndex","database","allowSlowCount","sort","map","sortPart","preparedQuery","RxStorageDexieStatics","prepareQuery","queryPlan","selectorSatisfiedByIndex"],"sources":["../../../../src/plugins/dev-mode/check-query.ts"],"sourcesContent":["import type {\n RxPluginPreCreateRxQueryArgs,\n MangoQuery,\n RxPluginPrePrepareQueryArgs,\n DexiePreparedQuery,\n FilledMangoQuery,\n RxJsonSchema,\n RxDocumentData,\n MangoQuerySelector\n} from '../../types';\nimport deepEqual from 'fast-deep-equal';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport {\n massageSelector\n} from 'pouchdb-selector-core';\nimport { RxStorageDexieStatics } from '../storage-dexie';\n\n/**\n * accidentally passing a non-valid object into the query params\n * is very hard to debug especially when queries are observed\n * This is why we do some checks here in dev-mode\n */\nexport function checkQuery(args: RxPluginPreCreateRxQueryArgs) {\n const isPlainObject = Object.prototype.toString.call(args.queryObj) === '[object Object]';\n if (!isPlainObject) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj\n });\n }\n\n const validKeys: (keyof MangoQuery)[] = [\n 'selector',\n 'limit',\n 'skip',\n 'sort',\n 'index'\n ];\n Object.keys(args.queryObj).forEach(key => {\n if (!(validKeys as string[]).includes(key)) {\n throw newRxTypeError('QU11', {\n op: args.op,\n collection: args.collection.name,\n queryObj: args.queryObj,\n key,\n args: {\n validKeys\n }\n });\n }\n });\n\n // do not allow skip or limit for count queries\n if (\n args.op === 'count' &&\n (\n args.queryObj.limit ||\n args.queryObj.skip\n )\n ) {\n throw newRxError(\n 'QU15',\n {\n collection: args.collection.name,\n query: args.queryObj\n }\n );\n }\n}\n\n\nexport function checkMangoQuery(args: RxPluginPrePrepareQueryArgs) {\n const schema = args.rxQuery.collection.schema.jsonSchema;\n\n /**\n * Ensure that all top level fields are included in the schema.\n * TODO this check can be augmented to also check sub-fields.\n */\n const massagedSelector: MangoQuerySelector = massageSelector(args.mangoQuery.selector);\n const schemaTopLevelFields = Object.keys(schema.properties);\n Object.keys(massagedSelector)\n // do not check operators\n .filter(fieldOrOperator => !fieldOrOperator.startsWith('$'))\n // skip this check on non-top-level fields\n .filter(field => !field.includes('.'))\n .forEach(field => {\n if (!schemaTopLevelFields.includes(field)) {\n throw newRxError('QU13', {\n schema,\n field,\n query: args.mangoQuery,\n });\n }\n });\n\n /**\n * ensure if custom index is set,\n * it is also defined in the schema\n */\n const schemaIndexes = schema.indexes ? schema.indexes : [];\n const index = args.mangoQuery.index;\n if (index) {\n const isInSchema = schemaIndexes.find(schemaIndex => deepEqual(schemaIndex, index));\n if (!isInSchema) {\n throw newRxError(\n 'QU12',\n {\n collection: args.rxQuery.collection.name,\n query: args.mangoQuery,\n schema\n }\n );\n }\n }\n\n\n /**\n * Ensure that a count() query can only be used\n * with selectors that are fully satisfied by the used index.\n */\n if (args.rxQuery.op === 'count') {\n if (\n !areSelectorsSatisfiedByIndex(\n args.rxQuery.collection.schema.jsonSchema,\n args.mangoQuery\n ) &&\n !args.rxQuery.collection.database.allowSlowCount\n ) {\n throw newRxError('QU14', {\n collection: args.rxQuery.collection,\n query: args.mangoQuery\n });\n }\n }\n\n /**\n * Ensure that sort only runs on known fields\n * TODO also check nested fields\n */\n if (args.mangoQuery.sort) {\n args.mangoQuery.sort\n .map(sortPart => Object.keys(sortPart)[0])\n .filter(field => !field.includes('.'))\n .forEach(field => {\n if (!schemaTopLevelFields.includes(field)) {\n throw newRxError('QU13', {\n schema,\n field,\n query: args.mangoQuery,\n });\n }\n });\n }\n}\n\n\nexport function areSelectorsSatisfiedByIndex(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): boolean {\n const preparedQuery: DexiePreparedQuery = RxStorageDexieStatics.prepareQuery(\n schema,\n query\n );\n return preparedQuery.queryPlan.selectorSatisfiedByIndex;\n}\n"],"mappings":";;;;;;;;;AAUA;AACA;AACA;AAGA;AAEA;AACA;AACA;AACA;AACA;AACO,SAASA,UAAU,CAACC,IAAkC,EAAE;EAC3D,IAAMC,aAAa,GAAGC,MAAM,CAACC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACL,IAAI,CAACM,QAAQ,CAAC,KAAK,iBAAiB;EACzF,IAAI,CAACL,aAAa,EAAE;IAChB,MAAM,IAAAM,uBAAc,EAAC,MAAM,EAAE;MACzBC,EAAE,EAAER,IAAI,CAACQ,EAAE;MACXC,UAAU,EAAET,IAAI,CAACS,UAAU,CAACC,IAAI;MAChCJ,QAAQ,EAAEN,IAAI,CAACM;IACnB,CAAC,CAAC;EACN;EAEA,IAAMK,SAA+B,GAAG,CACpC,UAAU,EACV,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,CACV;EACDT,MAAM,CAACU,IAAI,CAACZ,IAAI,CAACM,QAAQ,CAAC,CAACO,OAAO,CAAC,UAAAC,GAAG,EAAI;IACtC,IAAI,CAAEH,SAAS,CAAcI,QAAQ,CAACD,GAAG,CAAC,EAAE;MACxC,MAAM,IAAAP,uBAAc,EAAC,MAAM,EAAE;QACzBC,EAAE,EAAER,IAAI,CAACQ,EAAE;Q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,CAAC,UAAAC,QAAQ;MAAA,OAAI5C,MAAM,CAACU,IAAI,CAACkC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAAA,EAAC,CACzChB,MAAM,CAAC,UAAAG,KAAK;MAAA,OAAI,CAACA,KAAK,CAAClB,QAAQ,CAAC,GAAG,CAAC;IAAA,EAAC,CACrCF,OAAO,CAAC,UAAAoB,KAAK,EAAI;MACd,IAAI,CAACL,oBAAoB,CAACb,QAAQ,CAACkB,KAAK,CAAC,EAAE;QACvC,MAAM,IAAAf,mBAAU,EAAC,MAAM,EAAE;UACrBG,MAAM,EAANA,MAAM;UACNY,KAAK,EAALA,KAAK;UACLd,KAAK,EAAEnB,IAAI,CAAC0B;QAChB,CAAC,CAAC;MACN;IACJ,CAAC,CAAC;EACV;AACJ;AAGO,SAASe,4BAA4B,CACxCpB,MAA+C,EAC/CF,KAAkC,EAC3B;EACP,IAAM4B,aAAsC,GAAGC,mCAAqB,CAACC,YAAY,CAC7E5B,MAAM,EACNF,KAAK,CACR;EACD,OAAO4B,aAAa,CAACG,SAAS,CAACC,wBAAwB;AAC3D"} \ No newline at end of file diff --git a/dist/lib/plugins/dev-mode/check-schema.js b/dist/lib/plugins/dev-mode/check-schema.js index 4cd3f96e1c2..a0ba33f2e85 100644 --- a/dist/lib/plugins/dev-mode/check-schema.js +++ b/dist/lib/plugins/dev-mode/check-schema.js @@ -11,7 +11,7 @@ exports.validateFieldsDeep = validateFieldsDeep; var _objectPath = _interopRequireDefault(require("object-path")); var _rxError = require("../../rx-error"); var _rxSchemaHelper = require("../../rx-schema-helper"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _entityProperties = require("./entity-properties"); /** * does additional checks over the schema-json @@ -220,7 +220,7 @@ function getSchemaPropertyRealPath(shortPath) { realPath = realPath.concat('.items'); } } - return (0, _util.trimDots)(realPath); + return (0, _utils.trimDots)(realPath); } /** @@ -296,7 +296,7 @@ function checkSchema(jsonSchema) { // check format of jsonSchema.indexes if (jsonSchema.indexes) { // should be an array - if (!(0, _util.isMaybeReadonlyArray)(jsonSchema.indexes)) { + if (!(0, _utils.isMaybeReadonlyArray)(jsonSchema.indexes)) { throw (0, _rxError.newRxError)('SC18', { indexes: jsonSchema.indexes, schema: jsonSchema @@ -328,7 +328,7 @@ function checkSchema(jsonSchema) { * when they are transformed to strings. * Therefore we need to enforce some properties inside of the schema. */ - var indexAsArray = (0, _util.isMaybeReadonlyArray)(index) ? index : [index]; + var indexAsArray = (0, _utils.isMaybeReadonlyArray)(index) ? index : [index]; indexAsArray.forEach(function (fieldName) { var schemaPart = (0, _rxSchemaHelper.getSchemaByObjectPath)(jsonSchema, fieldName); var type = schemaPart.type; @@ -396,7 +396,7 @@ function checkSchema(jsonSchema) { } // remove backward-compatibility for index: true - Object.keys((0, _util.flattenObject)(jsonSchema)).map(function (key) { + Object.keys((0, _utils.flattenObject)(jsonSchema)).map(function (key) { // flattenObject returns only ending paths, we need all paths pointing to an object var split = key.split('.'); split.pop(); // all but last @@ -415,14 +415,14 @@ function checkSchema(jsonSchema) { key = key.replace('properties.', ''); // first key = key.replace(/\.properties\./g, '.'); // middle throw (0, _rxError.newRxError)('SC26', { - index: (0, _util.trimDots)(key), + index: (0, _utils.trimDots)(key), schema: jsonSchema }); }); /* check types of the indexes */ (jsonSchema.indexes || []).reduce(function (indexPaths, currentIndex) { - if ((0, _util.isMaybeReadonlyArray)(currentIndex)) { + if ((0, _utils.isMaybeReadonlyArray)(currentIndex)) { indexPaths.concat(currentIndex); } else { indexPaths.push(currentIndex); @@ -460,7 +460,7 @@ function checkSchema(jsonSchema) { * This check ensures people do not oversee the breaking change * Remove this check in the future */ - Object.keys((0, _util.flattenObject)(jsonSchema)).map(function (key) { + Object.keys((0, _utils.flattenObject)(jsonSchema)).map(function (key) { // flattenObject returns only ending paths, we need all paths pointing to an object var split = key.split('.'); split.pop(); // all but last @@ -479,7 +479,7 @@ function checkSchema(jsonSchema) { key = key.replace('properties.', ''); // first key = key.replace(/\.properties\./g, '.'); // middle throw (0, _rxError.newRxError)('SC27', { - index: (0, _util.trimDots)(key), + index: (0, _utils.trimDots)(key), schema: jsonSchema }); }); diff --git a/dist/lib/plugins/dev-mode/check-schema.js.map b/dist/lib/plugins/dev-mode/check-schema.js.map index 312bff79f4a..e83998bb914 100644 --- a/dist/lib/plugins/dev-mode/check-schema.js.map +++ b/dist/lib/plugins/dev-mode/check-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"check-schema.js","names":["checkFieldNameRegex","fieldName","includes","newRxError","regexStr","regex","RegExp","match","validateFieldsDeep","rxJsonSchema","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","checkField","schemaObj","path","Array","isArray","hasOwnProperty","type","required","length","items","isNested","split","primary","charAt","traverse","currentObj","currentPath","Object","keys","forEach","attributeName","properties","nextPath","checkPrimaryKey","jsonSchema","schema","validatePrimarySchemaPart","schemaPart","args","key","compositePrimaryKey","keySchemaPart","getSchemaByObjectPath","fields","field","primaryPathSchemaPart","maxLength","getSchemaPropertyRealPath","shortPath","pathParts","realPath","i","concat","trimDots","checkSchema","_rev","version","value","indexes","unique","encrypted","rxDocumentProperties","isMaybeReadonlyArray","index","indexAsArray","multipleOf","maximum","minimum","parentPath","lastPathPart","partParts","pop","join","parentSchemaPart","flattenObject","map","filter","elem","pos","arr","indexOf","objectPath","get","replace","reduce","indexPaths","currentIndex","push","indexPath","propPath"],"sources":["../../../../src/plugins/dev-mode/check-schema.ts"],"sourcesContent":["/**\n * does additional checks over the schema-json\n * to ensure nothing is broken or not supported\n */\n\nimport objectPath from 'object-path';\nimport {\n newRxError\n} from '../../rx-error';\nimport { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper';\nimport type {\n CompositePrimaryKey,\n JsonSchema,\n JsonSchemaTypes,\n RxJsonSchema,\n TopLevelProperty\n} from '../../types';\nimport {\n flattenObject, isMaybeReadonlyArray,\n trimDots\n} from '../../util';\nimport { rxDocumentProperties } from './entity-properties';\n\n/**\n * checks if the fieldname is allowed\n * this makes sure that the fieldnames can be transformed into javascript-vars\n * and does not conquer the observe$ and populate_ fields\n * @throws {Error}\n */\nexport function checkFieldNameRegex(fieldName: string) {\n if (fieldName === '_deleted') {\n return;\n }\n\n if (['properties', 'language'].includes(fieldName)) {\n throw newRxError('SC23', {\n fieldName\n });\n }\n\n const regexStr = '^[a-zA-Z](?:[[a-zA-Z0-9_]*]?[a-zA-Z0-9])?$';\n const regex = new RegExp(regexStr);\n if (\n /**\n * It must be allowed to set _id as primaryKey.\n * This makes it sometimes easier to work with RxDB+CouchDB\n * @link https://github.com/pubkey/rxdb/issues/681\n */\n fieldName !== '_id' &&\n !fieldName.match(regex)\n ) {\n throw newRxError('SC1', {\n regex: regexStr,\n fieldName\n });\n }\n}\n\n/**\n * validate that all schema-related things are ok\n */\nexport function validateFieldsDeep(rxJsonSchema: RxJsonSchema): true {\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function checkField(\n fieldName: string,\n schemaObj: any,\n path: string\n ) {\n if (\n typeof fieldName === 'string' &&\n typeof schemaObj === 'object' &&\n !Array.isArray(schemaObj)\n ) checkFieldNameRegex(fieldName);\n\n // 'item' only allowed it type=='array'\n if (schemaObj.hasOwnProperty('item') && schemaObj.type !== 'array') {\n throw newRxError('SC2', {\n fieldName\n });\n }\n\n /**\n * required fields cannot be set via 'required: true',\n * but must be set via required: []\n */\n if (schemaObj.hasOwnProperty('required') && typeof schemaObj.required === 'boolean') {\n throw newRxError('SC24', {\n fieldName\n });\n }\n\n\n // if ref given, must be type=='string', type=='array' with string-items or type==['string','null']\n if (schemaObj.hasOwnProperty('ref')) {\n if (Array.isArray(schemaObj.type)) {\n if (schemaObj.type.length > 2 || !schemaObj.type.includes('string') || !schemaObj.type.includes('null')) {\n throw newRxError('SC4', {\n fieldName\n });\n }\n } else {\n switch (schemaObj.type) {\n case 'string':\n break;\n case 'array':\n if (!schemaObj.items || !schemaObj.items.type || schemaObj.items.type !== 'string') {\n throw newRxError('SC3', {\n fieldName\n });\n }\n break;\n default:\n throw newRxError('SC4', {\n fieldName\n });\n }\n }\n }\n\n const isNested = path.split('.').length >= 2;\n\n // nested only\n if (isNested) {\n if (schemaObj.primary) {\n throw newRxError('SC6', {\n path,\n primary: schemaObj.primary\n });\n }\n\n if (schemaObj.default) {\n throw newRxError('SC7', {\n path\n });\n }\n }\n\n // first level\n if (!isNested) {\n\n // if _id is used, it must be primaryKey\n if (\n fieldName === '_id' &&\n primaryPath !== '_id'\n ) {\n throw newRxError('COL2', {\n fieldName\n });\n }\n\n // check underscore fields\n if (fieldName.charAt(0) === '_') {\n if (\n // exceptional allow underscore on these fields.\n fieldName === '_id' ||\n fieldName === '_deleted'\n ) {\n return;\n }\n throw newRxError('SC8', {\n fieldName\n });\n }\n }\n }\n\n function traverse(currentObj: any, currentPath: any) {\n if (!currentObj || typeof currentObj !== 'object') return;\n Object.keys(currentObj).forEach(attributeName => {\n const schemaObj = currentObj[attributeName];\n if (!currentObj.properties && schemaObj && typeof schemaObj === 'object') {\n checkField(\n attributeName,\n schemaObj,\n currentPath\n );\n }\n let nextPath = currentPath;\n if (attributeName !== 'properties') nextPath = nextPath + '.' + attributeName;\n traverse(schemaObj, nextPath);\n });\n }\n traverse(rxJsonSchema, '');\n return true;\n}\n\nexport function checkPrimaryKey(\n jsonSchema: RxJsonSchema\n) {\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', { schema: jsonSchema });\n }\n\n\n\n function validatePrimarySchemaPart(\n schemaPart: JsonSchema | TopLevelProperty\n ) {\n if (!schemaPart) {\n throw newRxError('SC33', { schema: jsonSchema });\n }\n\n const type: string = schemaPart.type as any;\n if (\n !type ||\n !['string', 'number', 'integer'].includes(type)\n ) {\n throw newRxError('SC32', { schema: jsonSchema, args: { schemaPart } });\n }\n }\n\n if (typeof jsonSchema.primaryKey === 'string') {\n const key = jsonSchema.primaryKey;\n const schemaPart = jsonSchema.properties[key];\n validatePrimarySchemaPart(schemaPart);\n } else {\n const compositePrimaryKey: CompositePrimaryKey = jsonSchema.primaryKey as any;\n\n const keySchemaPart = getSchemaByObjectPath(jsonSchema, compositePrimaryKey.key);\n validatePrimarySchemaPart(keySchemaPart);\n\n compositePrimaryKey.fields.forEach(field => {\n const schemaPart = getSchemaByObjectPath(jsonSchema, field);\n validatePrimarySchemaPart(schemaPart);\n });\n }\n\n\n /**\n * The primary key must have a maxLength set\n * which is required by some RxStorage implementations\n * to ensure we can craft custom index strings.\n */\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n const primaryPathSchemaPart = jsonSchema.properties[primaryPath];\n if (!primaryPathSchemaPart.maxLength) {\n throw newRxError('SC39', { schema: jsonSchema, args: { primaryPathSchemaPart } });\n }\n}\n\n/**\n * computes real path of the object path in the collection schema\n */\nfunction getSchemaPropertyRealPath(shortPath: string) {\n const pathParts = shortPath.split('.');\n let realPath = '';\n for (let i = 0; i < pathParts.length; i += 1) {\n if (pathParts[i] !== '[]') {\n realPath = realPath.concat('.properties.'.concat(pathParts[i]));\n } else {\n realPath = realPath.concat('.items');\n }\n }\n return trimDots(realPath);\n}\n\n/**\n * does the checking\n * @throws {Error} if something is not ok\n */\nexport function checkSchema(jsonSchema: RxJsonSchema) {\n\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', {\n schema: jsonSchema\n });\n }\n\n if (!jsonSchema.hasOwnProperty('properties')) {\n throw newRxError('SC29', {\n schema: jsonSchema\n });\n }\n\n // _rev MUST NOT exist, it is added by RxDB\n if (jsonSchema.properties._rev) {\n throw newRxError('SC10', {\n schema: jsonSchema\n });\n }\n\n // check version\n if (!jsonSchema.hasOwnProperty('version') ||\n typeof jsonSchema.version !== 'number' ||\n jsonSchema.version < 0\n ) {\n throw newRxError('SC11', {\n version: jsonSchema.version\n });\n }\n\n validateFieldsDeep(jsonSchema);\n checkPrimaryKey(jsonSchema);\n\n Object.keys(jsonSchema.properties).forEach(key => {\n const value: any = jsonSchema.properties[key];\n // check primary\n if (key === jsonSchema.primaryKey) {\n if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) {\n throw newRxError('SC13', {\n value,\n schema: jsonSchema\n });\n }\n if (value.unique) {\n throw newRxError('SC14', {\n value,\n schema: jsonSchema\n });\n }\n if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) {\n throw newRxError('SC15', {\n value,\n schema: jsonSchema\n });\n }\n if (value.type !== 'string') {\n throw newRxError('SC16', {\n value,\n schema: jsonSchema\n });\n }\n }\n\n // check if RxDocument-property\n if (rxDocumentProperties().includes(key)) {\n throw newRxError('SC17', {\n key,\n schema: jsonSchema\n });\n }\n });\n\n // check format of jsonSchema.indexes\n if (jsonSchema.indexes) {\n // should be an array\n if (!isMaybeReadonlyArray(jsonSchema.indexes)) {\n throw newRxError('SC18', {\n indexes: jsonSchema.indexes,\n schema: jsonSchema\n });\n }\n\n jsonSchema.indexes.forEach(index => {\n // should contain strings or array of strings\n if (!(typeof index === 'string' || Array.isArray(index))) {\n throw newRxError('SC19', { index, schema: jsonSchema });\n }\n // if is a compound index it must contain strings\n if (Array.isArray(index)) {\n for (let i = 0; i < index.length; i += 1) {\n if (typeof index[i] !== 'string') {\n throw newRxError('SC20', { index, schema: jsonSchema });\n }\n }\n }\n\n /**\n * To be able to craft custom indexable string with compound fields,\n * we need to know the maximum fieldlength of the fields values\n * when they are transformed to strings.\n * Therefore we need to enforce some properties inside of the schema.\n */\n const indexAsArray = isMaybeReadonlyArray(index) ? index : [index];\n indexAsArray.forEach(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n jsonSchema,\n fieldName\n );\n\n\n const type: JsonSchemaTypes = schemaPart.type as any;\n switch (type) {\n case 'string':\n const maxLength = schemaPart.maxLength;\n if (!maxLength) {\n throw newRxError('SC34', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'number':\n case 'integer':\n const multipleOf = schemaPart.multipleOf;\n if (!multipleOf) {\n throw newRxError('SC35', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n const maximum = schemaPart.maximum;\n const minimum = schemaPart.minimum;\n if (\n typeof maximum === 'undefined' ||\n typeof minimum === 'undefined'\n ) {\n throw newRxError('SC37', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'boolean':\n /**\n * If a boolean field is used as an index,\n * it must be required.\n */\n let parentPath = '';\n let lastPathPart = fieldName;\n if (fieldName.includes('.')) {\n const partParts = fieldName.split('.');\n lastPathPart = partParts.pop();\n parentPath = partParts.join('.');\n }\n const parentSchemaPart = parentPath === '' ? jsonSchema : getSchemaByObjectPath(\n jsonSchema,\n parentPath\n );\n\n if (\n !parentSchemaPart.required ||\n !parentSchemaPart.required.includes(lastPathPart)\n ) {\n throw newRxError('SC38', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n\n default:\n throw newRxError('SC36', {\n fieldName,\n type: schemaPart.type as any,\n schema: jsonSchema,\n });\n }\n });\n\n });\n }\n\n // remove backward-compatibility for index: true\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => { // check if this path defines an index\n const value = objectPath.get(jsonSchema, key);\n return !!value.index;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC26', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* check types of the indexes */\n (jsonSchema.indexes || [])\n .reduce((indexPaths: string[], currentIndex) => {\n if (isMaybeReadonlyArray(currentIndex)) {\n indexPaths.concat(currentIndex);\n } else {\n indexPaths.push(currentIndex);\n }\n return indexPaths;\n }, [])\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // from now on working only with unique indexes\n .map(indexPath => {\n const realPath = getSchemaPropertyRealPath(indexPath); // real path in the collection schema\n const schemaObj = objectPath.get(jsonSchema, realPath); // get the schema of the indexed property\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC21', {\n index: indexPath,\n schema: jsonSchema\n });\n }\n return { indexPath, schemaObj };\n })\n .filter(index =>\n index.schemaObj.type !== 'string' &&\n index.schemaObj.type !== 'integer' &&\n index.schemaObj.type !== 'number' &&\n index.schemaObj.type !== 'boolean'\n )\n .forEach(index => {\n throw newRxError('SC22', {\n key: index.indexPath,\n type: index.schemaObj.type,\n schema: jsonSchema\n });\n });\n\n\n /**\n * TODO\n * in 9.0.0 we changed the way encrypted fields are defined\n * This check ensures people do not oversee the breaking change\n * Remove this check in the future\n */\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '' && key !== 'attachments')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => {\n // check if this path defines an encrypted field\n const value = objectPath.get(jsonSchema, key);\n return !!value.encrypted;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC27', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* ensure encrypted fields exist in the schema */\n if (jsonSchema.encrypted) {\n jsonSchema.encrypted\n .forEach(propPath => {\n // real path in the collection schema\n const realPath = getSchemaPropertyRealPath(propPath);\n // get the schema of the indexed property\n const schemaObj = objectPath.get(jsonSchema, realPath);\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC28', {\n field: propPath,\n schema: jsonSchema\n });\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAKA;AACA;AAGA;AAQA;AAIA;AArBA;AACA;AACA;AACA;;AAoBA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,mBAAmB,CAACC,SAAiB,EAAE;EACnD,IAAIA,SAAS,KAA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KAAK,EAAE6C,QAAQ;UACftD,MAAM,EAAED;QACZ,CAAC,CAAC;MACN;IACJ,CAAC,CAAC;EACV;AACJ"} \ No newline at end of file +{"version":3,"file":"check-schema.js","names":["checkFieldNameRegex","fieldName","includes","newRxError","regexStr","regex","RegExp","match","validateFieldsDeep","rxJsonSchema","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","checkField","schemaObj","path","Array","isArray","hasOwnProperty","type","required","length","items","isNested","split","primary","charAt","traverse","currentObj","currentPath","Object","keys","forEach","attributeName","properties","nextPath","checkPrimaryKey","jsonSchema","schema","validatePrimarySchemaPart","schemaPart","args","key","compositePrimaryKey","keySchemaPart","getSchemaByObjectPath","fields","field","primaryPathSchemaPart","maxLength","getSchemaPropertyRealPath","shortPath","pathParts","realPath","i","concat","trimDots","checkSchema","_rev","version","value","indexes","unique","encrypted","rxDocumentProperties","isMaybeReadonlyArray","index","indexAsArray","multipleOf","maximum","minimum","parentPath","lastPathPart","partParts","pop","join","parentSchemaPart","flattenObject","map","filter","elem","pos","arr","indexOf","objectPath","get","replace","reduce","indexPaths","currentIndex","push","indexPath","propPath"],"sources":["../../../../src/plugins/dev-mode/check-schema.ts"],"sourcesContent":["/**\n * does additional checks over the schema-json\n * to ensure nothing is broken or not supported\n */\n\nimport objectPath from 'object-path';\nimport {\n newRxError\n} from '../../rx-error';\nimport { getPrimaryFieldOfPrimaryKey, getSchemaByObjectPath } from '../../rx-schema-helper';\nimport type {\n CompositePrimaryKey,\n JsonSchema,\n JsonSchemaTypes,\n RxJsonSchema,\n TopLevelProperty\n} from '../../types';\nimport {\n flattenObject, isMaybeReadonlyArray,\n trimDots\n} from '../../plugins/utils';\nimport { rxDocumentProperties } from './entity-properties';\n\n/**\n * checks if the fieldname is allowed\n * this makes sure that the fieldnames can be transformed into javascript-vars\n * and does not conquer the observe$ and populate_ fields\n * @throws {Error}\n */\nexport function checkFieldNameRegex(fieldName: string) {\n if (fieldName === '_deleted') {\n return;\n }\n\n if (['properties', 'language'].includes(fieldName)) {\n throw newRxError('SC23', {\n fieldName\n });\n }\n\n const regexStr = '^[a-zA-Z](?:[[a-zA-Z0-9_]*]?[a-zA-Z0-9])?$';\n const regex = new RegExp(regexStr);\n if (\n /**\n * It must be allowed to set _id as primaryKey.\n * This makes it sometimes easier to work with RxDB+CouchDB\n * @link https://github.com/pubkey/rxdb/issues/681\n */\n fieldName !== '_id' &&\n !fieldName.match(regex)\n ) {\n throw newRxError('SC1', {\n regex: regexStr,\n fieldName\n });\n }\n}\n\n/**\n * validate that all schema-related things are ok\n */\nexport function validateFieldsDeep(rxJsonSchema: RxJsonSchema): true {\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function checkField(\n fieldName: string,\n schemaObj: any,\n path: string\n ) {\n if (\n typeof fieldName === 'string' &&\n typeof schemaObj === 'object' &&\n !Array.isArray(schemaObj)\n ) checkFieldNameRegex(fieldName);\n\n // 'item' only allowed it type=='array'\n if (schemaObj.hasOwnProperty('item') && schemaObj.type !== 'array') {\n throw newRxError('SC2', {\n fieldName\n });\n }\n\n /**\n * required fields cannot be set via 'required: true',\n * but must be set via required: []\n */\n if (schemaObj.hasOwnProperty('required') && typeof schemaObj.required === 'boolean') {\n throw newRxError('SC24', {\n fieldName\n });\n }\n\n\n // if ref given, must be type=='string', type=='array' with string-items or type==['string','null']\n if (schemaObj.hasOwnProperty('ref')) {\n if (Array.isArray(schemaObj.type)) {\n if (schemaObj.type.length > 2 || !schemaObj.type.includes('string') || !schemaObj.type.includes('null')) {\n throw newRxError('SC4', {\n fieldName\n });\n }\n } else {\n switch (schemaObj.type) {\n case 'string':\n break;\n case 'array':\n if (!schemaObj.items || !schemaObj.items.type || schemaObj.items.type !== 'string') {\n throw newRxError('SC3', {\n fieldName\n });\n }\n break;\n default:\n throw newRxError('SC4', {\n fieldName\n });\n }\n }\n }\n\n const isNested = path.split('.').length >= 2;\n\n // nested only\n if (isNested) {\n if (schemaObj.primary) {\n throw newRxError('SC6', {\n path,\n primary: schemaObj.primary\n });\n }\n\n if (schemaObj.default) {\n throw newRxError('SC7', {\n path\n });\n }\n }\n\n // first level\n if (!isNested) {\n\n // if _id is used, it must be primaryKey\n if (\n fieldName === '_id' &&\n primaryPath !== '_id'\n ) {\n throw newRxError('COL2', {\n fieldName\n });\n }\n\n // check underscore fields\n if (fieldName.charAt(0) === '_') {\n if (\n // exceptional allow underscore on these fields.\n fieldName === '_id' ||\n fieldName === '_deleted'\n ) {\n return;\n }\n throw newRxError('SC8', {\n fieldName\n });\n }\n }\n }\n\n function traverse(currentObj: any, currentPath: any) {\n if (!currentObj || typeof currentObj !== 'object') return;\n Object.keys(currentObj).forEach(attributeName => {\n const schemaObj = currentObj[attributeName];\n if (!currentObj.properties && schemaObj && typeof schemaObj === 'object') {\n checkField(\n attributeName,\n schemaObj,\n currentPath\n );\n }\n let nextPath = currentPath;\n if (attributeName !== 'properties') nextPath = nextPath + '.' + attributeName;\n traverse(schemaObj, nextPath);\n });\n }\n traverse(rxJsonSchema, '');\n return true;\n}\n\nexport function checkPrimaryKey(\n jsonSchema: RxJsonSchema\n) {\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', { schema: jsonSchema });\n }\n\n\n\n function validatePrimarySchemaPart(\n schemaPart: JsonSchema | TopLevelProperty\n ) {\n if (!schemaPart) {\n throw newRxError('SC33', { schema: jsonSchema });\n }\n\n const type: string = schemaPart.type as any;\n if (\n !type ||\n !['string', 'number', 'integer'].includes(type)\n ) {\n throw newRxError('SC32', { schema: jsonSchema, args: { schemaPart } });\n }\n }\n\n if (typeof jsonSchema.primaryKey === 'string') {\n const key = jsonSchema.primaryKey;\n const schemaPart = jsonSchema.properties[key];\n validatePrimarySchemaPart(schemaPart);\n } else {\n const compositePrimaryKey: CompositePrimaryKey = jsonSchema.primaryKey as any;\n\n const keySchemaPart = getSchemaByObjectPath(jsonSchema, compositePrimaryKey.key);\n validatePrimarySchemaPart(keySchemaPart);\n\n compositePrimaryKey.fields.forEach(field => {\n const schemaPart = getSchemaByObjectPath(jsonSchema, field);\n validatePrimarySchemaPart(schemaPart);\n });\n }\n\n\n /**\n * The primary key must have a maxLength set\n * which is required by some RxStorage implementations\n * to ensure we can craft custom index strings.\n */\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n const primaryPathSchemaPart = jsonSchema.properties[primaryPath];\n if (!primaryPathSchemaPart.maxLength) {\n throw newRxError('SC39', { schema: jsonSchema, args: { primaryPathSchemaPart } });\n }\n}\n\n/**\n * computes real path of the object path in the collection schema\n */\nfunction getSchemaPropertyRealPath(shortPath: string) {\n const pathParts = shortPath.split('.');\n let realPath = '';\n for (let i = 0; i < pathParts.length; i += 1) {\n if (pathParts[i] !== '[]') {\n realPath = realPath.concat('.properties.'.concat(pathParts[i]));\n } else {\n realPath = realPath.concat('.items');\n }\n }\n return trimDots(realPath);\n}\n\n/**\n * does the checking\n * @throws {Error} if something is not ok\n */\nexport function checkSchema(jsonSchema: RxJsonSchema) {\n\n if (!jsonSchema.primaryKey) {\n throw newRxError('SC30', {\n schema: jsonSchema\n });\n }\n\n if (!jsonSchema.hasOwnProperty('properties')) {\n throw newRxError('SC29', {\n schema: jsonSchema\n });\n }\n\n // _rev MUST NOT exist, it is added by RxDB\n if (jsonSchema.properties._rev) {\n throw newRxError('SC10', {\n schema: jsonSchema\n });\n }\n\n // check version\n if (!jsonSchema.hasOwnProperty('version') ||\n typeof jsonSchema.version !== 'number' ||\n jsonSchema.version < 0\n ) {\n throw newRxError('SC11', {\n version: jsonSchema.version\n });\n }\n\n validateFieldsDeep(jsonSchema);\n checkPrimaryKey(jsonSchema);\n\n Object.keys(jsonSchema.properties).forEach(key => {\n const value: any = jsonSchema.properties[key];\n // check primary\n if (key === jsonSchema.primaryKey) {\n if (jsonSchema.indexes && jsonSchema.indexes.includes(key)) {\n throw newRxError('SC13', {\n value,\n schema: jsonSchema\n });\n }\n if (value.unique) {\n throw newRxError('SC14', {\n value,\n schema: jsonSchema\n });\n }\n if (jsonSchema.encrypted && jsonSchema.encrypted.includes(key)) {\n throw newRxError('SC15', {\n value,\n schema: jsonSchema\n });\n }\n if (value.type !== 'string') {\n throw newRxError('SC16', {\n value,\n schema: jsonSchema\n });\n }\n }\n\n // check if RxDocument-property\n if (rxDocumentProperties().includes(key)) {\n throw newRxError('SC17', {\n key,\n schema: jsonSchema\n });\n }\n });\n\n // check format of jsonSchema.indexes\n if (jsonSchema.indexes) {\n // should be an array\n if (!isMaybeReadonlyArray(jsonSchema.indexes)) {\n throw newRxError('SC18', {\n indexes: jsonSchema.indexes,\n schema: jsonSchema\n });\n }\n\n jsonSchema.indexes.forEach(index => {\n // should contain strings or array of strings\n if (!(typeof index === 'string' || Array.isArray(index))) {\n throw newRxError('SC19', { index, schema: jsonSchema });\n }\n // if is a compound index it must contain strings\n if (Array.isArray(index)) {\n for (let i = 0; i < index.length; i += 1) {\n if (typeof index[i] !== 'string') {\n throw newRxError('SC20', { index, schema: jsonSchema });\n }\n }\n }\n\n /**\n * To be able to craft custom indexable string with compound fields,\n * we need to know the maximum fieldlength of the fields values\n * when they are transformed to strings.\n * Therefore we need to enforce some properties inside of the schema.\n */\n const indexAsArray = isMaybeReadonlyArray(index) ? index : [index];\n indexAsArray.forEach(fieldName => {\n const schemaPart = getSchemaByObjectPath(\n jsonSchema,\n fieldName\n );\n\n\n const type: JsonSchemaTypes = schemaPart.type as any;\n switch (type) {\n case 'string':\n const maxLength = schemaPart.maxLength;\n if (!maxLength) {\n throw newRxError('SC34', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'number':\n case 'integer':\n const multipleOf = schemaPart.multipleOf;\n if (!multipleOf) {\n throw newRxError('SC35', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n const maximum = schemaPart.maximum;\n const minimum = schemaPart.minimum;\n if (\n typeof maximum === 'undefined' ||\n typeof minimum === 'undefined'\n ) {\n throw newRxError('SC37', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n case 'boolean':\n /**\n * If a boolean field is used as an index,\n * it must be required.\n */\n let parentPath = '';\n let lastPathPart = fieldName;\n if (fieldName.includes('.')) {\n const partParts = fieldName.split('.');\n lastPathPart = partParts.pop();\n parentPath = partParts.join('.');\n }\n const parentSchemaPart = parentPath === '' ? jsonSchema : getSchemaByObjectPath(\n jsonSchema,\n parentPath\n );\n\n if (\n !parentSchemaPart.required ||\n !parentSchemaPart.required.includes(lastPathPart)\n ) {\n throw newRxError('SC38', {\n index,\n field: fieldName,\n schema: jsonSchema\n });\n }\n break;\n\n default:\n throw newRxError('SC36', {\n fieldName,\n type: schemaPart.type as any,\n schema: jsonSchema,\n });\n }\n });\n\n });\n }\n\n // remove backward-compatibility for index: true\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => { // check if this path defines an index\n const value = objectPath.get(jsonSchema, key);\n return !!value.index;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC26', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* check types of the indexes */\n (jsonSchema.indexes || [])\n .reduce((indexPaths: string[], currentIndex) => {\n if (isMaybeReadonlyArray(currentIndex)) {\n indexPaths.concat(currentIndex);\n } else {\n indexPaths.push(currentIndex);\n }\n return indexPaths;\n }, [])\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // from now on working only with unique indexes\n .map(indexPath => {\n const realPath = getSchemaPropertyRealPath(indexPath); // real path in the collection schema\n const schemaObj = objectPath.get(jsonSchema, realPath); // get the schema of the indexed property\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC21', {\n index: indexPath,\n schema: jsonSchema\n });\n }\n return { indexPath, schemaObj };\n })\n .filter(index =>\n index.schemaObj.type !== 'string' &&\n index.schemaObj.type !== 'integer' &&\n index.schemaObj.type !== 'number' &&\n index.schemaObj.type !== 'boolean'\n )\n .forEach(index => {\n throw newRxError('SC22', {\n key: index.indexPath,\n type: index.schemaObj.type,\n schema: jsonSchema\n });\n });\n\n\n /**\n * TODO\n * in 9.0.0 we changed the way encrypted fields are defined\n * This check ensures people do not oversee the breaking change\n * Remove this check in the future\n */\n Object.keys(flattenObject(jsonSchema))\n .map(key => {\n // flattenObject returns only ending paths, we need all paths pointing to an object\n const split = key.split('.');\n split.pop(); // all but last\n return split.join('.');\n })\n .filter(key => key !== '' && key !== 'attachments')\n .filter((elem, pos, arr) => arr.indexOf(elem) === pos) // unique\n .filter(key => {\n // check if this path defines an encrypted field\n const value = objectPath.get(jsonSchema, key);\n return !!value.encrypted;\n })\n .forEach(key => { // replace inner properties\n key = key.replace('properties.', ''); // first\n key = key.replace(/\\.properties\\./g, '.'); // middle\n throw newRxError('SC27', {\n index: trimDots(key),\n schema: jsonSchema\n });\n });\n\n /* ensure encrypted fields exist in the schema */\n if (jsonSchema.encrypted) {\n jsonSchema.encrypted\n .forEach(propPath => {\n // real path in the collection schema\n const realPath = getSchemaPropertyRealPath(propPath);\n // get the schema of the indexed property\n const schemaObj = objectPath.get(jsonSchema, realPath);\n if (!schemaObj || typeof schemaObj !== 'object') {\n throw newRxError('SC28', {\n field: propPath,\n schema: jsonSchema\n });\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAKA;AACA;AAGA;AAQA;AAIA;AArBA;AACA;AACA;AACA;;AAoBA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,mBAAmB,CAACC,SAAiB,EAAE;EACnD,IAAIA,SAAS,KAAK,UAAU,EAAE;IAC1B;EACJ;EAEA,IAAI,CAAC,YAAY,EAAE,UAAU,CAAC,CAACC,QAAQ,CAACD,SAAS,CAAC,EAAE;IAChD,MAAM,IAAAE,mBAAU,EAAC,MAAM,EAAE;MACr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mode/error-messages.js index 2bc1362e08a..ecd2c95b910 100644 --- a/dist/lib/plugins/dev-mode/error-messages.js +++ b/dist/lib/plugins/dev-mode/error-messages.js @@ -19,8 +19,8 @@ var ERROR_MESSAGES = { UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage', UT6: 'schema contains encrypted fields but no encryption handler is used in the storage', // plugins - PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()', - PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', + PL1: 'Given plugin is not RxDB plugin.', + // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.', PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object', // pouch-db.js // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2', @@ -61,14 +61,15 @@ var ERROR_MESSAGES = { DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema', // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given', DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\n' + 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional', - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\'pouchdb-adapter-[adaptername]\'));', - DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\'pouchdb-adapter-leveldb\'));', + // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\'pouchdb-adapter-[adaptername]\'));', + // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\'pouchdb-adapter-leveldb\'));', DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash', + DB12: 'RxDatabase.addCollections(): could not write to internal store', // rx-collection COL1: 'RxDocument.insert() You cannot insert an existing document', COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey', COL3: 'RxCollection.upsert() does not work without primary', - COL4: 'RxCollection.atomicUpsert() does not work without primary', + COL4: 'RxCollection.incrementalUpsert() does not work without primary', COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)', COL6: 'RxCollection.findOne() needs a queryObject or string', COL7: 'hook must be a function', @@ -83,7 +84,9 @@ var ERROR_MESSAGES = { COL16: 'given static method is not a function', COL17: 'RxCollection.ORM: statics-name not allowed', COL18: 'collection-method not allowed because fieldname is in the schema', - COL19: 'Document update conflict. When changing a document you must work on the previous revision', + // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision', + COL20: 'Storage write error', + CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision', // rx-document.js DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed', DOC2: 'cannot observe primary path', @@ -131,8 +134,8 @@ var ERROR_MESSAGES = { LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.', // plugins/replication.js RC1: 'Replication: already added', - RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection', - RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', + RC2: 'replicateCouchDB() query must be from the same RxCollection', + // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\'s pouchdb as remote, use the collection instead', RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true', RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance', RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.', @@ -185,8 +188,9 @@ var ERROR_MESSAGES = { VD1: 'Sub-schema not found, does the schemaPath exists in your schema?', VD2: 'object does not match schema', // plugins/in-memory.js - IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', - IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', + // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\'pouchdb-adapter-memory\'));', + // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead', + // plugins/server.js S1: 'You cannot create collections after calling RxDatabase.server()', // plugins/replication-graphql.js @@ -197,7 +201,7 @@ var ERROR_MESSAGES = { // plugins/crdt/ CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.', - CRDT2: 'RxDocument.atomicUpdate() cannot be used when CRDTs are activated.', + CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.', CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used', // plugins/dexie/ DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index', diff --git a/dist/lib/plugins/dev-mode/error-messages.js.map b/dist/lib/plugins/dev-mode/error-messages.js.map index b8f65a8fc7b..9c94e324ce0 100644 --- a/dist/lib/plugins/dev-mode/error-messages.js.map +++ b/dist/lib/plugins/dev-mode/error-messages.js.map @@ -1 +1 @@ -{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","PL1","PL2","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB9","DB10","DB11","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL19","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DM1","DM2","DM3","AT1","EN1","EN2","EN3","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC3","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_P2P_PEER","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","VD1","VD2","IM1","IM2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin. Pouchdb plugins must be added via addPouchPlugin()',\n PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.atomicUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption.js\n EN1: 'password is no string',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'RxCollection.syncCouchDB() query must be from the same RxCollection',\n RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_P2P_PEER: 'RxReplication P2P Peer has error',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 insated - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.atomicUpdate() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/dexie/\n DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error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C,IAAI,EAAE,mDAAmD;EACzDC,IAAI,EAAE,gDAAgD;EACtDC,IAAI,EAAE,uCAAuC;EAC7CC,IAAI,EAAE,mJAAmJ;EACzJC,IAAI,EAAE,yEAAyE;EAC/EC,IAAI,EAAE,uEAAuE;EAC7EC,IAAI,EAAE,+EAA+E;EACrFC,IAAI,EAAE,4DAA4D;EAClEC,IAAI,EAAE,gDAAgD;EACtDC,IAAI,EAAE,qCAAqC;EAC3CC,IAAI,EAAE,qEAAqE;EAC3EC,IAAI,EAAE,+DAA+D;EACrEC,IAAI,EAAE,sGAAsG;EAC5GC,IAAI,EAAE,+GAA+G;EACrHC,IAAI,EAAE,8CAA8C;EACpDC,IAAI,EAAE,gHAAgH;EACtHC,IAAI,EAAE,kFAAkF;EACxFC,IAAI,EAAE,uDAAuD;EAE7D;EACA;;EAEA;EACAC,GAAG,EAAE,kEAAkE;EACvEC,GAAG,EAAE,8BAA8B;EAEnC;EACAC,GAAG,EAAE,kGAAkG;EACvGC,GAAG,EAAE,4GAA4G;EAEjH;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,oEAAoE;EAC3EC,KAAK,EAAE,wGAAwG;EAE/G;EACAC,IAAI,EAAE,oHAAoH;EAE1H;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB11","DB12","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","CONFLICT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DM1","DM2","DM3","AT1","EN1","EN2","EN3","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_P2P_PEER","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importy a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption.js\n EN1: 'password is no string',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_P2P_PEER: 'RxReplication P2P Peer has error',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 insated - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/dexie/\n DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;;AAGO,IAAMA,cAAc,GAAG;EAC1B;EACAC,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EAExF;EACAC,GAAG,EAAE,kCAAkC;EACvC;EACAC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EAEA;EACAC,GAAG,EAAE,2CAA2C;EAChD;EACA;EACAC,GAAG,EAAE,+DAA+D;EACpEC,GAAG,EAAE,wEAAwE;EAC7EC,GAAG,EAAE,iDAAiD;EACtD;EACA;EACAC,GAAG,EAAE,oDAAoD;EACzDC,IAAI,EAAE,uCAAuC;EAC7CC,IAAI,EAAE,sCAAsC;EAC5CC,IAAI,EAAE,8BAA8B;EACpCC,IAAI,EAAE,8DAA8D;EACpEC,IAAI,EAAE,8HAA8H,GAChI,8DAA8D;EAClEC,IAAI,EAAE,0DAA0D;EAEhE;EACAC,GAAG,EAAE,iCAAiC;EACtCC,GAAG,EAAE,kBAAkB;EACvBC,GAAG,EAAE,6DAA6D;EAClEC,GAAG,EAAE,8DAA8D;EACnEC,GAAG,EAAE,oEAAoE;EACzEC,GAAG,EAAE,gIA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b/dist/lib/plugins/dev-mode/index.js index 7a856f65c7c..e956af75096 100644 --- a/dist/lib/plugins/dev-mode/index.js +++ b/dist/lib/plugins/dev-mode/index.js @@ -50,7 +50,7 @@ Object.keys(_checkQuery).forEach(function (key) { }); }); var _rxError = require("../../rx-error"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); /** * Deep freezes and object when in dev-mode. * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode. @@ -62,7 +62,7 @@ function deepFreezeWhenDevMode(obj) { if (!obj || typeof obj === 'string' || typeof obj === 'number') { return obj; } - return (0, _util.deepFreeze)(obj); + return (0, _utils.deepFreeze)(obj); } var DEV_MODE_PLUGIN_NAME = 'dev-mode'; exports.DEV_MODE_PLUGIN_NAME = DEV_MODE_PLUGIN_NAME; diff --git a/dist/lib/plugins/dev-mode/index.js.map b/dist/lib/plugins/dev-mode/index.js.map index 62a0b00f35a..6107fc5743f 100644 --- a/dist/lib/plugins/dev-mode/index.js.map +++ b/dist/lib/plugins/dev-mode/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["deepFreezeWhenDevMode","obj","deepFreeze","DEV_MODE_PLUGIN_NAME","RxDBDevModePlugin","name","rxdb","overwritable","isDevMode","tunnelErrorMessage","code","ERROR_MESSAGES","console","error","Error","hooks","preCreateRxSchema","after","checkSchema","preCreateRxDatabase","args","ensureDatabaseNameIsValid","preCreateRxCollection","ensureCollectionNameValid","checkOrmDocumentMethods","schema","methods","charAt","newRxError","preCreateRxQuery","checkQuery","prePrepareQuery","checkMangoQuery","createRxCollection","checkOrmMethods","creator","statics","attachments","migrationStrategies","checkMigrationStrategies"],"sources":["../../../../src/plugins/dev-mode/index.ts"],"sourcesContent":["import type {\n RxPlugin,\n RxCollectionCreator,\n RxDatabaseCreator,\n RxErrorKey\n} from '../../types';\n\nimport {\n ERROR_MESSAGES\n} from './error-messages';\nimport {\n checkSchema\n} from './check-schema';\nimport {\n checkOrmDocumentMethods,\n checkOrmMethods\n} from './check-orm';\nimport { checkMigrationStrategies } from './check-migration-strategies';\nimport {\n ensureCollectionNameValid,\n ensureDatabaseNameIsValid\n} from './unallowed-properties';\nimport { checkMangoQuery, checkQuery } from './check-query';\nimport { newRxError } from '../../rx-error';\nimport { DeepReadonly } from '../../types/util';\nimport { deepFreeze } from '../../util';\n\nexport * from './check-schema';\nexport * from './unallowed-properties';\nexport * from './check-query';\n\n\n/**\n * Deep freezes and object when in dev-mode.\n * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode.\n * Also we can ensure the readonly state via typescript\n * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n */\nexport function deepFreezeWhenDevMode(obj: T): DeepReadonly {\n // direct return if not suitable for deepFreeze()\n if (\n !obj ||\n typeof obj === 'string' ||\n typeof obj === 'number'\n ) {\n return obj as any;\n }\n\n return deepFreeze(obj) as any;\n}\n\n\nexport const DEV_MODE_PLUGIN_NAME = 'dev-mode';\nexport const RxDBDevModePlugin: RxPlugin = {\n name: DEV_MODE_PLUGIN_NAME,\n rxdb: true,\n overwritable: {\n isDevMode() {\n return true;\n },\n deepFreezeWhenDevMode,\n tunnelErrorMessage(code: RxErrorKey) {\n if (!ERROR_MESSAGES[code]) {\n console.error('RxDB: Error-Code not known: ' + code);\n throw new Error('Error-Code ' + code + ' not known, contact the maintainer');\n }\n return ERROR_MESSAGES[code];\n }\n },\n hooks: {\n preCreateRxSchema: {\n after: checkSchema\n },\n preCreateRxDatabase: {\n after: function (args: RxDatabaseCreator) {\n ensureDatabaseNameIsValid(args);\n }\n },\n preCreateRxCollection: {\n after: function (args: RxCollectionCreator & { name: string; }) {\n ensureCollectionNameValid(args);\n checkOrmDocumentMethods(args.schema as any, args.methods);\n if (args.name.charAt(0) === '_') {\n throw newRxError('DB2', {\n name: args.name\n });\n }\n if (!args.schema) {\n throw newRxError('DB4', {\n name: args.name,\n args\n });\n }\n }\n },\n preCreateRxQuery: {\n after: function (args) {\n checkQuery(args);\n }\n },\n prePrepareQuery: {\n after: (args) => {\n checkMangoQuery(args);\n }\n },\n createRxCollection: {\n after: (args) => {\n // check ORM-methods\n checkOrmMethods(args.creator.statics);\n checkOrmMethods(args.creator.methods);\n checkOrmMethods(args.creator.attachments);\n\n // check migration strategies\n if (args.creator.schema && args.creator.migrationStrategies) {\n checkMigrationStrategies(\n args.creator.schema,\n args.creator.migrationStrategies\n );\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAOA;AAGA;AAiBA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAdA;AAIA;AACA;AAUA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AANA;AAOA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AANA;AAEA;AAOA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,qBAAqB,CAAIC,GAAM,EAAmB;EAC9D;EACA,IACI,CAACA,GAAG,IACJ,OAAOA,GAAG,KAAK,QAAQ,IACvB,OAAOA,GAAG,KAAK,QAAQ,EACzB;IACE,OAAOA,GAAG;EACd;EAEA,OAAO,IAAAC,gBAAU,EAACD,GAAG,CAAC;AAC1B;AAGO,IAAME,oBAAoB,GAAG,UAAU;AAAC;AACxC,IAAMC,iBAA2B,GAAG;EACvCC,IAAI,EAAEF,oBAAoB;EAC1BG,IAAI,EAAE,IAAI;EACVC,YAAY,EAAE;IACVC,SAAS,uBAAG;MACR,OAAO,IAAI;IACf,CAAC;IACDR,qBAAqB,EAArBA,qBAAqB;IACrBS,kBAAkB,8BAACC,IAAgB,EAAE;MACjC,IAAI,CAACC,6BAAc,CAACD,IAAI,CAAC,EAAE;QACvBE,OAAO,CAACC,KAAK,CAAC,8BAA8B,GAAGH,IAAI,CAAC;QACpD,MAAM,IAAII,KAAK,CAAC,aAAa,GAAGJ,IAAI,GAAG,oCAAoC,CAAC;MAChF;MACA,OAAOC,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O,CAACE,WAAW,CAAC;;QAEzC;QACA,IAAIjB,IAAI,CAACe,OAAO,CAACV,MAAM,IAAIL,IAAI,CAACe,OAAO,CAACG,mBAAmB,EAAE;UACzD,IAAAC,kDAAwB,EACpBnB,IAAI,CAACe,OAAO,CAACV,MAAM,EACnBL,IAAI,CAACe,OAAO,CAACG,mBAAmB,CACnC;QACL;MACJ;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["deepFreezeWhenDevMode","obj","deepFreeze","DEV_MODE_PLUGIN_NAME","RxDBDevModePlugin","name","rxdb","overwritable","isDevMode","tunnelErrorMessage","code","ERROR_MESSAGES","console","error","Error","hooks","preCreateRxSchema","after","checkSchema","preCreateRxDatabase","args","ensureDatabaseNameIsValid","preCreateRxCollection","ensureCollectionNameValid","checkOrmDocumentMethods","schema","methods","charAt","newRxError","preCreateRxQuery","checkQuery","prePrepareQuery","checkMangoQuery","createRxCollection","checkOrmMethods","creator","statics","attachments","migrationStrategies","checkMigrationStrategies"],"sources":["../../../../src/plugins/dev-mode/index.ts"],"sourcesContent":["import type {\n RxPlugin,\n RxCollectionCreator,\n RxDatabaseCreator,\n RxErrorKey\n} from '../../types';\n\nimport {\n ERROR_MESSAGES\n} from './error-messages';\nimport {\n checkSchema\n} from './check-schema';\nimport {\n checkOrmDocumentMethods,\n checkOrmMethods\n} from './check-orm';\nimport { checkMigrationStrategies } from './check-migration-strategies';\nimport {\n ensureCollectionNameValid,\n ensureDatabaseNameIsValid\n} from './unallowed-properties';\nimport { checkMangoQuery, checkQuery } from './check-query';\nimport { newRxError } from '../../rx-error';\nimport { DeepReadonly } from '../../types/util';\nimport { deepFreeze } from '../../plugins/utils';\n\nexport * from './check-schema';\nexport * from './unallowed-properties';\nexport * from './check-query';\n\n\n/**\n * Deep freezes and object when in dev-mode.\n * Deep-Freezing has the same performaance as deep-cloning, so we only do that in dev-mode.\n * Also we can ensure the readonly state via typescript\n * @link https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n */\nexport function deepFreezeWhenDevMode(obj: T): DeepReadonly {\n // direct return if not suitable for deepFreeze()\n if (\n !obj ||\n typeof obj === 'string' ||\n typeof obj === 'number'\n ) {\n return obj as any;\n }\n\n return deepFreeze(obj) as any;\n}\n\n\nexport const DEV_MODE_PLUGIN_NAME = 'dev-mode';\nexport const RxDBDevModePlugin: RxPlugin = {\n name: DEV_MODE_PLUGIN_NAME,\n rxdb: true,\n overwritable: {\n isDevMode() {\n return true;\n },\n deepFreezeWhenDevMode,\n tunnelErrorMessage(code: RxErrorKey) {\n if (!ERROR_MESSAGES[code]) {\n console.error('RxDB: Error-Code not known: ' + code);\n throw new Error('Error-Code ' + code + ' not known, contact the maintainer');\n }\n return ERROR_MESSAGES[code];\n }\n },\n hooks: {\n preCreateRxSchema: {\n after: checkSchema\n },\n preCreateRxDatabase: {\n after: function (args: RxDatabaseCreator) {\n ensureDatabaseNameIsValid(args);\n }\n },\n preCreateRxCollection: {\n after: function (args: RxCollectionCreator & { name: string; }) {\n ensureCollectionNameValid(args);\n checkOrmDocumentMethods(args.schema as any, args.methods);\n if (args.name.charAt(0) === '_') {\n throw newRxError('DB2', {\n name: args.name\n });\n }\n if (!args.schema) {\n throw newRxError('DB4', {\n name: args.name,\n args\n });\n }\n }\n },\n preCreateRxQuery: {\n after: function (args) {\n checkQuery(args);\n }\n },\n prePrepareQuery: {\n after: (args) => {\n checkMangoQuery(args);\n }\n },\n createRxCollection: {\n after: (args) => {\n // check ORM-methods\n checkOrmMethods(args.creator.statics);\n checkOrmMethods(args.creator.methods);\n checkOrmMethods(args.creator.attachments);\n\n // check migration strategies\n if (args.creator.schema && args.creator.migrationStrategies) {\n checkMigrationStrategies(\n args.creator.schema,\n args.creator.migrationStrategies\n );\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAOA;AAGA;AAiBA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAA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K,MAAM,EAASL,IAAI,CAACM,OAAO,CAAC;QACzD,IAAIN,IAAI,CAACf,IAAI,CAACsB,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;UAC7B,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;YACpBvB,IAAI,EAAEe,IAAI,CAACf;UACf,CAAC,CAAC;QACN;QACA,IAAI,CAACe,IAAI,CAACK,MAAM,EAAE;UACd,MAAM,IAAAG,mBAAU,EAAC,KAAK,EAAE;YACpBvB,IAAI,EAAEe,IAAI,CAACf,IAAI;YACfe,IAAI,EAAJA;UACJ,CAAC,CAAC;QACN;MACJ;IACJ,CAAC;IACDS,gBAAgB,EAAE;MACdZ,KAAK,EAAE,eAAUG,IAAI,EAAE;QACnB,IAAAU,sBAAU,EAACV,IAAI,CAAC;MACpB;IACJ,CAAC;IACDW,eAAe,EAAE;MACbd,KAAK,EAAE,eAACG,IAAI,EAAK;QACb,IAAAY,2BAAe,EAACZ,IAAI,CAAC;MACzB;IACJ,CAAC;IACDa,kBAAkB,EAAE;MAChBhB,KAAK,EAAE,eAACG,IAAI,EAAK;QACb;QACA,IAAAc,yBAAe,EAACd,IAAI,CAACe,OAAO,CAACC,OAAO,CAAC;QACrC,IAAAF,yBAAe,EAACd,IAAI,CAACe,OAAO,CAACT,OAAO,CAAC;QACrC,IAAAQ,yBAAe,EAACd,IAAI,CAACe,OAAO,CAACE,WAAW,CAAC;;QAEzC;QACA,IAAIjB,IAAI,CAACe,OAAO,CAACV,MAAM,IAAIL,IAAI,CAACe,OAAO,CAACG,mBAAmB,EAAE;UACzD,IAAAC,kDAAwB,EACpBnB,IAAI,CAACe,OAAO,CAACV,MAAM,EACnBL,IAAI,CAACe,OAAO,CAACG,mBAAmB,CACnC;QACL;MACJ;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/dev-mode/unallowed-properties.js b/dist/lib/plugins/dev-mode/unallowed-properties.js index b647b6f0d86..f05addb490c 100644 --- a/dist/lib/plugins/dev-mode/unallowed-properties.js +++ b/dist/lib/plugins/dev-mode/unallowed-properties.js @@ -8,7 +8,7 @@ exports.ensureDatabaseNameIsValid = ensureDatabaseNameIsValid; exports.validateDatabaseName = validateDatabaseName; var _rxError = require("../../rx-error"); var _entityProperties = require("./entity-properties"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); /** * if the name of a collection * clashes with a property of RxDatabase, @@ -30,7 +30,7 @@ function ensureDatabaseNameIsValid(args) { * So we do not allow this. * @link https://github.com/pubkey/rxdb/issues/2251 */ - if ((0, _util.isFolderPath)(args.name)) { + if ((0, _utils.isFolderPath)(args.name)) { if (args.name.endsWith('/') || args.name.endsWith('\\')) { throw (0, _rxError.newRxError)('DB11', { name: args.name @@ -58,7 +58,7 @@ function validateDatabaseName(name) { } // do not check, if foldername is given - if ((0, _util.isFolderPath)(name)) { + if ((0, _utils.isFolderPath)(name)) { return true; } if (!name.match(validCouchDBStringRegex)) { diff --git a/dist/lib/plugins/dev-mode/unallowed-properties.js.map b/dist/lib/plugins/dev-mode/unallowed-properties.js.map index 1fb821f7d5f..eb88371f0af 100644 --- a/dist/lib/plugins/dev-mode/unallowed-properties.js.map +++ b/dist/lib/plugins/dev-mode/unallowed-properties.js.map @@ -1 +1 @@ -{"version":3,"file":"unallowed-properties.js","names":["ensureCollectionNameValid","args","rxDatabaseProperties","includes","name","newRxError","validateDatabaseName","ensureDatabaseNameIsValid","isFolderPath","endsWith","validCouchDBStringRegexStr","validCouchDBStringRegex","RegExp","length","newRxTypeError","match","regex","givenName"],"sources":["../../../../src/plugins/dev-mode/unallowed-properties.ts"],"sourcesContent":["import type { RxCollectionCreator, RxDatabaseCreator } from '../../types';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { rxDatabaseProperties } from './entity-properties';\nimport { isFolderPath } from '../../util';\n\n/**\n * if the name of a collection\n * clashes with a property of RxDatabase,\n * we get problems so this function prohibits this\n */\nexport function ensureCollectionNameValid(\n args: RxCollectionCreator & { name: string; }\n) {\n if (rxDatabaseProperties().includes(args.name)) {\n throw newRxError('DB5', {\n name: args.name\n });\n }\n validateDatabaseName(args.name);\n}\n\nexport function ensureDatabaseNameIsValid(args: RxDatabaseCreator) {\n\n validateDatabaseName(args.name);\n\n /**\n * The server-plugin has problems when a path with and ending slash is given\n * So we do not allow this.\n * @link https://github.com/pubkey/rxdb/issues/2251\n */\n if (isFolderPath(args.name)) {\n if (args.name.endsWith('/') || args.name.endsWith('\\\\')) {\n throw newRxError('DB11', {\n name: args.name,\n });\n }\n }\n}\n\n\n\nconst validCouchDBStringRegexStr = '^[a-z][_$a-z0-9\\\\-]*$';\nconst validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr);\n\n/**\n * Validates that a given string is ok to be used with couchdb-collection-names.\n * We only allow these strings as database- or collection names because it ensures\n * that you later do not get in troubble when you want to use the database together witch couchdb.\n *\n * @link https://docs.couchdb.org/en/stable/api/database/common.html\n * @link https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n * @throws {RxError}\n */\nexport function validateDatabaseName(name: string): true {\n if (\n typeof name !== 'string' ||\n name.length === 0\n ) {\n throw newRxTypeError('UT1', {\n name\n });\n }\n\n\n // do not check, if foldername is given\n if (isFolderPath(name)) {\n return true;\n }\n\n if (!name.match(validCouchDBStringRegex)) {\n throw newRxError('UT2', {\n regex: validCouchDBStringRegexStr,\n givenName: name,\n });\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACO,SAASA,yBAAyB,CACrCC,IAA6C,EAC/C;EACE,IAAI,IAAAC,sCAAoB,GAAE,CAACC,QAAQ,CAACF,IAAI,CAACG,IAAI,CAAC,EAAE;IAC5C,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;MACpBD,IAAI,EAAEH,IAAI,CAACG;IACf,CAAC,CAAC;EACN;EACAE,oBAAoB,CAACL,IAAI,CAACG,IAAI,CAAC;AACnC;AAEO,SAASG,yBAAyB,CAACN,IAAiC,EAAE;EAEzEK,oBAAoB,CAACL,IAAI,CAACG,IAAI,CAAC;;EAE/B;AACJ;AACA;AACA;AACA;EACI,IAAI,IAAAI,kBAAY,EAACP,IAAI,CAACG,IAAI,CAAC,EAAE;IACzB,IAAIH,IAAI,CAACG,IAAI,CAACK,QAAQ,CAAC,GAAG,CAAC,IAAIR,IAAI,CAACG,IAAI,CAACK,QAAQ,CAAC,IAAI,CAAC,EAAE;MACrD,MAAM,IAAAJ,mBAAU,EAAC,MAAM,EAAE;QACrBD,IAAI,EAAEH,IAAI,CAACG;MACf,CAAC,CAAC;IACN;EACJ;AACJ;AAIA,IAAMM,0BAA0B,GAAG,uBAAuB;AAC1D,IAAMC,uBAAuB,GAAG,IAAIC,MAAM,CAACF,0BAA0B,CAAC;;AAEtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASJ,oBAAoB,CAACF,IAAY,EAAQ;EACrD,IACI,OAAOA,IAAI,KAAK,QAAQ,IACxBA,IAAI,CAACS,MAAM,KAAK,CAAC,EACnB;IACE,MAAM,IAAAC,uBAAc,EAAC,KAAK,EAAE;MACxBV,IAAI,EAAJA;IACJ,CAAC,CAAC;EACN;;EAGA;EACA,IAAI,IAAAI,kBAAY,EAACJ,IAAI,CAAC,EAAE;IACpB,OAAO,IAAI;EACf;EAEA,IAAI,CAACA,IAAI,CAACW,KAAK,CAACJ,uBAAuB,CAAC,EAAE;IACtC,MAAM,IAAAN,mBAAU,EAAC,KAAK,EAAE;MACpBW,KAAK,EAAEN,0BAA0B;MACjCO,SAAS,EAAEb;IACf,CAAC,CAAC;EACN;EAEA,OAAO,IAAI;AACf"} \ No newline at end of file +{"version":3,"file":"unallowed-properties.js","names":["ensureCollectionNameValid","args","rxDatabaseProperties","includes","name","newRxError","validateDatabaseName","ensureDatabaseNameIsValid","isFolderPath","endsWith","validCouchDBStringRegexStr","validCouchDBStringRegex","RegExp","length","newRxTypeError","match","regex","givenName"],"sources":["../../../../src/plugins/dev-mode/unallowed-properties.ts"],"sourcesContent":["import type { RxCollectionCreator, RxDatabaseCreator } from '../../types';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { rxDatabaseProperties } from './entity-properties';\nimport { isFolderPath } from '../../plugins/utils';\n\n/**\n * if the name of a collection\n * clashes with a property of RxDatabase,\n * we get problems so this function prohibits this\n */\nexport function ensureCollectionNameValid(\n args: RxCollectionCreator & { name: string; }\n) {\n if (rxDatabaseProperties().includes(args.name)) {\n throw newRxError('DB5', {\n name: args.name\n });\n }\n validateDatabaseName(args.name);\n}\n\nexport function ensureDatabaseNameIsValid(args: RxDatabaseCreator) {\n\n validateDatabaseName(args.name);\n\n /**\n * The server-plugin has problems when a path with and ending slash is given\n * So we do not allow this.\n * @link https://github.com/pubkey/rxdb/issues/2251\n */\n if (isFolderPath(args.name)) {\n if (args.name.endsWith('/') || args.name.endsWith('\\\\')) {\n throw newRxError('DB11', {\n name: args.name,\n });\n }\n }\n}\n\n\n\nconst validCouchDBStringRegexStr = '^[a-z][_$a-z0-9\\\\-]*$';\nconst validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr);\n\n/**\n * Validates that a given string is ok to be used with couchdb-collection-names.\n * We only allow these strings as database- or collection names because it ensures\n * that you later do not get in troubble when you want to use the database together witch couchdb.\n *\n * @link https://docs.couchdb.org/en/stable/api/database/common.html\n * @link https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n * @throws {RxError}\n */\nexport function validateDatabaseName(name: string): true {\n if (\n typeof name !== 'string' ||\n name.length === 0\n ) {\n throw newRxTypeError('UT1', {\n name\n });\n }\n\n\n // do not check, if foldername is given\n if (isFolderPath(name)) {\n return true;\n }\n\n if (!name.match(validCouchDBStringRegex)) {\n throw newRxError('UT2', {\n regex: validCouchDBStringRegexStr,\n givenName: name,\n });\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;AACA;AACA;AAC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BAAU,EAAC,KAAK,EAAE;MACpBW,KAAK,EAAEN,0BAA0B;MACjCO,SAAS,EAAEb;IACf,CAAC,CAAC;EACN;EAEA,OAAO,IAAI;AACf"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/dexie-helper.js.map b/dist/lib/plugins/dexie/dexie-helper.js.map deleted file mode 100644 index 5ab9dc0ce52..00000000000 --- a/dist/lib/plugins/dexie/dexie-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-helper.js","names":["getDocsInDb","internals","docIds","state","Promise","all","dexieTable","bulkGet","dexieDeletedTable","nonDeletedDocsInDb","deletedDocsInDb","docsInDb","slice","forEach","doc","idx","closeDexieDb","statePromise","prevCount","REF_COUNT_PER_DEXIE_DB","get","newCount","dexieDb","close","set","DEXIE_DOCS_TABLE_NAME","DEXIE_DELETED_DOCS_TABLE_NAME","DEXIE_CHANGES_TABLE_NAME","RX_STORAGE_NAME_DEXIE","DEXIE_STATE_DB_BY_NAME","Map","getDexieDbWithTables","databaseName","collectionName","settings","schema","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","dexieDbName","version","useSettings","flatClone","autoOpen","Dexie","dexieStoresSettings","getDexieStoreSchema","stores","open","sortDirectionToMingo","direction","getDexieSortComparator","_schema","query","mingoSortObject","sort","newRxError","sortBlock","key","Object","keys","values","fun","a","b","sorted","getMingoQuery","find","first","next","ensureNoBooleanIndex","indexes","checkedFields","Set","index","fields","Array","isArray","field","has","add","schemaObj","getSchemaByObjectPath","type","DEXIE_PIPE_SUBSTITUTE","dexieReplaceIfStartsWithPipe","str","split","length","map","part","join","startsWith","withoutFirst","substring","dexieReplaceIfStartsWithPipeRevert","fromStorageToDexie","documentData","row","ret","entries","value","fromDexieToStorage","rxJsonSchema","parts","push","arIndex"],"sources":["../../../../src/plugins/dexie/dexie-helper.ts"],"sourcesContent":["import type {\n DeterministicSortComparator\n} from 'event-reduce-js';\nimport type {\n DexieStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { Dexie } from 'dexie';\nimport { DexieSettings } from '../../types';\nimport { flatClone } from '../../util';\nimport { newRxError } from '../../rx-error';\nimport {\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath\n} from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const DEXIE_DOCS_TABLE_NAME = 'docs';\nexport const DEXIE_DELETED_DOCS_TABLE_NAME = 'deleted-docs';\nexport const DEXIE_CHANGES_TABLE_NAME = 'changes';\n\nexport const RX_STORAGE_NAME_DEXIE = 'dexie';\n\nconst DEXIE_STATE_DB_BY_NAME: Map = new Map();\nconst REF_COUNT_PER_DEXIE_DB: Map = new Map();\nexport function getDexieDbWithTables(\n databaseName: string,\n collectionName: string,\n settings: DexieSettings,\n schema: RxJsonSchema\n): DexieStorageInternals {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const dexieDbName = 'rxdb-dexie-' + databaseName + '--' + schema.version + '--' + collectionName;\n let state = DEXIE_STATE_DB_BY_NAME.get(dexieDbName);\n if (!state) {\n state = (async () => {\n /**\n * IndexedDB was not designed for dynamically adding tables on the fly,\n * so we create one dexie database per RxDB storage instance.\n * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696\n */\n const useSettings = flatClone(settings);\n useSettings.autoOpen = false;\n const dexieDb = new Dexie(dexieDbName, useSettings);\n const dexieStoresSettings = {\n [DEXIE_DOCS_TABLE_NAME]: getDexieStoreSchema(schema),\n [DEXIE_CHANGES_TABLE_NAME]: '++sequence, id',\n /**\n * Instead of adding {deleted: false} to every query we run over the document store,\n * we move deleted documents into a separate store where they can only be queried\n * by primary key.\n * This increases performance because it is way easier for the query planner to select\n * a good index and we also do not have to add the _deleted field to every index.\n *\n * We also need the [_meta.lwt+' + primaryPath + '] index for getChangedDocumentsSince()\n */\n [DEXIE_DELETED_DOCS_TABLE_NAME]: primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']'\n };\n\n dexieDb.version(1).stores(dexieStoresSettings);\n await dexieDb.open();\n return {\n dexieDb,\n dexieTable: (dexieDb as any)[DEXIE_DOCS_TABLE_NAME],\n dexieDeletedTable: (dexieDb as any)[DEXIE_DELETED_DOCS_TABLE_NAME]\n };\n })();\n\n DEXIE_STATE_DB_BY_NAME.set(dexieDbName, state);\n REF_COUNT_PER_DEXIE_DB.set(state, 0);\n }\n\n return state;\n}\n\nexport async function closeDexieDb(statePromise: DexieStorageInternals) {\n const state = await statePromise;\n const prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise);\n const newCount = (prevCount as any) - 1;\n if (newCount === 0) {\n state.dexieDb.close();\n REF_COUNT_PER_DEXIE_DB.delete(statePromise);\n } else {\n REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount);\n }\n}\n\n\nfunction sortDirectionToMingo(direction: 'asc' | 'desc'): 1 | -1 {\n if (direction === 'asc') {\n return 1;\n } else {\n return -1;\n }\n}\n\n/**\n * This function is at dexie-helper\n * because we need it in multiple places.\n */\nexport function getDexieSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n const mingoSortObject: {\n [fieldName: string]: 1 | -1;\n } = {};\n\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n\n query.sort.forEach(sortBlock => {\n const key = Object.keys(sortBlock)[0];\n const direction = Object.values(sortBlock)[0];\n mingoSortObject[key] = sortDirectionToMingo(direction);\n });\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n const sorted = getMingoQuery({}).find([a, b], {}).sort(mingoSortObject);\n const first = sorted.next();\n if (first === a) {\n return -1;\n } else {\n return 1;\n }\n };\n\n return fun;\n}\n\n\nexport function ensureNoBooleanIndex(schema: RxJsonSchema) {\n if (!schema.indexes) {\n return;\n }\n const checkedFields = new Set();\n schema.indexes.forEach(index => {\n const fields = Array.isArray(index) ? index : [];\n fields.forEach(field => {\n if (checkedFields.has(field)) {\n return;\n }\n checkedFields.add(field);\n const schemaObj = getSchemaByObjectPath(schema, field);\n if (schemaObj.type === 'boolean') {\n throw newRxError('DXE1', {\n schema,\n index,\n field\n });\n }\n });\n });\n}\n\n\n\n/**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\nexport const DEXIE_PIPE_SUBSTITUTE = '__';\nexport function dexieReplaceIfStartsWithPipe(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipe(part)).join('.');\n }\n\n if (str.startsWith('|')) {\n const withoutFirst = str.substring(1);\n return DEXIE_PIPE_SUBSTITUTE + withoutFirst;\n } else {\n return str;\n }\n}\n\nexport function dexieReplaceIfStartsWithPipeRevert(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipeRevert(part)).join('.');\n }\n\n if (str.startsWith(DEXIE_PIPE_SUBSTITUTE)) {\n const withoutFirst = str.substring(DEXIE_PIPE_SUBSTITUTE.length);\n return '|' + withoutFirst;\n } else {\n return str;\n }\n}\n\n/**\n * @recursive\n */\nexport function fromStorageToDexie(documentData: RxDocumentData): any {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromStorageToDexie(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object') {\n value = fromStorageToDexie(value);\n }\n ret[dexieReplaceIfStartsWithPipe(key)] = value;\n });\n return ret;\n }\n}\n\nexport function fromDexieToStorage(documentData: any): RxDocumentData {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromDexieToStorage(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object' || Array.isArray(documentData)) {\n value = fromDexieToStorage(value);\n }\n ret[dexieReplaceIfStartsWithPipeRevert(key)] = value;\n });\n return ret;\n }\n}\n\n\n/**\n * Creates a string that can be used to create the dexie store.\n * @link https://dexie.org/docs/API-Reference#quick-reference\n */\nexport function getDexieStoreSchema(\n rxJsonSchema: RxJsonSchema\n): string {\n let parts: string[][] = [];\n\n /**\n * First part must be the primary key\n * @link https://github.com/dexie/Dexie.js/issues/1307#issuecomment-846590912\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n parts.push([primaryKey]);\n\n // add other indexes\n if (rxJsonSchema.indexes) {\n rxJsonSchema.indexes.forEach(index => {\n const arIndex = Array.isArray(index) ? index : [index];\n parts.push(arIndex);\n });\n }\n\n // we also need the _meta.lwt+primaryKey index for the getChangedDocumentsSince() method.\n parts.push(['_meta.lwt', primaryKey]);\n\n /**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\n parts = parts.map(part => {\n return part.map(str => dexieReplaceIfStartsWithPipe(str));\n });\n\n return parts.map(part => {\n if (part.length === 1) {\n return part[0];\n } else {\n return '[' + part.join('+') + ']';\n }\n }).join(', ');\n}\n\n/**\n * Returns all documents in the database.\n * Non-deleted plus deleted ones.\n */\nexport async function getDocsInDb(\n internals: DexieStorageInternals,\n docIds: string[]\n): Promise[]> {\n const state = await internals;\n const [\n nonDeletedDocsInDb,\n deletedDocsInDb\n ] = await Promise.all([\n state.dexieTable.bulkGet(docIds),\n state.dexieDeletedTable.bulkGet(docIds)\n ]);\n const docsInDb = deletedDocsInDb.slice(0);\n nonDeletedDocsInDb.forEach((doc, idx) => {\n if (doc) {\n docsInDb[idx] = doc;\n }\n });\n return docsInDb;\n}\n"],"mappings":";;;;;;;;;;;;;;;AASA;AAEA;AACA;AACA;AAIA;AAoQA;AACA;AACA;AACA;AAHA,IAIsBA,W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OAAO,CAAC,UAAA6D,KAAK,EAAI;MAClC,IAAMgC,OAAO,GAAG9B,KAAK,CAACC,OAAO,CAACH,KAAK,CAAC,GAAGA,KAAK,GAAG,CAACA,KAAK,CAAC;MACtD8B,KAAK,CAACC,IAAI,CAACC,OAAO,CAAC;IACvB,CAAC,CAAC;EACN;;EAEA;EACAF,KAAK,CAACC,IAAI,CAAC,CAAC,WAAW,EAAEnE,UAAU,CAAC,CAAC;;EAErC;AACJ;AACA;AACA;AACA;EACIkE,KAAK,GAAGA,KAAK,CAACf,GAAG,CAAC,UAAAC,IAAI,EAAI;IACtB,OAAOA,IAAI,CAACD,GAAG,CAAC,UAAAH,GAAG;MAAA,OAAID,4BAA4B,CAACC,GAAG,CAAC;IAAA,EAAC;EAC7D,CAAC,CAAC;EAEF,OAAOkB,KAAK,CAACf,GAAG,CAAC,UAAAC,IAAI,EAAI;IACrB,IAAIA,IAAI,CAACF,MAAM,KAAK,CAAC,EAAE;MACnB,OAAOE,IAAI,CAAC,CAAC,CAAC;IAClB,CAAC,MAAM;MACH,OAAO,GAAG,GAAGA,IAAI,CAACC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG;IACrC;EACJ,CAAC,CAAC,CAACA,IAAI,CAAC,IAAI,CAAC;AACjB"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/dexie-query.js b/dist/lib/plugins/dexie/dexie-query.js deleted file mode 100644 index 36bf3380cfe..00000000000 --- a/dist/lib/plugins/dexie/dexie-query.js +++ /dev/null @@ -1,188 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.dexieQuery = exports.dexieCount = void 0; -exports.getKeyRangeByQueryPlan = getKeyRangeByQueryPlan; -var _dexieHelper = require("./dexie-helper"); -var _dexieStatics = require("./dexie-statics"); -var dexieCount = function dexieCount(instance, preparedQuery) { - try { - return Promise.resolve(instance.internals).then(function (state) { - var queryPlan = preparedQuery.queryPlan; - var queryPlanFields = queryPlan.index; - var keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); - var count = -1; - return Promise.resolve(state.dexieDb.transaction('r', state.dexieTable, function (dexieTx) { - try { - var tx = dexieTx.idbtrans; - var store = tx.objectStore(_dexieHelper.DEXIE_DOCS_TABLE_NAME); - var index; - if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { - index = store; - } else { - var indexName; - if (queryPlanFields.length === 1) { - indexName = (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(queryPlanFields[0]); - } else { - indexName = '[' + queryPlanFields.map(function (field) { - return (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(field); - }).join('+') + ']'; - } - index = store.index(indexName); - } - var request = index.count(keyRange); - return Promise.resolve(new Promise(function (res, rej) { - request.onsuccess = function () { - res(request.result); - }; - request.onerror = function (err) { - return rej(err); - }; - })).then(function (_Promise) { - count = _Promise; - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return count; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.dexieCount = dexieCount; -/** - * Runs mango queries over the Dexie.js database. - */ -var dexieQuery = function dexieQuery(instance, preparedQuery) { - try { - return Promise.resolve(instance.internals).then(function (state) { - var query = preparedQuery.query; - var skip = query.skip ? query.skip : 0; - var limit = query.limit ? query.limit : Infinity; - var skipPlusLimit = skip + limit; - var queryPlan = preparedQuery.queryPlan; - var queryMatcher = false; - if (!queryPlan.selectorSatisfiedByIndex) { - queryMatcher = _dexieStatics.RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); - } - var keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); - var queryPlanFields = queryPlan.index; - var rows = []; - return Promise.resolve(state.dexieDb.transaction('r', state.dexieTable, function (dexieTx) { - try { - /** - * TODO here we use the native IndexedDB transaction - * to get the cursor. - * Instead we should not leave Dexie.js API and find - * a way to create the cursor with Dexie.js. - */ - var tx = dexieTx.idbtrans; - - // const nativeIndexedDB = state.dexieDb.backendDB(); - // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly'); - - var store = tx.objectStore(_dexieHelper.DEXIE_DOCS_TABLE_NAME); - var index; - if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { - index = store; - } else { - var indexName; - if (queryPlanFields.length === 1) { - indexName = (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(queryPlanFields[0]); - } else { - indexName = '[' + queryPlanFields.map(function (field) { - return (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(field); - }).join('+') + ']'; - } - index = store.index(indexName); - } - var cursorReq = index.openCursor(keyRange); - return Promise.resolve(new Promise(function (res) { - cursorReq.onsuccess = function (e) { - var cursor = e.target.result; - if (cursor) { - // We have a record in cursor.value - var docData = (0, _dexieHelper.fromDexieToStorage)(cursor.value); - if (!docData._deleted && (!queryMatcher || queryMatcher(docData))) { - rows.push(docData); - } - - /** - * If we do not have to manually sort - * and have enough documents, - * we can abort iterating over the cursor - * because we already have every relevant document. - */ - if (queryPlan.sortFieldsSameAsIndexFields && rows.length === skipPlusLimit) { - res(); - } else { - cursor["continue"](); - } - } else { - // Iteration complete - res(); - } - }; - })).then(function () {}); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - if (!queryPlan.sortFieldsSameAsIndexFields) { - var sortComparator = _dexieStatics.RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); - rows = rows.sort(sortComparator); - } - - // apply skip and limit boundaries. - rows = rows.slice(skip, skipPlusLimit); - - /** - * Comment this in for debugging to check all fields in the database. - */ - // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray(); - // let documents = docsInDb - // .map(docData => stripDexieKey(docData)) - // .sort(sortComparator); - // if (preparedQuery.skip) { - // documents = documents.slice(preparedQuery.skip); - // } - // if (preparedQuery.limit && documents.length > preparedQuery.limit) { - // documents = documents.slice(0, preparedQuery.limit); - // } - - return { - documents: rows - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.dexieQuery = dexieQuery; -function getKeyRangeByQueryPlan(queryPlan, IDBKeyRange) { - if (!IDBKeyRange) { - if (typeof window === 'undefined') { - throw new Error('IDBKeyRange missing'); - } else { - IDBKeyRange = window.IDBKeyRange; - } - } - var ret; - /** - * If index has only one field, - * we have to pass the keys directly, not the key arrays. - */ - if (queryPlan.index.length === 1) { - ret = IDBKeyRange.bound(queryPlan.startKeys[0], queryPlan.endKeys[0], queryPlan.inclusiveStart, queryPlan.inclusiveEnd); - } else { - ret = IDBKeyRange.bound(queryPlan.startKeys, queryPlan.endKeys, queryPlan.inclusiveStart, queryPlan.inclusiveEnd); - } - return ret; -} -//# sourceMappingURL=dexie-query.js.map \ No newline at end of file diff --git a/dist/lib/plugins/dexie/dexie-query.js.map b/dist/lib/plugins/dexie/dexie-query.js.map deleted file mode 100644 index ac4db51361d..00000000000 --- a/dist/lib/plugins/dexie/dexie-query.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-query.js","names":["dexieCount","instance","preparedQuery","internals","state","queryPlan","queryPlanFields","index","keyRange","getKeyRangeByQueryPlan","dexieDb","_options","IDBKeyRange","count","transaction","dexieTable","dexieTx","tx","idbtrans","store","objectStore","DEXIE_DOCS_TABLE_NAME","length","primaryPath","indexName","dexieReplaceIfStartsWithPipe","map","field","join","request","Promise","res","rej","onsuccess","result","onerror","err","dexieQuery","query","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","RxStorageDexieStatics","getQueryMatcher","schema","rows","cursorReq","openCursor","e","cursor","target","docData","fromDexieToStorage","value","_deleted","push","sortFieldsSameAsIndexFields","sortComparator","getSortComparator","sort","slice","documents","window","Error","ret","bound","startKeys","endKeys","inclusiveStart","inclusiveEnd"],"sources":["../../../../src/plugins/dexie/dexie-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport type {\n DexiePreparedQuery,\n RxDocumentData,\n RxQueryPlan,\n RxStorageQueryResult\n} from '../../types';\nimport {\n dexieReplaceIfStartsWithPipe,\n DEXIE_DOCS_TABLE_NAME,\n fromDexieToStorage\n} from './dexie-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\nimport type { RxStorageInstanceDexie } from './rx-storage-instance-dexie';\n\n\nexport function getKeyRangeByQueryPlan(\n queryPlan: RxQueryPlan,\n IDBKeyRange?: any\n) {\n if (!IDBKeyRange) {\n if (typeof window === 'undefined') {\n throw new Error('IDBKeyRange missing');\n } else {\n IDBKeyRange = window.IDBKeyRange;\n }\n }\n\n let ret: any;\n /**\n * If index has only one field,\n * we have to pass the keys directly, not the key arrays.\n */\n if (queryPlan.index.length === 1) {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys[0],\n queryPlan.endKeys[0],\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n } else {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys,\n queryPlan.endKeys,\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n }\n return ret;\n}\n\n\n/**\n * Runs mango queries over the Dexie.js database.\n */\nexport async function dexieQuery(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise> {\n const state = await instance.internals;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlan = preparedQuery.queryPlan;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n\n const queryPlanFields: string[] = queryPlan.index;\n\n let rows: any[] = [];\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n /**\n * TODO here we use the native IndexedDB transaction\n * to get the cursor.\n * Instead we should not leave Dexie.js API and find\n * a way to create the cursor with Dexie.js.\n */\n const tx = (dexieTx as any).idbtrans;\n\n // const nativeIndexedDB = state.dexieDb.backendDB();\n // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly');\n\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n const cursorReq = index.openCursor(keyRange);\n await new Promise(res => {\n cursorReq.onsuccess = function (e: any) {\n const cursor = e.target.result;\n if (cursor) {\n // We have a record in cursor.value\n const docData = fromDexieToStorage(cursor.value);\n if (\n !docData._deleted &&\n (!queryMatcher || queryMatcher(docData))\n ) {\n rows.push(docData);\n }\n\n /**\n * If we do not have to manually sort\n * and have enough documents,\n * we can abort iterating over the cursor\n * because we already have every relevant document.\n */\n if (\n queryPlan.sortFieldsSameAsIndexFields &&\n rows.length === skipPlusLimit\n ) {\n res();\n } else {\n cursor.continue();\n }\n } else {\n // Iteration complete\n res();\n }\n };\n });\n\n\n }\n );\n\n\n if (!queryPlan.sortFieldsSameAsIndexFields) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n\n /**\n * Comment this in for debugging to check all fields in the database.\n */\n // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray();\n // let documents = docsInDb\n // .map(docData => stripDexieKey(docData))\n // .sort(sortComparator);\n // if (preparedQuery.skip) {\n // documents = documents.slice(preparedQuery.skip);\n // }\n // if (preparedQuery.limit && documents.length > preparedQuery.limit) {\n // documents = documents.slice(0, preparedQuery.limit);\n // }\n\n\n\n return {\n documents: rows\n };\n}\n\n\nexport async function dexieCount(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise {\n const state = await instance.internals;\n const queryPlan = preparedQuery.queryPlan;\n const queryPlanFields: string[] = queryPlan.index;\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n let count: number = -1;\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n const tx = (dexieTx as any).idbtrans;\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n\n const request = index.count(keyRange);\n count = await new Promise((res, rej) => {\n request.onsuccess = function () {\n res(request.result);\n };\n request.onerror = (err: any) => rej(err);\n });\n }\n );\n return count;\n}\n"],"mappings":";;;;;;;AAOA;AAKA;AAAwD,IAgLlCA,UAAU,YAAVA,UAAU,CAC5BC,QAA2C,EAC3CC,aAA4C;EAAA,IAC7B;IAAA,uBACKD,QAAQ,CAACE,SAAS,iBAAhCC,KAAK;MACX,IAAMC,SAAS,GAAGH,aAAa,CAACG,SAAS;MACzC,IAAMC,eAAyB,GAAGD,SAAS,CAACE,KAAK;MAEjD,IAAMC,QAAQ,GAAGC,sBAAsB,CACnCJ,SAAS,EACRD,KAAK,CAACM,OAAO,CAASC,QAAQ,CAACC,WAAW,CAC9C;MACD,IAAIC,KAAa,GAAG,CAAC,CAAC;MAAC,uBACjBT,KAAK,CAACM,OAAO,CAACI,WAAW,CAC3B,GAAG,EACHV,KAAK,CAACW,UAAU,YACTC,OAAO;QAAA,IAAK;UACf,IAAMC,EAAE,GAA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E7C,aAAa,CAAC;UAC9F8C,IAAI,GAAGA,IAAI,CAACc,IAAI,CAACF,cAAc,CAAC;QACpC;;QAEA;QACAZ,IAAI,GAAGA,IAAI,CAACe,KAAK,CAACxB,IAAI,EAAEG,aAAa,CAAC;;QAEtC;AACJ;AACA;QACI;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAIA,OAAO;UACHsB,SAAS,EAAEhB;QACf,CAAC;MAAC;IAAA;EACN,CAAC;IAAA;EAAA;AAAA;AAAA;AAzKM,SAASvC,sBAAsB,CAClCJ,SAAsB,EACtBO,WAAiB,EACnB;EACE,IAAI,CAACA,WAAW,EAAE;IACd,IAAI,OAAOqD,MAAM,KAAK,WAAW,EAAE;MAC/B,MAAM,IAAIC,KAAK,CAAC,qBAAqB,CAAC;IAC1C,CAAC,MAAM;MACHtD,WAAW,GAAGqD,MAAM,CAACrD,WAAW;IACpC;EACJ;EAEA,IAAIuD,GAAQ;EACZ;AACJ;AACA;AACA;EACI,IAAI9D,SAAS,CAACE,KAAK,CAACe,MAAM,KAAK,CAAC,EAAE;IAC9B6C,GAAG,GAAGvD,WAAW,CAACwD,KAAK,CACnB/D,SAAS,CAACgE,SAAS,CAAC,CAAC,CAAC,EACtBhE,SAAS,CAACiE,OAAO,CAAC,CAAC,CAAC,EACpBjE,SAAS,CAACkE,cAAc,EACxBlE,SAAS,CAACmE,YAAY,CACzB;EACL,CAAC,MAAM;IACHL,GAAG,GAAGvD,WAAW,CAACwD,KAAK,CACnB/D,SAAS,CAACgE,SAAS,EACnBhE,SAAS,CAACiE,OAAO,EACjBjE,SAAS,CAACkE,cAAc,EACxBlE,SAAS,CAACmE,YAAY,CACzB;EACL;EACA,OAAOL,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/dexie-statics.js.map b/dist/lib/plugins/dexie/dexie-statics.js.map deleted file mode 100644 index 164afe51953..00000000000 --- a/dist/lib/plugins/dexie/dexie-statics.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-statics.js","names":["RxStorageDexieStatics","prepareQuery","schema","mutateableQuery","sort","newRxError","query","queryPlan","getQueryPlan","getSortComparator","preparedQuery","getDexieSortComparator","getQueryMatcher","_schema","mingoQuery","getMingoQuery","selector","fun","doc","_deleted","cursor","find","next","checkpointSchema","DEFAULT_CHECKPOINT_SCHEMA"],"sources":["../../../../src/plugins/dexie/dexie-statics.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n RxDocumentData,\n RxJsonSchema,\n RxStorageStatics,\n DexiePreparedQuery,\n FilledMangoQuery\n} from '../../types';\nimport {\n getDexieSortComparator\n} from './dexie-helper';\nimport { newRxError } from '../../rx-error';\nimport { getQueryPlan } from '../../query-planner';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const RxStorageDexieStatics: RxStorageStatics = {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): DexiePreparedQuery {\n\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n },\n\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: DexiePreparedQuery\n ): DeterministicSortComparator {\n return getDexieSortComparator(schema, preparedQuery.query);\n },\n\n getQueryMatcher(\n _schema: RxJsonSchema,\n preparedQuery: DexiePreparedQuery\n ): QueryMatcher> {\n const query = preparedQuery.query;\n const mingoQuery = getMingoQuery(query.selector);\n const fun: QueryMatcher> = (doc: RxDocumentData) => {\n if (doc._deleted) {\n return false;\n }\n const cursor = mingoQuery.find([doc]);\n const next = cursor.next();\n if (next) {\n return true;\n } else {\n return false;\n }\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n\n};\n"],"mappings":";;;;;;AAWA;AAGA;AACA;AACA;AACA;AAEO,IAAMA,qBAAuC,GAAG;EACnDC,YAAY,wBACRC,MAA+C,EAC/CC,eAA4C,EACf;IAE7B,IAAI,CAACA,eAAe,CAACC,IAAI,EAAE;MACvB,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;QACpBC,KAAK,EAAEH;MACX,CAAC,CAAC;IACN;;IAEA;AACR;AACA;AACA;IACQ,IAAMI,SAAS,GAAG,IAAAC,0BAAY,EAC1BN,MAAM,EACNC,eAAe,CAClB;IAED,OAAO;MACHG,KAAK,EAAEH,eAAe;MACtBI,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAEDE,iBAAiB,6BACbP,MAA+C,EAC/CQ,aAA4C,EACN;IACtC,OAAO,IAAAC,mCAAsB,EAACT,MAAM,EAAEQ,aAAa,CAACJ,KAAK,CAAC;EAC9D,CAAC;EAEDM,eAAe,2BACXC,OAAgC,EAChCH,aAA4C,EACL;IACvC,IAAMJ,KAAK,GAAGI,aAAa,CAACJ,KAAK;IACjC,IAAMQ,UAAU,GAAG,IAAAC,2BAAa,EAACT,KAAK,CAACU,QAAQ,CAAC;IAChD,IAAMC,GAA4C,GAAG,SAA/CA,GAA4C,CAAIC,GAA8B,EAAK;MACrF,IAAIA,GAAG,CAACC,QAAQ,EAAE;QACd,OAAO,KAAK;MAChB;MACA,IAAMC,MAAM,GAAGN,UAAU,CAACO,IAAI,CAAC,CAACH,GAAG,CAAC,CAAC;MACrC,IAAMI,IAAI,GAAGF,MAAM,CAACE,IAAI,EAAE;MAC1B,IAAIA,IAAI,EAAE;QACN,OAAO,IAAI;MACf,CAAC,MAAM;QACH,OAAO,KAAK;MAChB;IACJ,CAAC;IACD,OAAOL,GAAG;EACd,CAAC;EAEDM,gBAAgB,EAAEC;AAEtB,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/index.js.map b/dist/lib/plugins/dexie/index.js.map deleted file mode 100644 index 5f4ca4474bb..00000000000 --- a/dist/lib/plugins/dexie/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/dexie/index.ts"],"sourcesContent":["export * from './rx-storage-dexie';\nexport * from './rx-storage-instance-dexie';\nexport * from './dexie-helper';\nexport * from './dexie-query';\nexport * from './dexie-statics';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/rx-storage-dexie.js.map b/dist/lib/plugins/dexie/rx-storage-dexie.js.map deleted file mode 100644 index 62a661fb853..00000000000 --- a/dist/lib/plugins/dexie/rx-storage-dexie.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-dexie.js","names":["RxStorageDexie","settings","name","RX_STORAGE_NAME_DEXIE","statics","RxStorageDexieStatics","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","ensureNoBooleanIndex","schema","createDexieStorageInstance","getRxStorageDexie","storage"],"sources":["../../../../src/plugins/dexie/rx-storage-dexie.ts"],"sourcesContent":["import type {\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNoBooleanIndex,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport type {\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport {\n createDexieStorageInstance,\n RxStorageInstanceDexie\n} from './rx-storage-instance-dexie';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\n\n\n\nexport class RxStorageDexie implements RxStorage {\n public name = RX_STORAGE_NAME_DEXIE;\n public statics = RxStorageDexieStatics;\n\n constructor(\n public settings: DexieSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n ensureNoBooleanIndex(params.schema);\n return createDexieStorageInstance(this, params, this.settings);\n }\n}\n\n\nexport function getRxStorageDexie(\n settings: DexieSettings = {}\n): RxStorageDexie {\n const storage = new RxStorageDexie(settings);\n return storage;\n}\n"],"mappings":";;;;;;;AAIA;AAQA;AAIA;AACA;AAAwD,IAI3CA,cAAc;EAIvB,wBACWC,QAAuB,EAChC;IAAA,KALKC,IAAI,GAAGC,kCAAqB;IAAA,KAC5BC,OAAO,GAAGC,mCAAqB;IAAA,KAG3BJ,QAAuB,GAAvBA,QAAuB;EAC9B;EAAC;EAAA,OAEEK,qBAAqB,GAA5B,+BACIC,MAAiE,EACvB;IAC1C,IAAAC,wDAAuC,EAACD,MAAM,CAAC;IAC/C,IAAAE,iCAAoB,EAACF,MAAM,CAACG,MAAM,CAAC;IACnC,OAAO,IAAAC,kDAA0B,EAAC,IAAI,EAAEJ,MAAM,EAAE,IAAI,CAACN,QAAQ,CAAC;EAClE,CAAC;EAAA;AAAA;AAAA;AAIE,SAASW,iBAAiB,GAEf;EAAA,IADdX,QAAuB,uEAAG,CAAC,CAAC;EAE5B,IAAMY,OAAO,GAAG,IAAIb,cAAc,CAACC,QAAQ,CAAC;EAC5C,OAAOY,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/rx-storage-instance-dexie.js b/dist/lib/plugins/dexie/rx-storage-instance-dexie.js deleted file mode 100644 index 6b1141d2ae1..00000000000 --- a/dist/lib/plugins/dexie/rx-storage-instance-dexie.js +++ /dev/null @@ -1,299 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxStorageInstanceDexie = void 0; -exports.createDexieStorageInstance = createDexieStorageInstance; -var _rxjs = require("rxjs"); -var _util = require("../../util"); -var _dexieHelper = require("./dexie-helper"); -var _dexieQuery = require("./dexie-query"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _rxStorageHelper = require("../../rx-storage-helper"); -var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); -var _rxError = require("../../rx-error"); -var instanceId = (0, _util.now)(); -var RxStorageInstanceDexie = /*#__PURE__*/function () { - function RxStorageInstanceDexie(storage, databaseName, collectionName, schema, internals, options, settings) { - this.changes$ = new _rxjs.Subject(); - this.instanceId = instanceId++; - this.closed = false; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - this.settings = settings; - this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); - } - var _proto = RxStorageInstanceDexie.prototype; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this = this; - ensureNotClosed(_this); - return Promise.resolve(_this.internals).then(function (state) { - var ret = { - success: {}, - error: {} - }; - var documentKeys = documentWrites.map(function (writeRow) { - return writeRow.document[_this.primaryPath]; - }); - var categorized = null; - return Promise.resolve(state.dexieDb.transaction('rw', state.dexieTable, state.dexieDeletedTable, function () { - try { - var docsInDbMap = new Map(); - return Promise.resolve((0, _dexieHelper.getDocsInDb)(_this.internals, documentKeys)).then(function (docsInDbWithInternals) { - docsInDbWithInternals.forEach(function (docWithDexieInternals) { - var doc = docWithDexieInternals ? (0, _dexieHelper.fromDexieToStorage)(docWithDexieInternals) : docWithDexieInternals; - if (doc) { - docsInDbMap.set(doc[_this.primaryPath], doc); - } - return doc; - }); - categorized = (0, _rxStorageHelper.categorizeBulkWriteRows)(_this, _this.primaryPath, docsInDbMap, documentWrites, context); - ret.error = categorized.errors; - - /** - * Batch up the database operations - * so we can later run them in bulk. - */ - var bulkPutDocs = []; - var bulkRemoveDocs = []; - var bulkPutDeletedDocs = []; - var bulkRemoveDeletedDocs = []; - categorized.bulkInsertDocs.forEach(function (row) { - var docId = row.document[_this.primaryPath]; - ret.success[docId] = row.document; - bulkPutDocs.push(row.document); - }); - categorized.bulkUpdateDocs.forEach(function (row) { - var docId = row.document[_this.primaryPath]; - ret.success[docId] = row.document; - if (row.document._deleted && row.previous && !row.previous._deleted) { - // newly deleted - bulkRemoveDocs.push(docId); - bulkPutDeletedDocs.push(row.document); - } else if (row.document._deleted && row.previous && row.previous._deleted) { - // deleted was modified but is still deleted - bulkPutDeletedDocs.push(row.document); - } else if (!row.document._deleted) { - // non-deleted was changed - bulkPutDocs.push(row.document); - } else { - throw (0, _rxError.newRxError)('SNH', { - args: { - row: row - } - }); - } - }); - return Promise.resolve(Promise.all([bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(function (d) { - return (0, _dexieHelper.fromStorageToDexie)(d); - })) : _util.PROMISE_RESOLVE_VOID, bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : _util.PROMISE_RESOLVE_VOID, bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(function (d) { - return (0, _dexieHelper.fromStorageToDexie)(d); - })) : _util.PROMISE_RESOLVE_VOID, bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : _util.PROMISE_RESOLVE_VOID])).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - if ((0, _util.ensureNotFalsy)(categorized).eventBulk.events.length > 0) { - var lastState = (0, _rxStorageHelper.getNewestOfDocumentStates)(_this.primaryPath, Object.values(ret.success)); - (0, _util.ensureNotFalsy)(categorized).eventBulk.checkpoint = { - id: lastState[_this.primaryPath], - lwt: lastState._meta.lwt - }; - var endTime = (0, _util.now)(); - (0, _util.ensureNotFalsy)(categorized).eventBulk.events.forEach(function (event) { - return event.endTime = endTime; - }); - _this.changes$.next((0, _util.ensureNotFalsy)(categorized).eventBulk); - } - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - try { - var _this2 = this; - ensureNotClosed(_this2); - return Promise.resolve(_this2.internals).then(function (state) { - var ret = {}; - return Promise.resolve(state.dexieDb.transaction('r', state.dexieTable, state.dexieDeletedTable, function () { - try { - var _temp2 = function _temp2() { - ids.forEach(function (id, idx) { - var documentInDb = docsInDb[idx]; - if (documentInDb && (!documentInDb._deleted || deleted)) { - ret[id] = (0, _dexieHelper.fromDexieToStorage)(documentInDb); - } - }); - }; - var docsInDb; - var _temp = function () { - if (deleted) { - return Promise.resolve((0, _dexieHelper.getDocsInDb)(_this2.internals, ids)).then(function (_getDocsInDb) { - docsInDb = _getDocsInDb; - }); - } else { - return Promise.resolve(state.dexieTable.bulkGet(ids)).then(function (_state$dexieTable$bul) { - docsInDb = _state$dexieTable$bul; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - ensureNotClosed(this); - return (0, _dexieQuery.dexieQuery)(this, preparedQuery); - }; - _proto.count = function count(preparedQuery) { - try { - var _this3 = this; - return Promise.resolve((0, _dexieQuery.dexieCount)(_this3, preparedQuery)).then(function (result) { - return { - count: result, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _this4 = this; - ensureNotClosed(_this4); - var sinceLwt = checkpoint ? checkpoint.lwt : _util.RX_META_LWT_MINIMUM; - var sinceId = checkpoint ? checkpoint.id : ''; - return Promise.resolve(_this4.internals).then(function (state) { - return Promise.resolve(Promise.all([state.dexieTable, state.dexieDeletedTable].map(function (table) { - try { - var query = table.where('[_meta.lwt+' + _this4.primaryPath + ']').above([sinceLwt, sinceId]).limit(limit); - return Promise.resolve(query.toArray()).then(function (changedDocuments) { - return changedDocuments.map(function (d) { - return (0, _dexieHelper.fromDexieToStorage)(d); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function (_ref) { - var changedDocsNormal = _ref[0], - changedDocsDeleted = _ref[1]; - var changedDocs = changedDocsNormal.concat(changedDocsDeleted); - changedDocs = (0, _util.sortDocumentsByLastWriteTime)(_this4.primaryPath, changedDocs); - changedDocs = changedDocs.slice(0, limit); - var lastDoc = (0, _util.lastOfArray)(changedDocs); - return { - documents: changedDocs, - checkpoint: lastDoc ? { - id: lastDoc[_this4.primaryPath], - lwt: lastDoc._meta.lwt - } : checkpoint ? checkpoint : { - id: '', - lwt: 0 - } - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.remove = function remove() { - try { - var _this5 = this; - ensureNotClosed(_this5); - return Promise.resolve(_this5.internals).then(function (state) { - return Promise.resolve(Promise.all([state.dexieDeletedTable.clear(), state.dexieTable.clear()])).then(function () { - return _this5.close(); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.changeStream = function changeStream() { - ensureNotClosed(this); - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(minimumDeletedTime) { - try { - var _this6 = this; - ensureNotClosed(_this6); - return Promise.resolve(_this6.internals).then(function (state) { - return Promise.resolve(state.dexieDb.transaction('rw', state.dexieDeletedTable, function () { - try { - var maxDeletionTime = (0, _util.now)() - minimumDeletedTime; - return Promise.resolve(state.dexieDeletedTable.where('_meta.lwt').below(maxDeletionTime).toArray()).then(function (toRemove) { - var removeIds = toRemove.map(function (doc) { - return doc[_this6.primaryPath]; - }); - return Promise.resolve(state.dexieDeletedTable.bulkDelete(removeIds)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - /** - * TODO instead of deleting all deleted docs at once, - * only clean up some of them and return false if there are more documents to clean up. - * This ensures that when many documents have to be purged, - * we do not block the more important tasks too long. - */ - return true; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { - ensureNotClosed(this); - throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.'); - }; - _proto.close = function close() { - ensureNotClosed(this); - this.closed = true; - this.changes$.complete(); - (0, _dexieHelper.closeDexieDb)(this.internals); - return _util.PROMISE_RESOLVE_VOID; - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new _rxjs.Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstanceDexie; -}(); -exports.RxStorageInstanceDexie = RxStorageInstanceDexie; -function createDexieStorageInstance(storage, params, settings) { - var internals = (0, _dexieHelper.getDexieDbWithTables)(params.databaseName, params.collectionName, settings, params.schema); - var instance = new RxStorageInstanceDexie(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); - (0, _rxStorageMultiinstance.addRxStorageMultiInstanceSupport)(_dexieHelper.RX_STORAGE_NAME_DEXIE, params, instance); - return Promise.resolve(instance); -} -function ensureNotClosed(instance) { - if (instance.closed) { - throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName); - } -} -//# sourceMappingURL=rx-storage-instance-dexie.js.map \ No newline at end of file diff --git a/dist/lib/plugins/dexie/rx-storage-instance-dexie.js.map b/dist/lib/plugins/dexie/rx-storage-instance-dexie.js.map deleted file mode 100644 index 32bd91579f0..00000000000 --- a/dist/lib/plugins/dexie/rx-storage-instance-dexie.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-dexie.js","names":["instanceId","now","RxStorageInstanceDexie","storage","databaseName","collectionName","schema","internals","options","settings","changes$","Subject","closed","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","bulkWrite","documentWrites","context","ensureNotClosed","state","ret","success","error","documentKeys","map","writeRow","document","categorized","dexieDb","transaction","dexieTable","dexieDeletedTable","docsInDbMap","Map","getDocsInDb","docsInDbWithInternals","forEach","docWithDexieInternals","doc","fromDexieToStorage","set","categorizeBulkWriteRows","errors","bulkPutDocs","bulkRemoveDocs","bulkPutDeletedDocs","bulkRemoveDeletedDocs","bulkInsertDocs","row","docId","push","bulkUpdateDocs","_deleted","previous","newRxError","args","Promise","all","length","bulkPut","d","fromStorageToDexie","PROMISE_RESOLVE_VOID","bulkDelete","ensureNotFalsy","eventBulk","events","lastState","getNewestOfDocumentStates","Object","values","checkpoint","id","lwt","_meta","endTime","event","next","findDocumentsById","ids","deleted","idx","documentInDb","docsInDb","bulkGet","query","preparedQuery","dexieQuery","count","dexieCount","result","mode","getChangedDocumentsSince","limit","sinceLwt","RX_META_LWT_MINIMUM","sinceId","table","where","above","toArray","changedDocuments","changedDocsNormal","changedDocsDeleted","changedDocs","concat","sortDocumentsByLastWriteTime","slice","lastDoc","lastOfArray","documents","remove","clear","close","changeStream","asObservable","cleanup","minimumDeletedTime","maxDeletionTime","below","toRemove","removeIds","getAttachmentData","_documentId","_attachmentId","Error","complete","closeDexieDb","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","createDexieStorageInstance","params","getDexieDbWithTables","instance","addRxStorageMultiInstanceSupport","RX_STORAGE_NAME_DEXIE","resolve"],"sources":["../../../../src/plugins/dexie/rx-storage-instance-dexie.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n now,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM,\n sortDocumentsByLastWriteTime,\n lastOfArray,\n ensureNotFalsy\n} from '../../util';\nimport type {\n RxStorageInstance,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n RxStorageInstanceCreationParams,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n RxStorageCountResult\n} from '../../types';\nimport {\n DexiePreparedQuery,\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport { RxStorageDexie } from './rx-storage-dexie';\nimport {\n closeDexieDb,\n fromDexieToStorage,\n fromStorageToDexie,\n getDexieDbWithTables,\n getDocsInDb,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport { dexieCount, dexieQuery } from './dexie-query';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance';\nimport { newRxError } from '../../rx-error';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceDexie implements RxStorageInstance<\nRxDocType,\nDexieStorageInternals,\nDexieSettings,\nRxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageDexie,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: DexieStorageInternals,\n public readonly options: Readonly,\n public readonly settings: DexieSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const documentKeys: string[] = documentWrites.map(writeRow => writeRow.document[this.primaryPath] as any);\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n const docsInDbMap = new Map>();\n const docsInDbWithInternals = await getDocsInDb(this.internals, documentKeys);\n docsInDbWithInternals.forEach(docWithDexieInternals => {\n const doc = docWithDexieInternals ? fromDexieToStorage(docWithDexieInternals) : docWithDexieInternals;\n if (doc) {\n docsInDbMap.set(doc[this.primaryPath], doc);\n }\n return doc;\n });\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDbMap,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Batch up the database operations\n * so we can later run them in bulk.\n */\n const bulkPutDocs: any[] = [];\n const bulkRemoveDocs: string[] = [];\n const bulkPutDeletedDocs: any[] = [];\n const bulkRemoveDeletedDocs: string[] = [];\n\n categorized.bulkInsertDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n bulkPutDocs.push(row.document);\n });\n categorized.bulkUpdateDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n if (\n row.document._deleted &&\n (row.previous && !row.previous._deleted)\n ) {\n // newly deleted\n bulkRemoveDocs.push(docId);\n bulkPutDeletedDocs.push(row.document);\n } else if (\n row.document._deleted &&\n row.previous && row.previous._deleted\n ) {\n // deleted was modified but is still deleted\n bulkPutDeletedDocs.push(row.document);\n } else if (!row.document._deleted) {\n // non-deleted was changed\n bulkPutDocs.push(row.document);\n } else {\n throw newRxError('SNH', { args: { row } });\n }\n });\n\n await Promise.all([\n bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : PROMISE_RESOLVE_VOID,\n bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : PROMISE_RESOLVE_VOID\n ]);\n });\n\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n const endTime = now();\n ensureNotFalsy(categorized).eventBulk.events.forEach(event => (event as any).endTime = endTime);\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n\n return ret;\n }\n\n async findDocumentsById(\n ids: string[],\n deleted: boolean\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxDocumentDataById = {};\n\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n let docsInDb: RxDocumentData[];\n if (deleted) {\n docsInDb = await getDocsInDb(this.internals, ids);\n } else {\n docsInDb = await state.dexieTable.bulkGet(ids);\n }\n ids.forEach((id, idx) => {\n const documentInDb = docsInDb[idx];\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = fromDexieToStorage(documentInDb);\n }\n });\n });\n return ret;\n }\n\n query(preparedQuery: DexiePreparedQuery): Promise> {\n ensureNotClosed(this);\n return dexieQuery(\n this,\n preparedQuery\n );\n }\n async count(\n preparedQuery: DexiePreparedQuery\n ): Promise {\n const result = await dexieCount(this, preparedQuery);\n return {\n count: result,\n mode: 'fast'\n };\n }\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n ensureNotClosed(this);\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n const state = await this.internals;\n\n\n const [changedDocsNormal, changedDocsDeleted] = await Promise.all(\n [\n state.dexieTable,\n state.dexieDeletedTable\n ].map(async (table) => {\n const query = table\n .where('[_meta.lwt+' + this.primaryPath + ']')\n .above([sinceLwt, sinceId])\n .limit(limit);\n const changedDocuments: RxDocumentData[] = await query.toArray();\n return changedDocuments.map(d => fromDexieToStorage(d));\n })\n );\n let changedDocs = changedDocsNormal.concat(changedDocsDeleted);\n\n changedDocs = sortDocumentsByLastWriteTime(this.primaryPath as any, changedDocs);\n changedDocs = changedDocs.slice(0, limit);\n\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n async remove(): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await Promise.all([\n state.dexieDeletedTable.clear(),\n state.dexieTable.clear()\n ]);\n return this.close();\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotClosed(this);\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieDeletedTable,\n async () => {\n const maxDeletionTime = now() - minimumDeletedTime;\n const toRemove = await state.dexieDeletedTable\n .where('_meta.lwt')\n .below(maxDeletionTime)\n .toArray();\n const removeIds: string[] = toRemove.map(doc => doc[this.primaryPath]);\n await state.dexieDeletedTable.bulkDelete(removeIds);\n }\n );\n\n /**\n * TODO instead of deleting all deleted docs at once,\n * only clean up some of them and return false if there are more documents to clean up.\n * This ensures that when many documents have to be purged,\n * we do not block the more important tasks too long.\n */\n return true;\n }\n\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n ensureNotClosed(this);\n throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.');\n }\n\n close(): Promise {\n ensureNotClosed(this);\n this.closed = true;\n this.changes$.complete();\n closeDexieDb(this.internals);\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\n\nexport function createDexieStorageInstance(\n storage: RxStorageDexie,\n params: RxStorageInstanceCreationParams,\n settings: DexieSettings\n): Promise> {\n const internals = getDexieDbWithTables(\n params.databaseName,\n params.collectionName,\n settings,\n params.schema\n );\n\n const instance = new RxStorageInstanceDexie(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_DEXIE,\n params,\n instance\n );\n\n return Promise.resolve(instance);\n}\n\n\n\nfunction ensureNotClosed(\n instance: RxStorageInstanceDexie\n) {\n if (instance.closed) {\n throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName);\n }\n}\n"],"mappings":";;;;;;;AAAA;AAIA;AAgCA;AAQA;AACA;AACA;AACA;AACA;AAEA,IAAIA,UAAU,GAAG,IAAAC,SAAG,GAAE;AAAC,IAEVC,sBAAsB;EAW/B,gCACoBC,OAAuB,EACvBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAAgC,EAChCC,OAAgC,EAChCC,QAAuB,EACzC;IAAA,KAZMC,QAAQ,GAAoG,IAAIC,aAAO,EAAE;IAAA,KACjHX,UAAU,GAAGA,UAAU,EAAE;IAAA,KAClCY,MAAM,GAAG,KAAK;IAAA,KAGDT,OAAuB,GAAvBA,OAAuB;IAAA,KACvBC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAAgC,GAAhCA,SAAgC;IAAA,KAChCC,OAAgC,GAAhCA,OAAgC;IAAA,KAChCC,QAAuB,GAAvBA,QAAuB;IAEvC,IAAI,CAACI,WAAW,GAAG,IAAAC,2CAA2B,EAAC,IAAI,CAACR,MAAM,CAACS,UAAU,CAAC;EAC1E;EAAC;EAAA,OAEKC,SAAS,sBACXC,cAAyC,EACzCC,OAAe;IAAA,IAC+B;MAAA,YAC9B,IAAI;MAApB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,MAAiE,EACjE5H,QAAuB,EACmB;EAC1C,IAAMF,SAAS,GAAG,IAAA+H,iCAAoB,EAClCD,MAAM,CAACjI,YAAY,EACnBiI,MAAM,CAAChI,cAAc,EACrBI,QAAQ,EACR4H,MAAM,CAAC/H,MAAM,CAChB;EAED,IAAMiI,QAAQ,GAAG,IAAIrI,sBAAsB,CACvCC,OAAO,EACPkI,MAAM,CAACjI,YAAY,EACnBiI,MAAM,CAAChI,cAAc,EACrBgI,MAAM,CAAC/H,MAAM,EACbC,SAAS,EACT8H,MAAM,CAAC7H,OAAO,EACdC,QAAQ,CACX;EAED,IAAA+H,wDAAgC,EAC5BC,kCAAqB,EACrBJ,MAAM,EACNE,QAAQ,CACX;EAED,OAAO9E,OAAO,CAACiF,OAAO,CAACH,QAAQ,CAAC;AACpC;AAIA,SAASpH,eAAe,CACpBoH,QAAqC,EACvC;EACE,IAAIA,QAAQ,CAAC3H,MAAM,EAAE;IACjB,MAAM,IAAIkH,KAAK,CAAC,mCAAmC,GAAGS,QAAQ,CAACnI,YAAY,GAAG,GAAG,GAAGmI,QAAQ,CAAClI,cAAc,CAAC;EAChH;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/encryption/index.js b/dist/lib/plugins/encryption/index.js index 5c2a61af964..46459c560d1 100644 --- a/dist/lib/plugins/encryption/index.js +++ b/dist/lib/plugins/encryption/index.js @@ -8,6 +8,8 @@ exports.MINIMUM_PASSWORD_LENGTH = void 0; exports.decryptString = decryptString; exports.encryptString = encryptString; exports.wrappedKeyEncryptionStorage = wrappedKeyEncryptionStorage; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _aes = _interopRequireDefault(require("crypto-js/aes")); var cryptoEnc = _interopRequireWildcard(require("crypto-js/enc-utf8")); var _objectPath = _interopRequireDefault(require("object-path")); @@ -15,18 +17,7 @@ var _pluginHelpers = require("../../plugin-helpers"); var _rxDatabaseInternalStore = require("../../rx-database-internal-store"); var _rxError = require("../../rx-error"); var _rxStorageHelper = require("../../rx-storage-helper"); -var _util = require("../../util"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} +var _utils = require("../../plugins/utils"); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** @@ -60,120 +51,129 @@ function decryptString(cipherText, password) { } function wrappedKeyEncryptionStorage(args) { return Object.assign({}, args.storage, { - createStorageInstance: function createStorageInstance(params) { - try { - var _temp4 = function _temp4(_result) { - if (_exit) return _result; - if (!params.password) { - throw (0, _rxError.newRxError)('EN3', { - database: params.databaseName, - collection: params.collectionName, - schema: params.schema - }); - } - var password = params.password; - var schemaWithoutEncrypted = (0, _util.clone)(params.schema); - delete schemaWithoutEncrypted.encrypted; - if (schemaWithoutEncrypted.attachments) { - schemaWithoutEncrypted.attachments.encrypted = false; - } - function modifyToStorage(docData) { - docData = cloneWithoutAttachments(docData); - (0, _util.ensureNotFalsy)(params.schema.encrypted).forEach(function (path) { - var value = _objectPath["default"].get(docData, path); - if (typeof value === 'undefined') { - return; - } - var stringValue = JSON.stringify(value); - var encrypted = encryptString(stringValue, password); - _objectPath["default"].set(docData, path, encrypted); - }); + createStorageInstance: function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var retInstance, password, schemaWithoutEncrypted, instance, modifyToStorage, modifyFromStorage, modifyAttachmentFromStorage; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + modifyAttachmentFromStorage = function _modifyAttachmentFrom(attachmentData) { + if (params.schema.attachments && params.schema.attachments.encrypted) { + var decrypted = decryptString((0, _utils.b64DecodeUnicode)(attachmentData), password); + return decrypted; + } else { + return attachmentData; + } + }; + modifyFromStorage = function _modifyFromStorage(docData) { + docData = cloneWithoutAttachments(docData); + (0, _utils.ensureNotFalsy)(params.schema.encrypted).forEach(function (path) { + var value = _objectPath["default"].get(docData, path); + if (typeof value === 'undefined') { + return; + } + var decrypted = decryptString(value, password); + var decryptedParsed = JSON.parse(decrypted); + _objectPath["default"].set(docData, path, decryptedParsed); + }); + return docData; + }; + modifyToStorage = function _modifyToStorage(docData) { + docData = cloneWithoutAttachments(docData); + (0, _utils.ensureNotFalsy)(params.schema.encrypted).forEach(function (path) { + var value = _objectPath["default"].get(docData, path); + if (typeof value === 'undefined') { + return; + } + var stringValue = JSON.stringify(value); + var encrypted = encryptString(stringValue, password); + _objectPath["default"].set(docData, path, encrypted); + }); - // handle attachments - if (params.schema.attachments && params.schema.attachments.encrypted) { - var newAttachments = {}; - Object.entries(docData._attachments).forEach(function (_ref) { - var id = _ref[0], - attachment = _ref[1]; - var useAttachment = (0, _util.flatClone)(attachment); - if (useAttachment.data) { - var dataString = useAttachment.data; - useAttachment.data = (0, _util.b64EncodeUnicode)(encryptString(dataString, password)); + // handle attachments + if (params.schema.attachments && params.schema.attachments.encrypted) { + var newAttachments = {}; + Object.entries(docData._attachments).forEach(function (_ref) { + var id = _ref[0], + attachment = _ref[1]; + var useAttachment = (0, _utils.flatClone)(attachment); + if (useAttachment.data) { + var dataString = useAttachment.data; + useAttachment.data = (0, _utils.b64EncodeUnicode)(encryptString(dataString, password)); + } + newAttachments[id] = useAttachment; + }); + docData._attachments = newAttachments; } - newAttachments[id] = useAttachment; - }); - docData._attachments = newAttachments; - } - return docData; - } - function modifyFromStorage(docData) { - docData = cloneWithoutAttachments(docData); - (0, _util.ensureNotFalsy)(params.schema.encrypted).forEach(function (path) { - var value = _objectPath["default"].get(docData, path); - if (typeof value === 'undefined') { - return; + return docData; + }; + if ((0, _rxStorageHelper.hasEncryption)(params.schema)) { + _context.next = 18; + break; } - var decrypted = decryptString(value, password); - var decryptedParsed = JSON.parse(decrypted); - _objectPath["default"].set(docData, path, decryptedParsed); - }); - return docData; - } - function modifyAttachmentFromStorage(attachmentData) { - if (params.schema.attachments && params.schema.attachments.encrypted) { - var decrypted = decryptString((0, _util.b64DecodeUnicode)(attachmentData), password); - return decrypted; - } else { - return attachmentData; - } - } - return Promise.resolve(args.storage.createStorageInstance(Object.assign({}, params, { - schema: schemaWithoutEncrypted - }))).then(function (instance) { - return (0, _pluginHelpers.wrapRxStorageInstance)(instance, modifyToStorage, modifyFromStorage, modifyAttachmentFromStorage); - }); - }; - var _exit = false; - var _temp3 = function () { - if (!(0, _rxStorageHelper.hasEncryption)(params.schema)) { - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (retInstance) { - var _exit2 = false; - function _temp2(_result3) { - if (_exit2) return _result3; - _exit = true; - return retInstance; + _context.next = 6; + return args.storage.createStorageInstance(params); + case 6: + retInstance = _context.sent; + if (!(params.schema.title === _rxDatabaseInternalStore.INTERNAL_STORE_SCHEMA_TITLE && params.password)) { + _context.next = 17; + break; } - var _temp = function () { - if (params.schema.title === _rxDatabaseInternalStore.INTERNAL_STORE_SCHEMA_TITLE && params.password) { - return _catch(function () { - validatePassword(params.password); - }, function (err) { - /** - * Even if the checks fail, - * we have to clean up. - */ - return Promise.resolve(retInstance.close()).then(function () { - throw err; - }); - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); + _context.prev = 8; + validatePassword(params.password); + _context.next = 17; + break; + case 12: + _context.prev = 12; + _context.t0 = _context["catch"](8); + _context.next = 16; + return retInstance.close(); + case 16: + throw _context.t0; + case 17: + return _context.abrupt("return", retInstance); + case 18: + if (params.password) { + _context.next = 20; + break; + } + throw (0, _rxError.newRxError)('EN3', { + database: params.databaseName, + collection: params.collectionName, + schema: params.schema + }); + case 20: + password = params.password; + schemaWithoutEncrypted = (0, _utils.clone)(params.schema); + delete schemaWithoutEncrypted.encrypted; + if (schemaWithoutEncrypted.attachments) { + schemaWithoutEncrypted.attachments.encrypted = false; + } + _context.next = 26; + return args.storage.createStorageInstance(Object.assign({}, params, { + schema: schemaWithoutEncrypted + })); + case 26: + instance = _context.sent; + return _context.abrupt("return", (0, _pluginHelpers.wrapRxStorageInstance)(instance, modifyToStorage, modifyFromStorage, modifyAttachmentFromStorage)); + case 28: + case "end": + return _context.stop(); } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); + }, _callee, null, [[8, 12]]); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); } function cloneWithoutAttachments(data) { var attachments = data._attachments; - data = (0, _util.flatClone)(data); + data = (0, _utils.flatClone)(data); delete data._attachments; - data = (0, _util.clone)(data); + data = (0, _utils.clone)(data); data._attachments = attachments; return data; } diff --git a/dist/lib/plugins/encryption/index.js.map b/dist/lib/plugins/encryption/index.js.map index 861a1e21852..1e02d73cb2d 100644 --- a/dist/lib/plugins/encryption/index.js.map +++ b/dist/lib/plugins/encryption/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["body","recover","result","e","then","MINIMUM_PASSWORD_LENGTH","encryptString","value","password","encrypted","AES","encrypt","toString","decryptString","cipherText","newRxError","args","decrypted","decrypt","ret","cryptoEnc","wrappedKeyEncryptionStorage","Object","assign","storage","createStorageInstance","params","database","databaseName","collection","collectionName","schema","schemaWithoutEncrypted","clone","attachments","modifyToStorage","docData","cloneWithoutAttachments","ensureNotFalsy","forEach","path","objectPath","get","stringValue","JSON","stringify","set","newAttachments","entries","_attachments","id","attachment","useAttachment","flatClone","data","dataString","b64EncodeUnicode","modifyFromStorage","decryptedParsed","parse","modifyAttachmentFromStorage","attachmentData","b64DecodeUnicode","instance","wrapRxStorageInstance","hasEncryption","retInstance","title","INTERNAL_STORE_SCHEMA_TITLE","validatePassword","err","close","newRxTypeError","length","minPassLength"],"sources":["../../../../src/plugins/encryption/index.ts"],"sourcesContent":["/**\n * this plugin adds the encryption-capabilities to rxdb\n * It's using crypto-js/aes for password-encryption\n * @link https://github.com/brix/crypto-js\n */\nimport AES from 'crypto-js/aes';\nimport * as cryptoEnc from 'crypto-js/enc-utf8';\nimport objectPath from 'object-path';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport {\n INTERNAL_STORE_SCHEMA_TITLE\n} from '../../rx-database-internal-store';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { hasEncryption } from '../../rx-storage-helper';\nimport type {\n InternalStoreDocType,\n RxAttachmentWriteData,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n b64DecodeUnicode,\n b64EncodeUnicode,\n clone,\n ensureNotFalsy,\n flatClone\n} from '../../util';\n\nexport const MINIMUM_PASSWORD_LENGTH: 8 = 8;\n\n\nexport function encryptString(value: string, password: string): string {\n const encrypted = AES.encrypt(value, password);\n return encrypted.toString();\n}\n\nexport function decryptString(cipherText: string, password: any): string {\n /**\n * Trying to decrypt non-strings\n * will cause no errors and will be hard to debug.\n * So instead we do this check here.\n */\n if (typeof cipherText !== 'string') {\n throw newRxError('SNH', {\n args: {\n cipherText\n }\n });\n }\n\n const decrypted = AES.decrypt(cipherText, password);\n const ret = decrypted.toString(cryptoEnc);\n return ret;\n}\n\nexport type InternalStorePasswordDocType = InternalStoreDocType<{\n hash: string;\n}>;\n\nexport function wrappedKeyEncryptionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!hasEncryption(params.schema)) {\n const retInstance = await args.storage.createStorageInstance(params);\n if (\n params.schema.title === INTERNAL_STORE_SCHEMA_TITLE &&\n params.password\n ) {\n try {\n validatePassword(params.password);\n } catch (err) {\n /**\n * Even if the checks fail,\n * we have to clean up.\n */\n await retInstance.close();\n throw err;\n }\n }\n return retInstance;\n }\n\n if (!params.password) {\n throw newRxError('EN3', {\n database: params.databaseName,\n collection: params.collectionName,\n schema: params.schema\n });\n }\n const password = params.password;\n\n const schemaWithoutEncrypted: RxJsonSchema> = clone(params.schema);\n delete schemaWithoutEncrypted.encrypted;\n if (schemaWithoutEncrypted.attachments) {\n schemaWithoutEncrypted.attachments.encrypted = false;\n }\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: schemaWithoutEncrypted\n }\n )\n );\n\n function modifyToStorage(docData: RxDocumentWriteData) {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n\n const stringValue = JSON.stringify(value);\n const encrypted = encryptString(stringValue, password);\n objectPath.set(docData, path, encrypted);\n });\n\n // handle attachments\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const newAttachments: typeof docData._attachments = {};\n Object.entries(docData._attachments).forEach(([id, attachment]) => {\n const useAttachment: RxAttachmentWriteData = flatClone(attachment) as any;\n if (useAttachment.data) {\n const dataString = useAttachment.data;\n useAttachment.data = b64EncodeUnicode(encryptString(dataString, password));\n }\n newAttachments[id] = useAttachment;\n });\n docData._attachments = newAttachments;\n }\n return docData;\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n const decrypted = decryptString(value, password);\n const decryptedParsed = JSON.parse(decrypted);\n objectPath.set(docData, path, decryptedParsed);\n });\n return docData;\n }\n\n function modifyAttachmentFromStorage(attachmentData: string): string {\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const decrypted = decryptString(b64DecodeUnicode(attachmentData), password);\n return decrypted;\n } else {\n return attachmentData;\n }\n }\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage,\n modifyAttachmentFromStorage\n );\n }\n }\n );\n}\n\n\n\n\n\nfunction cloneWithoutAttachments(data: RxDocumentWriteData): RxDocumentData {\n const attachments = data._attachments;\n data = flatClone(data);\n delete (data as any)._attachments;\n data = clone(data);\n data._attachments = attachments;\n return data as any;\n}\n\nfunction validatePassword(password: any) {\n if (password && typeof password !== 'string') {\n throw newRxTypeError('EN1', {\n password\n });\n }\n if (password && password.length < MINIMUM_PASSWORD_LENGTH) {\n throw newRxError('EN2', {\n minPassLength: MINIMUM_PASSWORD_LENGTH,\n password\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAKA;AACA;AACA;AACA;AACA;AAGA;AACA;AAUA;AA2hBO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AAAC;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CG,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;AACJ"} \ No newline at end of file +{"version":3,"file":"index.js","names":["MINIMUM_PASSWORD_LENGTH","encryptString","value","password","encrypted","AES","encrypt","toString","decryptString","cipherText","newRxError","args","decrypted","decrypt","ret","cryptoEnc","wrappedKeyEncryptionStorage","Object","assign","storage","createStorageInstance","params","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","attachmentData","schema","attachments","b64DecodeUnicode","docData","cloneWithoutAttachments","ensureNotFalsy","forEach","path","objectPath","get","decryptedParsed","JSON","parse","set","stringValue","stringify","newAttachments","entries","_attachments","id","attachment","useAttachment","flatClone","data","dataString","b64EncodeUnicode","hasEncryption","retInstance","title","INTERNAL_STORE_SCHEMA_TITLE","validatePassword","close","database","databaseName","collection","collectionName","schemaWithoutEncrypted","clone","instance","wrapRxStorageInstance","newRxTypeError","length","minPassLength"],"sources":["../../../../src/plugins/encryption/index.ts"],"sourcesContent":["/**\n * this plugin adds the encryption-capabilities to rxdb\n * It's using crypto-js/aes for password-encryption\n * @link https://github.com/brix/crypto-js\n */\nimport AES from 'crypto-js/aes';\nimport * as cryptoEnc from 'crypto-js/enc-utf8';\nimport objectPath from 'object-path';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport {\n INTERNAL_STORE_SCHEMA_TITLE\n} from '../../rx-database-internal-store';\nimport { newRxError, newRxTypeError } from '../../rx-error';\nimport { hasEncryption } from '../../rx-storage-helper';\nimport type {\n InternalStoreDocType,\n RxAttachmentWriteData,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n b64DecodeUnicode,\n b64EncodeUnicode,\n clone,\n ensureNotFalsy,\n flatClone\n} from '../../plugins/utils';\n\nexport const MINIMUM_PASSWORD_LENGTH: 8 = 8;\n\n\nexport function encryptString(value: string, password: string): string {\n const encrypted = AES.encrypt(value, password);\n return encrypted.toString();\n}\n\nexport function decryptString(cipherText: string, password: any): string {\n /**\n * Trying to decrypt non-strings\n * will cause no errors and will be hard to debug.\n * So instead we do this check here.\n */\n if (typeof cipherText !== 'string') {\n throw newRxError('SNH', {\n args: {\n cipherText\n }\n });\n }\n\n const decrypted = AES.decrypt(cipherText, password);\n const ret = decrypted.toString(cryptoEnc);\n return ret;\n}\n\nexport type InternalStorePasswordDocType = InternalStoreDocType<{\n hash: string;\n}>;\n\nexport function wrappedKeyEncryptionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n return Object.assign(\n {},\n args.storage,\n {\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!hasEncryption(params.schema)) {\n const retInstance = await args.storage.createStorageInstance(params);\n if (\n params.schema.title === INTERNAL_STORE_SCHEMA_TITLE &&\n params.password\n ) {\n try {\n validatePassword(params.password);\n } catch (err) {\n /**\n * Even if the checks fail,\n * we have to clean up.\n */\n await retInstance.close();\n throw err;\n }\n }\n return retInstance;\n }\n\n if (!params.password) {\n throw newRxError('EN3', {\n database: params.databaseName,\n collection: params.collectionName,\n schema: params.schema\n });\n }\n const password = params.password;\n\n const schemaWithoutEncrypted: RxJsonSchema> = clone(params.schema);\n delete schemaWithoutEncrypted.encrypted;\n if (schemaWithoutEncrypted.attachments) {\n schemaWithoutEncrypted.attachments.encrypted = false;\n }\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: schemaWithoutEncrypted\n }\n )\n );\n\n function modifyToStorage(docData: RxDocumentWriteData) {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n\n const stringValue = JSON.stringify(value);\n const encrypted = encryptString(stringValue, password);\n objectPath.set(docData, path, encrypted);\n });\n\n // handle attachments\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const newAttachments: typeof docData._attachments = {};\n Object.entries(docData._attachments).forEach(([id, attachment]) => {\n const useAttachment: RxAttachmentWriteData = flatClone(attachment) as any;\n if (useAttachment.data) {\n const dataString = useAttachment.data;\n useAttachment.data = b64EncodeUnicode(encryptString(dataString, password));\n }\n newAttachments[id] = useAttachment;\n });\n docData._attachments = newAttachments;\n }\n return docData;\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n docData = cloneWithoutAttachments(docData);\n ensureNotFalsy(params.schema.encrypted)\n .forEach(path => {\n const value = objectPath.get(docData, path);\n if (typeof value === 'undefined') {\n return;\n }\n const decrypted = decryptString(value, password);\n const decryptedParsed = JSON.parse(decrypted);\n objectPath.set(docData, path, decryptedParsed);\n });\n return docData;\n }\n\n function modifyAttachmentFromStorage(attachmentData: string): string {\n if (\n params.schema.attachments &&\n params.schema.attachments.encrypted\n ) {\n const decrypted = decryptString(b64DecodeUnicode(attachmentData), password);\n return decrypted;\n } else {\n return attachmentData;\n }\n }\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage,\n modifyAttachmentFromStorage\n );\n }\n }\n );\n}\n\n\n\n\n\nfunction cloneWithoutAttachments(data: RxDocumentWriteData): RxDocumentData {\n const attachments = data._attachments;\n data = flatClone(data);\n delete (data as any)._attachments;\n data = clone(data);\n data._attachments = attachments;\n return data as any;\n}\n\nfunction validatePassword(password: any) {\n if (password && typeof password !== 'string') {\n throw newRxTypeError('EN1', {\n password\n });\n }\n if (password && password.length < MINIMUM_PASSWORD_LENGTH) {\n throw newRxError('EN2', {\n minPassLength: MINIMUM_PASSWORD_LENGTH,\n password\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AAKA;AACA;AACA;AACA;AACA;AAGA;AACA;AAUA;AAM6B;AAAA;AA7B7B;AACA;AACA;AACA;AACA;;AA2BO,IAAMA,uBAA0B,GAAG,CAAC;AAAC;AAGrC,SAASC,aAAa,CAACC,KAAa,EAAEC,QAAgB,EAAU;EACnE,IAAMC,SAAS,GAAGC,eAAG,CAACC,OAAO,CAACJ,KAAK,EAAE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cACvC,IAAI0D,sBAAsB,CAACnC,WAAW,EAAE;gBACpCmC,sBAAsB,CAACnC,WAAW,CAACvB,SAAS,GAAG,KAAK;cACxD;cAAC;cAAA,OAEsBO,IAAI,CAACQ,OAAO,CAACC,qBAAqB,CACrDH,MAAM,CAACC,MAAM,CACT,CAAC,CAAC,EACFG,MAAM,EACN;gBACIK,MAAM,EAAEoC;cACZ,CAAC,CACJ,CACJ;YAAA;cARKE,QAAQ;cAAA,iCAqEP,IAAAC,oCAAqB,EACxBD,QAAQ,EACR1C,eAAe,EACfC,iBAAiB,EACjBC,2BAA2B,CAC9B;YAAA;YAAA;cAAA;UAAA;QAAA;MAAA;MAAA;QAAA;MAAA;MAAA;IAAA;EAET,CAAC,CACJ;AACL;AAMA,SAASM,uBAAuB,CAAImB,IAA4B,EAAqB;EACjF,IAAMtB,WAAW,GAAGsB,IAAI,CAACL,YAAY;EACrCK,IAAI,GAAG,IAAAD,gBAAS,EAACC,IAAI,CAAC;EACtB,OAAQA,IAAI,CAASL,YAAY;EACjCK,IAAI,GAAG,IAAAc,YAAK,EAACd,IAAI,CAAC;EAClBA,IAAI,CAACL,YAAY,GAAGjB,WAAW;EAC/B,OAAOsB,IAAI;AACf;AAEA,SAASO,gBAAgB,CAACrD,QAAa,EAAE;EACrC,IAAIA,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;IAC1C,MAAM,IAAA+D,uBAAc,EAAC,KAAK,EAAE;MACxB/D,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;EACA,IAAIA,QAAQ,IAAIA,QAAQ,CAACgE,MAAM,GAAGnE,uBAAuB,EAAE;IACvD,MAAM,IAAAU,mBAAU,EAAC,KAAK,EAAE;MACpB0D,aAAa,EAAEpE,uBAAuB;MACtCG,QAAQ,EAARA;IACJ,CAAC,CAAC;EACN;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/flutter/index.js b/dist/lib/plugins/flutter/index.js index a3fb9e99500..bbc3e825e8b 100644 --- a/dist/lib/plugins/flutter/index.js +++ b/dist/lib/plugins/flutter/index.js @@ -1,38 +1,53 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.getLokijsAdapterFlutter = getLokijsAdapterFlutter; exports.setFlutterRxDatabaseConnector = setFlutterRxDatabaseConnector; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); function setFlutterRxDatabaseConnector(createDB) { - process.init = function (databaseName) { - try { - return Promise.resolve(createDB(databaseName)).then(function (db) { - db.eventBulks$.subscribe(function (eventBulk) { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - sendRxDBEvent(JSON.stringify(eventBulk)); - }); - process.db = db; - var collections = []; - Object.entries(db.collections).forEach(function (_ref) { - var collectionName = _ref[0], - collection = _ref[1]; - collections.push({ - name: collectionName, - primaryKey: collection.schema.primaryPath - }); - }); - return { - databaseName: databaseName, - collections: collections - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; + process.init = /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(databaseName) { + var db, collections; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return createDB(databaseName); + case 2: + db = _context.sent; + db.eventBulks$.subscribe(function (eventBulk) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + sendRxDBEvent(JSON.stringify(eventBulk)); + }); + process.db = db; + collections = []; + Object.entries(db.collections).forEach(function (_ref2) { + var collectionName = _ref2[0], + collection = _ref2[1]; + collections.push({ + name: collectionName, + primaryKey: collection.schema.primaryPath + }); + }); + return _context.abrupt("return", { + databaseName: databaseName, + collections: collections + }); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }(); } /** @@ -41,38 +56,59 @@ function setFlutterRxDatabaseConnector(createDB) { */ function getLokijsAdapterFlutter() { var ret = { - loadDatabase: function loadDatabase(databaseName, callback) { - try { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - return Promise.resolve(readKeyValue(databaseName)).then(function (serializedDb) { - var success = true; - if (success) { - callback(serializedDb); - } else { - callback(new Error('There was a problem loading the database')); + loadDatabase: function () { + var _loadDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(databaseName, callback) { + var serializedDb, success; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return readKeyValue(databaseName); + case 2: + serializedDb = _context2.sent; + success = true; + if (success) { + callback(serializedDb); + } else { + callback(new Error('There was a problem loading the database')); + } + case 5: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); + }, _callee2); + })); + function loadDatabase(_x2, _x3) { + return _loadDatabase.apply(this, arguments); } - }, - saveDatabase: function saveDatabase(databaseName, dbstring, callback) { - try { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - return Promise.resolve(persistKeyValue(databaseName, dbstring)).then(function () { - var success = true; // make your own determinations - if (success) { - callback(null); - } else { - callback(new Error('An error was encountered loading " + dbname + " database.')); + return loadDatabase; + }(), + saveDatabase: function () { + var _saveDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(databaseName, dbstring, callback) { + var success; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return persistKeyValue(databaseName, dbstring); + case 2: + success = true; // make your own determinations + if (success) { + callback(null); + } else { + callback(new Error('An error was encountered loading " + dbname + " database.')); + } + case 4: + case "end": + return _context3.stop(); } - }); - } catch (e) { - return Promise.reject(e); + }, _callee3); + })); + function saveDatabase(_x4, _x5, _x6) { + return _saveDatabase.apply(this, arguments); } - } + return saveDatabase; + }() }; return ret; } diff --git a/dist/lib/plugins/flutter/index.js.map b/dist/lib/plugins/flutter/index.js.map index c8aae28b33f..0328cd75fe9 100644 --- a/dist/lib/plugins/flutter/index.js.map +++ b/dist/lib/plugins/flutter/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["setFlutterRxDatabaseConnector","createDB","process","init","databaseName","db","eventBulks$","subscribe","eventBulk","sendRxDBEvent","JSON","stringify","collections","Object","entries","forEach","collectionName","collection","push","name","primaryKey","schema","primaryPath","getLokijsAdapterFlutter","ret","loadDatabase","callback","readKeyValue","serializedDb","success","Error","saveDatabase","dbstring","persistKeyValue"],"sources":["../../../../src/plugins/flutter/index.ts"],"sourcesContent":["import type {\n RxDatabase\n} from '../../types';\n\nexport type CreateRxDatabaseFunctionType = (databaseName: string) => Promise;\n\nexport function setFlutterRxDatabaseConnector(\n createDB: CreateRxDatabaseFunctionType\n) {\n (process as any).init = async (databaseName: string) => {\n const db = await createDB(databaseName);\n db.eventBulks$.subscribe(eventBulk => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sendRxDBEvent(JSON.stringify(eventBulk));\n });\n (process as any).db = db;\n const collections: { name: string; primaryKey: string; }[] = [];\n Object.entries(db.collections).forEach(([collectionName, collection]) => {\n collections.push({\n name: collectionName,\n primaryKey: collection.schema.primaryPath\n });\n });\n return {\n databaseName,\n collections\n };\n };\n}\n\n/**\n * Create a simple lokijs adapter so that we can persist string via flutter\n * @link https://github.com/techfort/LokiJS/blob/master/tutorials/Persistence%20Adapters.md#creating-your-own-basic-persistence-adapter\n */\nexport function getLokijsAdapterFlutter() {\n const ret = {\n async loadDatabase(databaseName: string, callback: (v: string | Error) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const serializedDb: string = await readKeyValue(databaseName);\n\n const success = true;\n if (success) {\n callback(serializedDb);\n } else {\n callback(new Error('There was a problem loading the database'));\n }\n },\n async saveDatabase(databaseName: string, dbstring: string, callback: (v: string | Error | null) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n await persistKeyValue(databaseName, dbstring);\n\n const success = true; // make your own determinations\n if (success) {\n callback(null);\n } else {\n callback(new Error('An error was encountered loading \" + dbname + \" database.'));\n }\n }\n };\n return ret;\n}\n"],"mappings":";;;;;;;AAMO,SAASA,6BAA6B,CACzCC,QAAsC,EACxC;EACGC,OAAO,CAASC,IAAI,aAAUC,YAAoB;IAAA,IAAK;MAAA,uBACnCH,QAAQ,CAACG,YAAY,CAAC,iBAAjCC,EAAE;QACRA,EAAE,CAACC,WAAW,CAACC,SAAS,CAAC,UAAAC,SAAS,EAAI;UAClC;UACA;UACAC,aAAa,CAACC,IAAI,CAACC,SAAS,CAACH,SAAS,CAAC,CAAC;QAC5C,CAAC,CAAC;QACDN,OAAO,CAASG,EAAE,GAAGA,EAAE;QACxB,IAAMO,WAAoD,GAAG,EAAE;QAC/DC,MAAM,CAACC,OAAO,CAACT,EAAE,CAACO,WAAW,CAAC,CAACG,OAAO,CAAC,gBAAkC;UAAA,IAAhCC,cAAc;YAAEC,UAAU;UAC/DL,WAAW,CAACM,IAAI,CAAC;YACbC,IAAI,EAAEH,cAAc;YACpBI,UAAU,EAAEH,UAAU,CAACI,MAAM,CAACC;UAClC,CAAC,CAAC;QACN,CAAC,CAAC;QACF,OAAO;UACHlB,YAAY,EAAZA,YAAY;UACZQ,WAAW,EAAXA;QACJ,CAAC;MAAC;IACN,CAAC;MAAA;IAAA;EAAA;AACL;;AAEA;AACA;AACA;AACA;AACO,SAASW,uBAAuB,GAAG;EACtC,IAAMC,GAAG,GAAG;IACFC,YAAY,wBAACrB,YAAoB,EAAEsB,QAAmC;MAAA,IAAE;QAC1E;QACA;QAAA,uBACmCC,YAAY,CAACvB,YAAY,CAAC,iBAAvDwB,YAAoB;UAE1B,IAAMC,OAAO,GAAG,IAAI;UAAC,IACjBA,OAAO;YACPH,QAAQ,CAACE,YAAY,CAAC;UAAC;YAEvBF,QAAQ,CAAC,IAAII,KAAK,CAAC,0CAA0C,CAAC,CAAC;UAAC;QAAA;MAExE,CAAC;QAAA;MAAA;IAAA;IACKC,YAAY,wBAAC3B,YAAoB,EAAE4B,QAAgB,EAAEN,QAA0C;MAAA,IAAE;QACnG;QACA;QAAA,uBACMO,eAAe,CAAC7B,YAAY,EAAE4B,QAAQ,CAAC;UAE7C,IAAMH,OAAO,GAAG,IAAI,CAAC,CAAE;UAAA,IACnBA,OAAO;YACPH,QAAQ,CAAC,IAAI,CAAC;UAAC;YAEfA,QAAQ,CAAC,IAAII,KAAK,CAAC,2DAA2D,CAAC,CAAC;UAAC;QAAA;MAEzF,CAAC;QAAA;MAAA;IAAA;EACL,CAAC;EACD,OAAON,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"index.js","names":["setFlutterRxDatabaseConnector","createDB","process","init","databaseName","db","eventBulks$","subscribe","eventBulk","sendRxDBEvent","JSON","stringify","collections","Object","entries","forEach","collectionName","collection","push","name","primaryKey","schema","primaryPath","getLokijsAdapterFlutter","ret","loadDatabase","callback","readKeyValue","serializedDb","success","Error","saveDatabase","dbstring","persistKeyValue"],"sources":["../../../../src/plugins/flutter/index.ts"],"sourcesContent":["import type {\n RxDatabase\n} from '../../types';\n\nexport type CreateRxDatabaseFunctionType = (databaseName: string) => Promise;\n\nexport function setFlutterRxDatabaseConnector(\n createDB: CreateRxDatabaseFunctionType\n) {\n (process as any).init = async (databaseName: string) => {\n const db = await createDB(databaseName);\n db.eventBulks$.subscribe(eventBulk => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n sendRxDBEvent(JSON.stringify(eventBulk));\n });\n (process as any).db = db;\n const collections: { name: string; primaryKey: string; }[] = [];\n Object.entries(db.collections).forEach(([collectionName, collection]) => {\n collections.push({\n name: collectionName,\n primaryKey: collection.schema.primaryPath\n });\n });\n return {\n databaseName,\n collections\n };\n };\n}\n\n/**\n * Create a simple lokijs adapter so that we can persist string via flutter\n * @link https://github.com/techfort/LokiJS/blob/master/tutorials/Persistence%20Adapters.md#creating-your-own-basic-persistence-adapter\n */\nexport function getLokijsAdapterFlutter() {\n const ret = {\n async loadDatabase(databaseName: string, callback: (v: string | Error) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const serializedDb: string = await readKeyValue(databaseName);\n\n const success = true;\n if (success) {\n callback(serializedDb);\n } else {\n callback(new Error('There was a problem loading the database'));\n }\n },\n async saveDatabase(databaseName: string, dbstring: string, callback: (v: string | Error | null) => {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n await persistKeyValue(databaseName, dbstring);\n\n const success = true; // make your own determinations\n if (success) {\n callback(null);\n } else {\n callback(new Error('An error was encountered loading \" + dbname + \" database.'));\n }\n }\n };\n return ret;\n}\n"],"mappings":";;;;;;;;;;AAMO,SAASA,6BAA6B,CACzCC,QAAsC,EACxC;EACGC,OAAO,CAASC,IAAI;IAAA,yFAAG,iBAAOC,YAAoB;MAAA;MAAA;QAAA;UAAA;YAAA;YAAA,OAC9BH,QAAQ,CAACG,YAAY,CAAC;UAAA;YAAjCC,EAAE;YACRA,EAAE,CAACC,WAAW,CAACC,SAAS,CAAC,UAAAC,SAAS,EAAI;cAClC;cACA;cACAC,aAAa,CAACC,IAAI,CAACC,SAAS,CAACH,SAAS,CAAC,CAAC;YAC5C,CAAC,CAAC;YACDN,OAAO,CAASG,EAAE,GAAGA,EAAE;YAClBO,WAAoD,GAAG,EAAE;YAC/DC,MAAM,CAACC,OAAO,CAACT,EAAE,CAACO,WAAW,CAAC,CAACG,OAAO,CAAC,iBAAkC;cAAA,IAAhCC,cAAc;gBAAEC,UAAU;cAC/DL,WAAW,CAACM,IAAI,CAAC;gBACbC,IAAI,EAAEH,cAAc;gBACpBI,UAAU,EAAEH,UAAU,CAACI,MAAM,CAACC;cAClC,CAAC,CAAC;YACN,CAAC,CAAC;YAAC,iCACI;cACHlB,YAAY,EAAZA,YAAY;cACZQ,WAAW,EAAXA;YACJ,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACJ;IAAA;MAAA;IAAA;EAAA;AACL;;AAEA;AACA;AACA;AACA;AACO,SAASW,uBAAuB,GAAG;EACtC,IAAMC,GAAG,GAAG;IACFC,YAAY;MAAA,oHAACrB,YAAoB,EAAEsB,QAAmC;QAAA;QAAA;UAAA;YAAA;cAAA;cAAA,OAGrCC,YAAY,CAACvB,YAAY,CAAC;YAAA;cAAvDwB,YAAoB;cAEpBC,OAAO,GAAG,IAAI;cACpB,IAAIA,OAAO,EAAE;gBACTH,QAAQ,CAACE,YAAY,CAAC;cAC1B,CAAC,MAAM;gBACHF,QAAQ,CAAC,IAAII,KAAK,CAAC,0CAA0C,CAAC,CAAC;cACnE;YAAC;YAAA;cAAA;UAAA;QAAA;MAAA;MAAA;QAAA;MAAA;MAAA;IAAA;IAECC,YAAY;MAAA,oHAAC3B,YAAoB,EAAE4B,QAAgB,EAAEN,QAA0C;QAAA;QAAA;UAAA;YAAA;cAAA;cAAA,OAG3FO,eAAe,CAAC7B,YAAY,EAAE4B,QAAQ,CAAC;YAAA;cAEvCH,OAAO,GAAG,IAAI,EAAG;cACvB,IAAIA,OAAO,EAAE;gBACTH,QAAQ,CAAC,IAAI,CAAC;cAClB,CAAC,MAAM;gBACHA,QAAQ,CAAC,IAAII,KAAK,CAAC,2DAA2D,CAAC,CAAC;cACpF;YAAC;YAAA;cAAA;UAAA;QAAA;MAAA;MAAA;QAAA;MAAA;MAAA;IAAA;EAET,CAAC;EACD,OAAON,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/foundationdb-helpers.js.map b/dist/lib/plugins/foundationdb/foundationdb-helpers.js.map deleted file mode 100644 index 36700e6843d..00000000000 --- a/dist/lib/plugins/foundationdb/foundationdb-helpers.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"foundationdb-helpers.js","names":["getFoundationDBIndexName","index","join","CLEANUP_INDEX"],"sources":["../../../../src/plugins/foundationdb/foundationdb-helpers.ts"],"sourcesContent":["export function getFoundationDBIndexName(index: string[]): string {\n return index.join('|');\n}\nexport const CLEANUP_INDEX: string[] = ['_deleted', '_meta.lwt'];\n"],"mappings":";;;;;;;AAAO,SAASA,wBAAwB,CAACC,KAAe,EAAU;EAC9D,OAAOA,KAAK,CAACC,IAAI,CAAC,GAAG,CAAC;AAC1B;AACO,IAAMC,aAAuB,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/foundationdb-query.js b/dist/lib/plugins/foundationdb/foundationdb-query.js deleted file mode 100644 index c0d2abaa361..00000000000 --- a/dist/lib/plugins/foundationdb/foundationdb-query.js +++ /dev/null @@ -1,249 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.queryFoundationDB = void 0; -var _customIndex = require("../../custom-index"); -var _util = require("../../util"); -var _dexie = require("../dexie"); -var _foundationdbHelpers = require("./foundationdb-helpers"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -var queryFoundationDB = function queryFoundationDB(instance, preparedQuery) { - try { - var queryPlan = preparedQuery.queryPlan; - var query = preparedQuery.query; - var skip = query.skip ? query.skip : 0; - var limit = query.limit ? query.limit : Infinity; - var skipPlusLimit = skip + limit; - var queryPlanFields = queryPlan.index; - var mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields; - var queryMatcher = false; - if (!queryPlan.selectorSatisfiedByIndex) { - queryMatcher = _dexie.RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); - } - return Promise.resolve(instance.internals.dbsPromise).then(function (dbs) { - var indexForName = queryPlanFields.slice(0); - indexForName.unshift('_deleted'); - var indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(indexForName); - var indexDB = (0, _util.ensureNotFalsy)(dbs.indexes[indexName]).db; - var lowerBound = queryPlan.startKeys; - lowerBound = [false].concat(lowerBound); - var lowerBoundString = (0, _customIndex.getStartIndexStringFromLowerBound)(instance.schema, indexForName, lowerBound, queryPlan.inclusiveStart); - var upperBound = queryPlan.endKeys; - upperBound = [false].concat(upperBound); - var upperBoundString = (0, _customIndex.getStartIndexStringFromUpperBound)(instance.schema, indexForName, upperBound, queryPlan.inclusiveEnd); - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var _interrupt = false; - var innerResult = []; - var indexTx = tx.at(indexDB.subspace); - var mainTx = tx.at(dbs.main.subspace); - var range = indexTx.getRangeBatch(lowerBoundString, upperBoundString, { - // TODO these options seem to be broken in the foundationdb node bindings - // limit: instance.settings.batchSize, - // streamingMode: StreamingMode.Exact - }); - var done = false; - var _temp = _for(function () { - return !_interrupt && !done; - }, void 0, function () { - return Promise.resolve(range.next()).then(function (next) { - if (next.done) { - done = true; - _interrupt = true; - return; - } - var docIds = next.value.map(function (row) { - return row[1]; - }); - return Promise.resolve(Promise.all(docIds.map(function (docId) { - return mainTx.get(docId); - }))).then(function (docsData) { - docsData.forEach(function (docData) { - if (!done) { - if (!queryMatcher || queryMatcher(docData)) { - innerResult.push(docData); - } - } - if (!mustManuallyResort && innerResult.length === skipPlusLimit) { - done = true; - range["return"](); - } - }); - }); - }); - }); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return innerResult; - }) : innerResult); - } catch (e) { - return Promise.reject(e); - } - })).then(function (result) { - if (mustManuallyResort) { - var sortComparator = _dexie.RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); - result = result.sort(sortComparator); - } - - // apply skip and limit boundaries. - result = result.slice(skip, skipPlusLimit); - return { - documents: result - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.queryFoundationDB = queryFoundationDB; -//# sourceMappingURL=foundationdb-query.js.map \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/foundationdb-query.js.map b/dist/lib/plugins/foundationdb/foundationdb-query.js.map deleted file mode 100644 index 6efc6464af1..00000000000 --- a/dist/lib/plugins/foundationdb/foundationdb-query.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"foundationdb-query.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","queryFoundationDB","instance","preparedQuery","queryPlan","query","skip","limit","Infinity","skipPlusLimit","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","queryMatcher","selectorSatisfiedByIndex","RxStorageDexieStatics","getQueryMatcher","schema","internals","dbsPromise","dbs","indexForName","slice","unshift","indexName","getFoundationDBIndexName","indexDB","ensureNotFalsy","indexes","db","lowerBound","startKeys","concat","lowerBoundString","getStartIndexStringFromLowerBound","inclusiveStart","upperBound","endKeys","upperBoundString","getStartIndexStringFromUpperBound","inclusiveEnd","root","doTransaction","tx","innerResult","indexTx","at","subspace","mainTx","main","range","getRangeBatch","done","next","docIds","map","row","Promise","all","docId","get","docsData","forEach","docData","push","length","sortComparator","getSortComparator","sort","documents"],"sources":["../../../../src/plugins/foundationdb/foundationdb-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport type {\n RxDocumentData,\n RxStorageQueryResult\n} from '../../types';\nimport { ensureNotFalsy } from '../../util';\nimport { RxStorageDexieStatics } from '../dexie';\nimport { getFoundationDBIndexName } from './foundationdb-helpers';\nimport type {\n FoundationDBPreparedQuery\n} from './foundationdb-types';\nimport { RxStorageInstanceFoundationDB } from './rx-storage-instance-foundationdb';\n\nexport async function queryFoundationDB(\n instance: RxStorageInstanceFoundationDB,\n preparedQuery: FoundationDBPreparedQuery\n): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const dbs = await instance.internals.dbsPromise;\n\n\n const indexForName = queryPlanFields.slice(0);\n indexForName.unshift('_deleted');\n const indexName = getFoundationDBIndexName(indexForName);\n const indexDB = ensureNotFalsy(dbs.indexes[indexName]).db;\n\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n instance.schema,\n indexForName,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n instance.schema,\n indexForName,\n upperBound,\n queryPlan.inclusiveEnd\n );\n let result = await dbs.root.doTransaction(async (tx: any) => {\n const innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexDB.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n\n const range = indexTx.getRangeBatch(\n lowerBoundString,\n upperBoundString,\n {\n // TODO these options seem to be broken in the foundationdb node bindings\n // limit: instance.settings.batchSize,\n // streamingMode: StreamingMode.Exact\n }\n );\n let done = false;\n while (!done) {\n const next = await range.next();\n if (next.done) {\n done = true;\n break;\n }\n const docIds = next.value.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n docsData.forEach((docData) => {\n if (!done) {\n if (!queryMatcher || queryMatcher(docData)) {\n innerResult.push(docData);\n }\n }\n if (\n !mustManuallyResort &&\n innerResult.length === skipPlusLimit\n ) {\n done = true;\n range.return();\n }\n });\n }\n return innerResult;\n });\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n result = result.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n result = result.slice(skip, skipPlusLimit);\n\n return {\n documents: result\n };\n}\n"],"mappings":";;;;;;AACA;AAQA;AACA;AACA;AA4BO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACK,IAAI,EAAE;MACxBL,KAAK,CAACK,IAAI,CAAC,QAAQD,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAE,CAAC,CAAC,CAAC;MACxE;IACD;IAC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EAAEpF;QACf,CAAC;MAAC;IAAA;EACN,CAAC;IAAA;EAAA;AAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/foundationdb-types.js.map b/dist/lib/plugins/foundationdb/foundationdb-types.js.map deleted file mode 100644 index 229cc5bf2ef..00000000000 --- a/dist/lib/plugins/foundationdb/foundationdb-types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"foundationdb-types.js","names":[],"sources":["../../../../src/plugins/foundationdb/foundationdb-types.ts"],"sourcesContent":["/* eslint-disable no-unused-vars */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type {\n DexiePreparedQuery,\n EventBulk,\n RxAttachmentWriteData,\n RxDocumentData,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types';\nexport type RxStorageFoundationDBSettings = {\n /**\n * Version of the API of the foundationDB server.\n */\n apiVersion: number;\n /**\n * Path to the foundationDB cluster file\n * like '/path/to/fdb.cluster'\n * (optional)\n */\n clusterFile?: string;\n batchSize?: number;\n};\nexport type RxStorageFoundationDBInstanceCreationOptions = {\n // can be overwritte per instance\n batchSize?: number;\n};\n\n/**\n * TODO atm we cannot import types from 'foundationdb'\n * because 'foundationdb' is an optional peer dependency\n * this is NOT also in the devDependencies.\n * This is because it requires to install the foundationdb client cli\n * which would mean everyone that wants to develop RxDB must have this installed manually.\n */\n// import {\n// open as foundationDBOpen,\n// Database,\n// Transaction\n// } from 'foundationdb';\n\nexport type FoundationDBIndexMeta = {\n indexName: string;\n index: string[];\n getIndexableString: (doc: RxDocumentData) => string;\n db: FoundationDBDatabase;\n};\n\nexport type FoundationDBConnection = any; // ReturnType;\nexport type FoundationDBDatabase = any; // Database;\nexport type FoundationDBTransaction = any; // Transaction, any>;\nexport type FoundationDBStorageInternals = {\n connection: FoundationDBConnection;\n dbsPromise: Promise<{\n root: FoundationDBDatabase;\n main: FoundationDBDatabase;\n attachments: FoundationDBDatabase;\n events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>>;\n indexes: {\n [indexName: string]: FoundationDBIndexMeta;\n };\n }>;\n};\nexport type RxStorageFoundationDB = RxStorage, RxStorageFoundationDBInstanceCreationOptions> & {\n};\n\n\nexport type FoundationDBPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/index.js.map b/dist/lib/plugins/foundationdb/index.js.map deleted file mode 100644 index 61d7515c008..00000000000 --- a/dist/lib/plugins/foundationdb/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["versionSet","getRxStorageFoundationDB","settings","apiVersion","Error","require","setAPIVersion","storage","name","statics","RxStorageDexieStatics","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","useSettings","Object","assign","options","batchSize","createFoundationDBStorageInstance"],"sources":["../../../../src/plugins/foundationdb/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type {\n RxStorageInstanceCreationParams\n} from '../../types';\nimport { RxStorageDexieStatics } from '../dexie/dexie-statics';\nimport type {\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n\nimport {\n createFoundationDBStorageInstance,\n RxStorageInstanceFoundationDB\n} from './rx-storage-instance-foundationdb';\n\n\nlet versionSet: undefined | number;\n\nexport function getRxStorageFoundationDB(\n settings: RxStorageFoundationDBSettings\n): RxStorageFoundationDB {\n if (versionSet && versionSet !== settings.apiVersion) {\n throw new Error('foundationdb already initialized with api version ' + versionSet);\n } else if (!versionSet) {\n versionSet = settings.apiVersion;\n const { setAPIVersion } = require('foundationdb');\n setAPIVersion(settings.apiVersion);\n }\n\n\n const storage: RxStorageFoundationDB = {\n name: 'foundationdb',\n statics: RxStorageDexieStatics,\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n if (!useSettings.batchSize) {\n useSettings.batchSize = 50;\n }\n return createFoundationDBStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './foundationdb-types';\nexport * from './foundationdb-helpers';\n"],"mappings":";;;;;;;;;AAAA;AAIA;AAOA;AA2CA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAtCA,IAAIA,UAA8B;AAE3B,SAASC,wBAAwB,CACpCC,QAAuC,EAClB;EACrB,IAAIF,UAAU,IAAIA,UAAU,KAAKE,QAAQ,CAACC,UAAU,EAAE;IAClD,MAAM,IAAIC,KAAK,CAAC,oDAAoD,GAAGJ,UAAU,CAAC;EACtF,CAAC,MAAM,IAAI,CAACA,UAAU,EAAE;IACpBA,UAAU,GAAGE,QAAQ,CAACC,UAAU;IAChC,eAA0BE,OAAO,CAAC,cAAc,CAAC;MAAzCC,aAAa,YAAbA,aAAa;IACrBA,aAAa,CAACJ,QAAQ,CAACC,UAAU,CAAC;EACtC;EAGA,IAAMI,OAA8B,GAAG;IACnCC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAEC,mCAAqB;IAC9BC,qBAAqB,iCACjBC,MAAgG,EAC/C;MACjD,IAAAC,wDAAuC,EAACD,MAAM,CAAC;MAC/C,IAAME,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFd,QAAQ,EACRU,MAAM,CAACK,OAAO,CACjB;MACD,IAAI,CAACH,WAAW,CAACI,SAAS,EAAE;QACxBJ,WAAW,CAACI,SAAS,GAAG,EAAE;MAC9B;MACA,OAAO,IAAAC,gEAAiC,EAAC,IAAI,EAAEP,MAAM,EAAEE,WAAW,CAAC;IACvE;EACJ,CAAC;EAED,OAAOP,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/rx-storage-instance-foundationdb.js b/dist/lib/plugins/foundationdb/rx-storage-instance-foundationdb.js deleted file mode 100644 index 14dda89a108..00000000000 --- a/dist/lib/plugins/foundationdb/rx-storage-instance-foundationdb.js +++ /dev/null @@ -1,426 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxStorageInstanceFoundationDB = void 0; -exports.createFoundationDBStorageInstance = createFoundationDBStorageInstance; -var _rxjs = require("rxjs"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _rxStorageHelper = require("../../rx-storage-helper"); -var _foundationdbHelpers = require("./foundationdb-helpers"); -var _customIndex = require("../../custom-index"); -var _util = require("../../util"); -var _foundationdbQuery = require("./foundationdb-query"); -var _queryPlanner = require("../../query-planner"); -var _memory = require("../memory"); -// import { -// open as foundationDBOpen, -// directory as foundationDBDirectory, -// encoders as foundationDBEncoders, -// keySelector as foundationDBKeySelector, -// StreamingMode as foundationDBStreamingMode -// } from 'foundationdb'; -var RxStorageInstanceFoundationDB = /*#__PURE__*/function () { - function RxStorageInstanceFoundationDB(storage, databaseName, collectionName, schema, internals, options, settings) { - this.closed = false; - this.changes$ = new _rxjs.Subject(); - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - this.settings = settings; - this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); - } - var _proto = RxStorageInstanceFoundationDB.prototype; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this = this; - return Promise.resolve(_this.internals.dbsPromise).then(function (dbs) { - var categorized = null; - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var ret = { - success: {}, - error: {} - }; - var ids = documentWrites.map(function (row) { - return row.document[_this.primaryPath]; - }); - var mainTx = tx.at(dbs.main.subspace); - var attachmentTx = tx.at(dbs.attachments.subspace); - var docsInDB = new Map(); - /** - * TODO this might be faster if fdb - * any time adds a bulk-fetch-by-key method. - */ - return Promise.resolve(Promise.all(ids.map(function (id) { - try { - return Promise.resolve(mainTx.get(id)).then(function (doc) { - docsInDB.set(id, doc); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - categorized = (0, _rxStorageHelper.categorizeBulkWriteRows)(_this, _this.primaryPath, docsInDB, documentWrites, context); - ret.error = categorized.errors; - - // INSERTS - categorized.bulkInsertDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this.primaryPath]; - ret.success[docId] = writeRow.document; - - // insert document data - mainTx.set(docId, writeRow.document); - - // insert secondary indexes - Object.values(dbs.indexes).forEach(function (indexMeta) { - var indexString = indexMeta.getIndexableString(writeRow.document); - var indexTx = tx.at(indexMeta.db.subspace); - indexTx.set(indexString, docId); - }); - }); - // UPDATES - categorized.bulkUpdateDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this.primaryPath]; - - // overwrite document data - mainTx.set(docId, writeRow.document); - - // update secondary indexes - Object.values(dbs.indexes).forEach(function (indexMeta) { - var oldIndexString = indexMeta.getIndexableString((0, _util.ensureNotFalsy)(writeRow.previous)); - var newIndexString = indexMeta.getIndexableString(writeRow.document); - if (oldIndexString !== newIndexString) { - var indexTx = tx.at(indexMeta.db.subspace); - indexTx["delete"](oldIndexString); - indexTx.set(newIndexString, docId); - } - }); - ret.success[docId] = writeRow.document; - }); - - // attachments - categorized.attachmentsAdd.forEach(function (attachment) { - attachmentTx.set((0, _memory.attachmentMapKey)(attachment.documentId, attachment.attachmentId), attachment.attachmentData); - }); - categorized.attachmentsUpdate.forEach(function (attachment) { - attachmentTx.set((0, _memory.attachmentMapKey)(attachment.documentId, attachment.attachmentId), attachment.attachmentData); - }); - categorized.attachmentsRemove.forEach(function (attachment) { - attachmentTx["delete"]((0, _memory.attachmentMapKey)(attachment.documentId, attachment.attachmentId)); - }); - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function (result) { - /** - * The events must be emitted AFTER the transaction - * has finished. - * Otherwise an observable changestream might cause a read - * to a document that does not already exist outside of the transaction. - */ - if ((0, _util.ensureNotFalsy)(categorized).eventBulk.events.length > 0) { - var lastState = (0, _rxStorageHelper.getNewestOfDocumentStates)(_this.primaryPath, Object.values(result.success)); - (0, _util.ensureNotFalsy)(categorized).eventBulk.checkpoint = { - id: lastState[_this.primaryPath], - lwt: lastState._meta.lwt - }; - _this.changes$.next((0, _util.ensureNotFalsy)(categorized).eventBulk); - } - return result; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, withDeleted) { - try { - var _this2 = this; - return Promise.resolve(_this2.internals.dbsPromise).then(function (dbs) { - return dbs.main.doTransaction(function (tx) { - try { - var ret = {}; - return Promise.resolve(Promise.all(ids.map(function (docId) { - try { - return Promise.resolve(tx.get(docId)).then(function (docInDb) { - if (docInDb && (!docInDb._deleted || withDeleted)) { - ret[docId] = docInDb; - } - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - return (0, _foundationdbQuery.queryFoundationDB)(this, preparedQuery); - }; - _proto.count = function count(preparedQuery) { - try { - var _this3 = this; - /** - * At this point in time (end 2022), FoundationDB does not support - * range counts. So we have to run a normal query and use the result set length. - * @link https://github.com/apple/foundationdb/issues/5981 - */ - return Promise.resolve(_this3.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(documentId, attachmentId) { - try { - var _this4 = this; - return Promise.resolve(_this4.internals.dbsPromise).then(function (dbs) { - return Promise.resolve(dbs.attachments.get((0, _memory.attachmentMapKey)(documentId, attachmentId))).then(function (attachment) { - return attachment.data; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _this5 = this; - var _require = require('foundationdb'), - keySelector = _require.keySelector, - StreamingMode = _require.StreamingMode; - return Promise.resolve(_this5.internals.dbsPromise).then(function (dbs) { - var index = ['_meta.lwt', _this5.primaryPath]; - var indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(index); - var indexMeta = dbs.indexes[indexName]; - var lowerBoundString = ''; - if (checkpoint) { - var _checkpointPartialDoc; - var checkpointPartialDoc = (_checkpointPartialDoc = {}, _checkpointPartialDoc[_this5.primaryPath] = checkpoint.id, _checkpointPartialDoc._meta = { - lwt: checkpoint.lwt - }, _checkpointPartialDoc); - lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc); - } - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var innerResult = []; - var indexTx = tx.at(indexMeta.db.subspace); - var mainTx = tx.at(dbs.main.subspace); - return Promise.resolve(indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), _queryPlanner.INDEX_MAX, { - limit: limit, - streamingMode: StreamingMode.Exact - })).then(function (range) { - var docIds = range.map(function (row) { - return row[1]; - }); - return Promise.resolve(Promise.all(docIds.map(function (docId) { - return mainTx.get(docId); - }))).then(function (docsData) { - innerResult = innerResult.concat(docsData); - return innerResult; - }); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function (result) { - var lastDoc = (0, _util.lastOfArray)(result); - return { - documents: result, - checkpoint: lastDoc ? { - id: lastDoc[_this5.primaryPath], - lwt: lastDoc._meta.lwt - } : checkpoint ? checkpoint : { - id: '', - lwt: 0 - } - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.changeStream = function changeStream() { - return this.changes$.asObservable(); - }; - _proto.remove = function remove() { - try { - var _this6 = this; - return Promise.resolve(_this6.internals.dbsPromise).then(function (dbs) { - return Promise.resolve(dbs.root.doTransaction(function (tx) { - tx.clearRange('', _queryPlanner.INDEX_MAX); - return _util.PROMISE_RESOLVE_VOID; - })).then(function () { - return _this6.close(); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.cleanup = function cleanup(minimumDeletedTime) { - try { - var _this7 = this; - var _require2 = require('foundationdb'), - keySelector = _require2.keySelector, - StreamingMode = _require2.StreamingMode; - var maxDeletionTime = (0, _util.now)() - minimumDeletedTime; - return Promise.resolve(_this7.internals.dbsPromise).then(function (dbs) { - var index = _foundationdbHelpers.CLEANUP_INDEX; - var indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(index); - var indexMeta = dbs.indexes[indexName]; - var lowerBoundString = (0, _customIndex.getStartIndexStringFromLowerBound)(_this7.schema, index, [true, - /** - * Do not use 0 here, - * because 1 is the minimum value for _meta.lwt - */ - 1], false); - var upperBoundString = (0, _customIndex.getStartIndexStringFromUpperBound)(_this7.schema, index, [true, maxDeletionTime], true); - var noMoreUndeleted = true; - return Promise.resolve(dbs.root.doTransaction(function (tx) { - try { - var batchSize = (0, _util.ensureNotFalsy)(_this7.settings.batchSize); - var indexTx = tx.at(indexMeta.db.subspace); - var mainTx = tx.at(dbs.main.subspace); - return Promise.resolve(indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), upperBoundString, { - limit: batchSize + 1, - // get one more extra to detect what to return from cleanup() - streamingMode: StreamingMode.Exact - })).then(function (range) { - if (range.length > batchSize) { - noMoreUndeleted = false; - range.pop(); - } - var docIds = range.map(function (row) { - return row[1]; - }); - return Promise.resolve(Promise.all(docIds.map(function (docId) { - return mainTx.get(docId); - }))).then(function (docsData) { - Object.values(dbs.indexes).forEach(function (indexMetaInner) { - var subIndexDB = tx.at(indexMetaInner.db.subspace); - docsData.forEach(function (docData) { - var indexString = indexMetaInner.getIndexableString(docData); - subIndexDB["delete"](indexString); - }); - }); - docIds.forEach(function (id) { - return mainTx["delete"](id); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return noMoreUndeleted; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new _rxjs.Subject().asObservable(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return _util.PROMISE_RESOLVE_VOID; - }; - _proto.close = function close() { - try { - var _this8 = this; - if (_this8.closed) { - return Promise.reject(new Error('already closed')); - } - _this8.closed = true; - _this8.changes$.complete(); - return Promise.resolve(_this8.internals.dbsPromise).then(function (dbs) { - dbs.root.close(); - - // TODO shouldn't we close the index databases? - // Object.values(dbs.indexes).forEach(db => db.close()); - }); - } catch (e) { - return Promise.reject(e); - } - }; - return RxStorageInstanceFoundationDB; -}(); -exports.RxStorageInstanceFoundationDB = RxStorageInstanceFoundationDB; -function createFoundationDBStorageInstance(storage, params, settings) { - var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(params.schema.primaryKey); - var _require3 = require('foundationdb'), - open = _require3.open, - directory = _require3.directory, - encoders = _require3.encoders; - var connection = open(settings.clusterFile); - var dbsPromise = function () { - try { - return Promise.resolve(directory.createOrOpen(connection, 'rxdb')).then(function (dir) { - var root = connection.at(dir).at(params.databaseName + '.').at(params.collectionName + '.').at(params.schema.version + '.'); - var main = root.at('main.').withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples - .withValueEncoding(encoders.json); // and values using JSON - - var events = root.at('events.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); - var attachments = root.at('attachments.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); - var indexDBs = {}; - var useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : []; - useIndexes.push([primaryPath]); - var useIndexesFinal = useIndexes.map(function (index) { - var indexAr = Array.isArray(index) ? index.slice(0) : [index]; - indexAr.unshift('_deleted'); - return indexAr; - }); - // used for `getChangedDocumentsSince()` - useIndexesFinal.push(['_meta.lwt', primaryPath]); - useIndexesFinal.push(_foundationdbHelpers.CLEANUP_INDEX); - useIndexesFinal.forEach(function (indexAr) { - var indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(indexAr); - var indexDB = root.at(indexName + '.').withKeyEncoding(encoders.string).withValueEncoding(encoders.string); - indexDBs[indexName] = { - indexName: indexName, - db: indexDB, - getIndexableString: (0, _customIndex.getIndexableStringMonad)(params.schema, indexAr), - index: indexAr - }; - }); - return { - root: root, - main: main, - events: events, - attachments: attachments, - indexes: indexDBs - }; - }); - } catch (e) { - return Promise.reject(e); - } - }(); - var internals = { - connection: connection, - dbsPromise: dbsPromise - }; - var instance = new RxStorageInstanceFoundationDB(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); - return Promise.resolve(instance); -} -//# sourceMappingURL=rx-storage-instance-foundationdb.js.map \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/rx-storage-instance-foundationdb.js.map b/dist/lib/plugins/foundationdb/rx-storage-instance-foundationdb.js.map deleted file mode 100644 index eaac5da437f..00000000000 --- a/dist/lib/plugins/foundationdb/rx-storage-instance-foundationdb.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-foundationdb.js","names":["RxStorageInstanceFoundationDB","storage","databaseName","collectionName","schema","internals","options","settings","closed","changes$","Subject","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","bulkWrite","documentWrites","context","dbsPromise","dbs","categorized","root","doTransaction","tx","ret","success","error","ids","map","row","document","mainTx","at","main","subspace","attachmentTx","attachments","docsInDB","Map","Promise","all","id","get","doc","set","categorizeBulkWriteRows","errors","bulkInsertDocs","forEach","writeRow","docId","Object","values","indexes","indexMeta","indexString","getIndexableString","indexTx","db","bulkUpdateDocs","oldIndexString","ensureNotFalsy","previous","newIndexString","attachmentsAdd","attachment","attachmentMapKey","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","result","eventBulk","events","length","lastState","getNewestOfDocumentStates","checkpoint","lwt","_meta","next","findDocumentsById","withDeleted","docInDb","_deleted","query","preparedQuery","queryFoundationDB","count","documents","mode","getAttachmentData","data","getChangedDocumentsSince","limit","require","keySelector","StreamingMode","index","indexName","getFoundationDBIndexName","lowerBoundString","checkpointPartialDoc","innerResult","getRangeAll","firstGreaterThan","INDEX_MAX","streamingMode","Exact","range","docIds","docsData","concat","lastDoc","lastOfArray","changeStream","asObservable","remove","clearRange","PROMISE_RESOLVE_VOID","close","cleanup","minimumDeletedTime","maxDeletionTime","now","CLEANUP_INDEX","getStartIndexStringFromLowerBound","upperBoundString","getStartIndexStringFromUpperBound","noMoreUndeleted","batchSize","pop","indexMetaInner","subIndexDB","docData","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","reject","Error","complete","createFoundationDBStorageInstance","params","open","directory","encoders","connection","clusterFile","createOrOpen","dir","version","withKeyEncoding","string","withValueEncoding","json","indexDBs","useIndexes","slice","push","useIndexesFinal","indexAr","Array","isArray","unshift","indexDB","getIndexableStringMonad","instance","resolve"],"sources":["../../../../src/plugins/foundationdb/rx-storage-instance-foundationdb.ts"],"sourcesContent":["import { Observable, Subject } from 'rxjs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type {\n BulkWriteRow,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport type {\n FoundationDBDatabase,\n FoundationDBIndexMeta,\n FoundationDBPreparedQuery,\n FoundationDBStorageInternals,\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n// import {\n// open as foundationDBOpen,\n// directory as foundationDBDirectory,\n// encoders as foundationDBEncoders,\n// keySelector as foundationDBKeySelector,\n// StreamingMode as foundationDBStreamingMode\n// } from 'foundationdb';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport {\n\n CLEANUP_INDEX,\n getFoundationDBIndexName\n} from './foundationdb-helpers';\nimport {\n getIndexableStringMonad,\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport {\n ensureNotFalsy, lastOfArray, now\n , PROMISE_RESOLVE_VOID\n} from '../../util';\nimport { queryFoundationDB } from './foundationdb-query';\nimport { INDEX_MAX } from '../../query-planner';\nimport { attachmentMapKey } from '../memory';\n\nexport class RxStorageInstanceFoundationDB implements RxStorageInstance<\n RxDocType,\n FoundationDBStorageInternals,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n\n public closed = false;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n\n constructor(\n public readonly storage: RxStorageFoundationDB,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: FoundationDBStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageFoundationDBSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n const dbs = await this.internals.dbsPromise;\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n const result = await dbs.root.doTransaction(async (tx: any) => {\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const ids = documentWrites.map(row => (row.document as any)[this.primaryPath]);\n const mainTx = tx.at(dbs.main.subspace);\n const attachmentTx = tx.at(dbs.attachments.subspace);\n const docsInDB = new Map>();\n /**\n * TODO this might be faster if fdb\n * any time adds a bulk-fetch-by-key method.\n */\n await Promise.all(\n ids.map(async (id) => {\n const doc = await mainTx.get(id);\n docsInDB.set(id, doc);\n })\n );\n\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDB,\n documentWrites,\n context\n );\n\n ret.error = categorized.errors;\n\n // INSERTS\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n ret.success[docId] = writeRow.document as any;\n\n // insert document data\n mainTx.set(docId, writeRow.document);\n\n // insert secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const indexString = indexMeta.getIndexableString(writeRow.document as any);\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.set(indexString, docId);\n });\n });\n // UPDATES\n categorized.bulkUpdateDocs.forEach((writeRow: BulkWriteRow) => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n\n // overwrite document data\n mainTx.set(docId, writeRow.document);\n\n // update secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const oldIndexString = indexMeta.getIndexableString(ensureNotFalsy(writeRow.previous));\n const newIndexString = indexMeta.getIndexableString(writeRow.document as any);\n if (oldIndexString !== newIndexString) {\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.delete(oldIndexString);\n indexTx.set(newIndexString, docId);\n }\n });\n ret.success[docId] = writeRow.document as any;\n });\n\n // attachments\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentTx.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n\n return ret;\n });\n /**\n * The events must be emitted AFTER the transaction\n * has finished.\n * Otherwise an observable changestream might cause a read\n * to a document that does not already exist outside of the transaction.\n */\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(result.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n return result;\n }\n\n async findDocumentsById(ids: string[], withDeleted: boolean): Promise> {\n const dbs = await this.internals.dbsPromise;\n return dbs.main.doTransaction(async (tx: any) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n ids.map(async (docId) => {\n const docInDb = await tx.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n })\n );\n return ret;\n });\n }\n query(preparedQuery: FoundationDBPreparedQuery): Promise> {\n return queryFoundationDB(this, preparedQuery);\n }\n async count(\n preparedQuery: FoundationDBPreparedQuery\n ): Promise {\n /**\n * At this point in time (end 2022), FoundationDB does not support\n * range counts. So we have to run a normal query and use the result set length.\n * @link https://github.com/apple/foundationdb/issues/5981\n */\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n async getAttachmentData(documentId: string, attachmentId: string): Promise {\n const dbs = await this.internals.dbsPromise;\n const attachment = await dbs.attachments.get(attachmentMapKey(documentId, attachmentId));\n return attachment.data;\n }\n async getChangedDocumentsSince(limit: number, checkpoint?: RxStorageDefaultCheckpoint): Promise<{ documents: RxDocumentData[]; checkpoint: RxStorageDefaultCheckpoint; }> {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const dbs = await this.internals.dbsPromise;\n const index = [\n '_meta.lwt',\n this.primaryPath as any\n ];\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n let lowerBoundString = '';\n if (checkpoint) {\n const checkpointPartialDoc: any = {\n [this.primaryPath]: checkpoint.id,\n _meta: {\n lwt: checkpoint.lwt\n }\n };\n lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc);\n }\n const result: RxDocumentData[] = await dbs.root.doTransaction(async (tx: any) => {\n let innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n INDEX_MAX,\n {\n limit,\n streamingMode: StreamingMode.Exact\n }\n );\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(\n docIds.map((docId: string) => mainTx.get(docId))\n );\n innerResult = innerResult.concat(docsData);\n return innerResult;\n });\n const lastDoc = lastOfArray(result);\n return {\n documents: result,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n changeStream(): Observable, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async remove(): Promise {\n const dbs = await this.internals.dbsPromise;\n await dbs.root.doTransaction((tx: any) => {\n tx.clearRange('', INDEX_MAX);\n return PROMISE_RESOLVE_VOID;\n });\n return this.close();\n }\n async cleanup(minimumDeletedTime: number): Promise {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const maxDeletionTime = now() - minimumDeletedTime;\n const dbs = await this.internals.dbsPromise;\n const index = CLEANUP_INDEX;\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n /**\n * Do not use 0 here,\n * because 1 is the minimum value for _meta.lwt\n */\n 1\n ],\n false\n );\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n [\n true,\n maxDeletionTime\n ],\n true\n );\n let noMoreUndeleted: boolean = true;\n await dbs.root.doTransaction(async (tx: any) => {\n const batchSize = ensureNotFalsy(this.settings.batchSize);\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n upperBoundString,\n {\n limit: batchSize + 1, // get one more extra to detect what to return from cleanup()\n streamingMode: StreamingMode.Exact\n }\n );\n if (range.length > batchSize) {\n noMoreUndeleted = false;\n range.pop();\n }\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n\n Object\n .values(dbs.indexes)\n .forEach(indexMetaInner => {\n const subIndexDB = tx.at(indexMetaInner.db.subspace);\n docsData.forEach(docData => {\n const indexString = indexMetaInner.getIndexableString(docData);\n subIndexDB.delete(indexString);\n });\n });\n docIds.forEach((id: string) => mainTx.delete(id));\n });\n\n return noMoreUndeleted;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject().asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n\n async close() {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n\n const dbs = await this.internals.dbsPromise;\n dbs.root.close();\n\n // TODO shouldn't we close the index databases?\n // Object.values(dbs.indexes).forEach(db => db.close());\n }\n}\n\n\nexport function createFoundationDBStorageInstance(\n storage: RxStorageFoundationDB,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageFoundationDBSettings\n): Promise> {\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n const {\n open,\n directory,\n encoders\n } = require('foundationdb');\n\n const connection = open(settings.clusterFile);\n const dbsPromise = (async () => {\n const dir = await directory.createOrOpen(connection, 'rxdb');\n\n const root = connection\n .at(dir)\n .at(params.databaseName + '.')\n .at(params.collectionName + '.')\n .at(params.schema.version + '.');\n const main: FoundationDBDatabase = root\n .at('main.')\n .withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples\n .withValueEncoding(encoders.json) as any; // and values using JSON\n\n\n const events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>> = root\n .at('events.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n const attachments: FoundationDBDatabase = root\n .at('attachments.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n\n const indexDBs: { [indexName: string]: FoundationDBIndexMeta; } = {};\n const useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : [];\n useIndexes.push([primaryPath]);\n const useIndexesFinal = useIndexes.map(index => {\n const indexAr = Array.isArray(index) ? index.slice(0) : [index];\n indexAr.unshift('_deleted');\n return indexAr;\n });\n // used for `getChangedDocumentsSince()`\n useIndexesFinal.push([\n '_meta.lwt',\n primaryPath\n ]);\n useIndexesFinal.push(CLEANUP_INDEX);\n useIndexesFinal.forEach(indexAr => {\n const indexName = getFoundationDBIndexName(indexAr);\n const indexDB = root.at(indexName + '.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.string);\n indexDBs[indexName] = {\n indexName,\n db: indexDB,\n getIndexableString: getIndexableStringMonad(params.schema, indexAr),\n index: indexAr\n };\n });\n\n return {\n root,\n main,\n events,\n attachments,\n indexes: indexDBs\n };\n })();\n\n\n const internals: FoundationDBStorageInternals = {\n connection,\n dbsPromise: dbsPromise\n };\n\n const instance = new RxStorageInstanceFoundationDB(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAoCA;AAIA;AAKA;AAKA;AAIA;AACA;AACA;AA3BA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA,IAuBaA,6BAA6B;EAWtC,uCACoBC,OAA8B,EAC9BC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAAkD,EAClDC,OAA+D,EAC/DC,QAAuC,EACzD;IAAA,KAXKC,MAAM,GAAG,KAAK;IAAA,KACbC,QAAQ,GAAoG,IAAIC,aAAO,EAAE;IAAA,KAG7GT,OAA8B,GAA9BA,OAA8B;IAAA,KAC9BC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAAkD,GAAlDA,SAAkD;IAAA,KAClDC,OAA+D,GAA/DA,OAA+D;IAAA,KAC/DC,QAAuC,GAAvC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AkD,GAAG;IACvD6I,UAAU,EAAVA,UAAU;IACVjI,UAAU,EAAEA;EAChB,CAAC;EAED,IAAMqJ,QAAQ,GAAG,IAAItK,6BAA6B,CAC9CC,OAAO,EACP6I,MAAM,CAAC5I,YAAY,EACnB4I,MAAM,CAAC3I,cAAc,EACrB2I,MAAM,CAAC1I,MAAM,EACbC,SAAS,EACTyI,MAAM,CAACxI,OAAO,EACdC,QAAQ,CACX;EACD,OAAO+B,OAAO,CAACiI,OAAO,CAACD,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/lib/plugins/json-dump/index.js b/dist/lib/plugins/json-dump/index.js index b2f59753e58..7dd489243df 100644 --- a/dist/lib/plugins/json-dump/index.js +++ b/dist/lib/plugins/json-dump/index.js @@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { exports.RxDBJsonDumpPlugin = void 0; var _rxQuery = require("../../rx-query"); var _rxError = require("../../rx-error"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); /** * this plugin adds the json export/import capabilities to RxDB */ @@ -61,7 +61,7 @@ var dumpRxCollection = function dumpRxCollection() { var query = (0, _rxQuery.createRxQuery)('find', (0, _rxQuery._getDefaultQuery)(), this); return (0, _rxQuery.queryCollection)(query).then(function (docs) { json.docs = docs.map(function (docData) { - docData = (0, _util.flatClone)(docData); + docData = (0, _utils.flatClone)(docData); delete docData._rev; delete docData._attachments; return docData; @@ -81,9 +81,9 @@ function importDumpRxCollection(exportedJSON) { return this.storageInstance.bulkWrite(docs.map(function (docData) { var document = Object.assign({}, docData, { _meta: { - lwt: (0, _util.now)() + lwt: (0, _utils.now)() }, - _rev: (0, _util.getDefaultRevision)(), + _rev: (0, _utils.getDefaultRevision)(), _attachments: {}, _deleted: false }); diff --git a/dist/lib/plugins/json-dump/index.js.map b/dist/lib/plugins/json-dump/index.js.map index 6ce8573f390..fb4da6179b6 100644 --- a/dist/lib/plugins/json-dump/index.js.map +++ b/dist/lib/plugins/json-dump/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["dumpRxDatabase","collections","json","name","instanceToken","token","useCollections","Object","keys","filter","colName","includes","charAt","map","Promise","all","col","exportJSON","then","cols","importDumpRxDatabase","dump","missingCollections","length","newRxError","colDump","importJSON","dumpRxCollection","schemaHash","schema","hash","docs","query","createRxQuery","_getDefaultQuery","queryCollection","docData","flatClone","_rev","_attachments","importDumpRxCollection","exportedJSON","own","storageInstance","bulkWrite","document","assign","_meta","lwt","now","getDefaultRevision","_deleted","RxDBJsonDumpPlugin","rxdb","prototypes","RxDatabase","proto","RxCollection","overwritable"],"sources":["../../../../src/plugins/json-dump/index.ts"],"sourcesContent":["/**\n * this plugin adds the json export/import capabilities to RxDB\n */\nimport {\n createRxQuery,\n queryCollection,\n _getDefaultQuery\n} from '../../rx-query';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDatabase,\n RxCollection,\n RxPlugin,\n RxDocumentData\n} from '../../types';\nimport {\n flatClone,\n getDefaultRevision,\n now\n} from '../../util';\n\nfunction dumpRxDatabase(\n this: RxDatabase,\n collections?: string[]\n): Promise {\n const json: any = {\n name: this.name,\n instanceToken: this.token,\n collections: []\n };\n\n const useCollections = Object.keys(this.collections)\n .filter(colName => !collections || collections.includes(colName))\n .filter(colName => colName.charAt(0) !== '_')\n .map(colName => this.collections[colName]);\n\n return Promise.all(\n useCollections\n .map(col => col.exportJSON())\n ).then(cols => {\n json.collections = cols;\n return json;\n });\n}\n\nconst importDumpRxDatabase = function (\n this: RxDatabase,\n dump: any\n) {\n /**\n * collections must be created before the import\n * because we do not know about the other collection-settings here\n */\n const missingCollections = dump.collections\n .filter((col: any) => !this.collections[col.name])\n .map((col: any) => col.name);\n if (missingCollections.length > 0) {\n throw newRxError('JD1', {\n missingCollections\n });\n }\n\n return Promise.all(\n dump.collections\n .map((colDump: any) => this.collections[colDump.name].importJSON(colDump))\n );\n};\n\nconst dumpRxCollection = function (\n this: RxCollection\n) {\n const json: any = {\n name: this.name,\n schemaHash: this.schema.hash,\n docs: []\n };\n\n const query = createRxQuery(\n 'find',\n _getDefaultQuery(),\n this\n );\n return queryCollection(query)\n .then((docs: any) => {\n json.docs = docs.map((docData: any) => {\n docData = flatClone(docData);\n delete docData._rev;\n delete docData._attachments;\n return docData;\n });\n return json;\n });\n};\n\nfunction importDumpRxCollection(\n this: RxCollection,\n exportedJSON: any\n): Promise {\n // check schemaHash\n if (exportedJSON.schemaHash !== this.schema.hash) {\n throw newRxError('JD2', {\n schemaHash: exportedJSON.schemaHash,\n own: this.schema.hash\n });\n }\n\n const docs: RxDocType[] = exportedJSON.docs;\n return this.storageInstance.bulkWrite(\n docs.map(docData => {\n const document: RxDocumentData = Object.assign(\n {},\n docData,\n {\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision(),\n _attachments: {},\n _deleted: false\n }\n );\n return {\n document\n };\n }),\n 'json-dump-import'\n );\n}\n\nexport const RxDBJsonDumpPlugin: RxPlugin = {\n name: 'json-dump',\n rxdb: true,\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.exportJSON = dumpRxDatabase;\n proto.importJSON = importDumpRxDatabase;\n },\n RxCollection: (proto: any) => {\n proto.exportJSON = dumpRxCollection;\n proto.importJSON = importDumpRxCollection;\n }\n },\n overwritable: {}\n};\n"],"mappings":";;;;;;AAGA;AAKA;AASA;AAjBA;AACA;AACA;;AAqBA,SAASA,cAAc,CAEnBC,WAAsB,EACV;EAAA;EACZ,IAAMC,IAAS,GAAG;IACdC,IAAI,EAAE,IAAI,CAACA,IAAI;IACfC,aAAa,EAAE,IAAI,CAACC,KAAK;IACzBJ,WAAW,EAAE;EACjB,CAAC;EAED,IAAMK,cAAc,GAAGC,MAAM,CAACC,IAAI,CAAC,IAAI,CAACP,WAAW,CAAC,CAC/CQ,MAAM,CAAC,UAAAC,OAAO;IAAA,OAAI,CAACT,WAAW,IAAIA,WAAW,CAACU,QAAQ,CAACD,OAAO,CAAC;EAAA,EAAC,CAChED,MAAM,CAAC,UAAAC,OAAO;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AAC,EACF,kBAAkB,CACrB;AACL;AAEO,IAAMO,kBAA4B,GAAG;EACxCjD,IAAI,EAAE,WAAW;EACjBkD,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACvC,UAAU,GAAGjB,cAAc;MACjCwD,KAAK,CAAC9B,UAAU,GAAGN,oBAAoB;IAC3C,CAAC;IACDqC,YAAY,EAAE,sBAACD,KAAU,EAAK;MAC1BA,KAAK,CAACvC,UAAU,GAAGU,gBAAgB;MACnC6B,KAAK,CAAC9B,UAAU,GAAGc,sBAAsB;IAC7C;EACJ,CAAC;EACDkB,YAAY,EAAE,CAAC;AACnB,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["dumpRxDatabase","collections","json","name","instanceToken","token","useCollections","Object","keys","filter","colName","includes","charAt","map","Promise","all","col","exportJSON","then","cols","importDumpRxDatabase","dump","missingCollections","length","newRxError","colDump","importJSON","dumpRxCollection","schemaHash","schema","hash","docs","query","createRxQuery","_getDefaultQuery","queryCollection","docData","flatClone","_rev","_attachments","importDumpRxCollection","exportedJSON","own","storageInstance","bulkWrite","document","assign","_meta","lwt","now","getDefaultRevision","_deleted","RxDBJsonDumpPlugin","rxdb","prototypes","RxDatabase","proto","RxCollection","overwritable"],"sources":["../../../../src/plugins/json-dump/index.ts"],"sourcesContent":["/**\n * this plugin adds the json export/import capabilities to RxDB\n */\nimport {\n createRxQuery,\n queryCollection,\n _getDefaultQuery\n} from '../../rx-query';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDatabase,\n RxCollection,\n RxPlugin,\n RxDocumentData\n} from '../../types';\nimport {\n flatClone,\n getDefaultRevision,\n now\n} from '../../plugins/utils';\n\nfunction dumpRxDatabase(\n this: RxDatabase,\n collections?: string[]\n): Promise {\n const json: any = {\n name: this.name,\n instanceToken: this.token,\n collections: []\n };\n\n const useCollections = Object.keys(this.collections)\n .filter(colName => !collections || collections.includes(colName))\n .filter(colName => colName.charAt(0) !== '_')\n .map(colName => this.collections[colName]);\n\n return Promise.all(\n useCollections\n .map(col => col.exportJSON())\n ).then(cols => {\n json.collections = cols;\n return json;\n });\n}\n\nconst importDumpRxDatabase = function (\n this: RxDatabase,\n dump: any\n) {\n /**\n * collections must be created before the import\n * because we do not know about the other collection-settings here\n */\n const missingCollections = dump.collections\n .filter((col: any) => !this.collections[col.name])\n .map((col: any) => col.name);\n if (missingCollections.length > 0) {\n throw newRxError('JD1', {\n missingCollections\n });\n }\n\n return Promise.all(\n dump.collections\n .map((colDump: any) => this.collections[colDump.name].importJSON(colDump))\n );\n};\n\nconst dumpRxCollection = function (\n this: RxCollection\n) {\n const json: any = {\n name: this.name,\n schemaHash: this.schema.hash,\n docs: []\n };\n\n const query = createRxQuery(\n 'find',\n _getDefaultQuery(),\n this\n );\n return queryCollection(query)\n .then((docs: any) => {\n json.docs = docs.map((docData: any) => {\n docData = flatClone(docData);\n delete docData._rev;\n delete docData._attachments;\n return docData;\n });\n return json;\n });\n};\n\nfunction importDumpRxCollection(\n this: RxCollection,\n exportedJSON: any\n): Promise {\n // check schemaHash\n if (exportedJSON.schemaHash !== this.schema.hash) {\n throw newRxError('JD2', {\n schemaHash: exportedJSON.schemaHash,\n own: this.schema.hash\n });\n }\n\n const docs: RxDocType[] = exportedJSON.docs;\n return this.storageInstance.bulkWrite(\n docs.map(docData => {\n const document: RxDocumentData = Object.assign(\n {},\n docData,\n {\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision(),\n _attachments: {},\n _deleted: false\n }\n );\n return {\n document\n };\n }),\n 'json-dump-import'\n );\n}\n\nexport const RxDBJsonDumpPlugin: RxPlugin = {\n name: 'json-dump',\n rxdb: true,\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.exportJSON = dumpRxDatabase;\n proto.importJSON = importDumpRxDatabase;\n },\n RxCollection: (proto: any) => {\n proto.exportJSON = dumpRxCollection;\n proto.importJSON = importDumpRxCollection;\n }\n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AAC,CAAC;EACN;EAEA,IAAMC,IAAiB,GAAGU,YAAY,CAACV,IAAI;EAC3C,OAAO,IAAI,CAACY,eAAe,CAACC,SAAS,CACjCb,IAAI,CAAClB,GAAG,CAAC,UAAAuB,OAAO,EAAI;IAChB,IAAMS,QAAmC,GAAGtC,MAAM,CAACuC,MAAM,CACrD,CAAC,CAAC,EACFV,OAAO,EACP;MACIW,KAAK,EAAE;QACHC,GAAG,EAAE,IAAAC,UAAG;MACZ,CAAC;MACDX,IAAI,EAAE,IAAAY,yBAAkB,GAAE;MAC1BX,YAAY,EAAE,CAAC,CAAC;MAChBY,QAAQ,EAAE;IACd,CAAC,CACJ;IACD,OAAO;MACHN,QAAQ,EAARA;IACJ,CAAC;EACL,CAAC,CAAC,EACF,kBAAkB,CACrB;AACL;AAEO,IAAMO,kBAA4B,GAAG;EACxCjD,IAAI,EAAE,WAAW;EACjBkD,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACvC,UAAU,GAAGjB,cAAc;MACjCwD,KAAK,CAAC9B,UAAU,GAAGN,oBAAoB;IAC3C,CAAC;IACDqC,YAAY,EAAE,sBAACD,KAAU,EAAK;MAC1BA,KAAK,CAACvC,UAAU,GAAGU,gBAAgB;MACnC6B,KAAK,CAAC9B,UAAU,GAAGc,sBAAsB;IAC7C;EACJ,CAAC;EACDkB,YAAY,EAAE,CAAC;AACnB,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/key-compression/index.js b/dist/lib/plugins/key-compression/index.js index 4a6e87d7258..33d8b1c4fa7 100644 --- a/dist/lib/plugins/key-compression/index.js +++ b/dist/lib/plugins/key-compression/index.js @@ -1,5 +1,6 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -7,12 +8,14 @@ exports.compressDocumentData = compressDocumentData; exports.decompressDocumentData = decompressDocumentData; exports.getCompressionStateByRxJsonSchema = getCompressionStateByRxJsonSchema; exports.wrappedKeyCompressionStorage = wrappedKeyCompressionStorage; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _jsonschemaKeyCompression = require("jsonschema-key-compression"); var _overwritable = require("../../overwritable"); var _pluginHelpers = require("../../plugin-helpers"); var _rxSchemaHelper = require("../../rx-schema-helper"); var _rxStorageHelper = require("../../rx-storage-helper"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); /** * this plugin adds the keycompression-capabilities to rxdb * if you dont use this, ensure that you set disableKeyComression to false in your schema @@ -32,7 +35,7 @@ function getCompressionStateByRxJsonSchema(schema) { _overwritable.overwritable.deepFreezeWhenDevMode(schema); var compressionState = COMPRESSION_STATE_BY_SCHEMA.get(schema); if (!compressionState) { - var compressionSchema = (0, _util.flatClone)(schema); + var compressionSchema = (0, _utils.flatClone)(schema); delete compressionSchema.primaryKey; var table = (0, _jsonschemaKeyCompression.createCompressionTable)(compressionSchema, _jsonschemaKeyCompression.DEFAULT_COMPRESSION_FLAG, [ /** @@ -64,7 +67,7 @@ function getCompressionStateByRxJsonSchema(schema) { */ if (schema.indexes) { var newIndexes = schema.indexes.map(function (idx) { - if ((0, _util.isMaybeReadonlyArray)(idx)) { + if ((0, _utils.isMaybeReadonlyArray)(idx)) { return idx.map(function (subIdx) { return (0, _jsonschemaKeyCompression.compressedPath)(table, subIdx); }); @@ -123,35 +126,51 @@ function wrappedKeyCompressionStorage(args) { }); return Object.assign({}, args.storage, { statics: statics, - createStorageInstance: function createStorageInstance(params) { - try { - var modifyToStorage = function modifyToStorage(docData) { - return compressDocumentData(compressionState, docData); - }; - var modifyFromStorage = function modifyFromStorage(docData) { - return decompressDocumentData(compressionState, docData); - }; - /** - * Because this wrapper resolves the key-compression, - * we can set the flag to false - * which allows underlying storages to detect wrong conficturations - * like when keyCompression is set to false but no key-compression module is used. - */ - if (!params.schema.keyCompression) { - return Promise.resolve(args.storage.createStorageInstance(params)); - } - var compressionState = getCompressionStateByRxJsonSchema(params.schema); - var childSchema = (0, _util.flatClone)(compressionState.compressedSchema); - childSchema.keyCompression = false; - return Promise.resolve(args.storage.createStorageInstance(Object.assign({}, params, { - schema: childSchema - }))).then(function (instance) { - return (0, _pluginHelpers.wrapRxStorageInstance)(instance, modifyToStorage, modifyFromStorage); - }); - } catch (e) { - return Promise.reject(e); + createStorageInstance: function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var compressionState, modifyToStorage, modifyFromStorage, childSchema, instance; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + modifyFromStorage = function _modifyFromStorage(docData) { + return decompressDocumentData(compressionState, docData); + }; + modifyToStorage = function _modifyToStorage(docData) { + return compressDocumentData(compressionState, docData); + }; + if (params.schema.keyCompression) { + _context.next = 4; + break; + } + return _context.abrupt("return", args.storage.createStorageInstance(params)); + case 4: + compressionState = getCompressionStateByRxJsonSchema(params.schema); + /** + * Because this wrapper resolves the key-compression, + * we can set the flag to false + * which allows underlying storages to detect wrong conficturations + * like when keyCompression is set to false but no key-compression module is used. + */ + childSchema = (0, _utils.flatClone)(compressionState.compressedSchema); + childSchema.keyCompression = false; + _context.next = 9; + return args.storage.createStorageInstance(Object.assign({}, params, { + schema: childSchema + })); + case 9: + instance = _context.sent; + return _context.abrupt("return", (0, _pluginHelpers.wrapRxStorageInstance)(instance, modifyToStorage, modifyFromStorage)); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); } function compressDocumentData(compressionState, docData) { diff --git a/dist/lib/plugins/key-compression/index.js.map b/dist/lib/plugins/key-compression/index.js.map index 08b451445c5..7959b930eb8 100644 --- a/dist/lib/plugins/key-compression/index.js.map +++ b/dist/lib/plugins/key-compression/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["COMPRESSION_STATE_BY_SCHEMA","WeakMap","getCompressionStateByRxJsonSchema","schema","overwritable","deepFreezeWhenDevMode","compressionState","get","compressionSchema","flatClone","primaryKey","table","createCompressionTable","DEFAULT_COMPRESSION_FLAG","getPrimaryFieldOfPrimaryKey","compressedSchema","createCompressedJsonSchema","composedPrimary","newComposedPrimary","key","compressedPath","fields","map","field","separator","indexes","newIndexes","idx","isMaybeReadonlyArray","subIdx","set","wrappedKeyCompressionStorage","args","statics","Object","assign","storage","prepareQuery","mutateableQuery","keyCompression","compressQuery","getSortComparator","preparedQuery","comparator","a","b","compressedDocDataA","compressObject","compressedDocDataB","res","getQueryMatcher","matcher","docData","compressedDocData","ret","createStorageInstance","params","modifyToStorage","compressDocumentData","modifyFromStorage","decompressDocumentData","childSchema","instance","wrapRxStorageInstance","flatCloneDocWithMeta","attachments","_attachments","decompressObject"],"sources":["../../../../src/plugins/key-compression/index.ts"],"sourcesContent":["/**\n * this plugin adds the keycompression-capabilities to rxdb\n * if you dont use this, ensure that you set disableKeyComression to false in your schema\n */\n\nimport type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport {\n createCompressionTable,\n CompressionTable,\n JsonSchema as KeyCompressionJsonSchema,\n compressObject,\n decompressObject,\n compressedPath,\n DEFAULT_COMPRESSION_FLAG,\n createCompressedJsonSchema,\n compressQuery\n} from 'jsonschema-key-compression';\nimport {\n overwritable\n} from '../../overwritable';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../../rx-storage-helper';\n\nimport type {\n RxJsonSchema,\n CompositePrimaryKey,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxDocumentData,\n RxStorageStatics,\n FilledMangoQuery,\n PreparedQuery,\n RxDocumentWriteData\n} from '../../types';\nimport {\n flatClone,\n isMaybeReadonlyArray\n} from '../../util';\n\ndeclare type CompressionState = {\n table: CompressionTable;\n schema: RxJsonSchema;\n compressedSchema: RxJsonSchema;\n};\n\n/**\n * Cache the compression table and the compressed schema\n * by the storage instance for better performance.\n */\nconst COMPRESSION_STATE_BY_SCHEMA: WeakMap<\nRxJsonSchema,\nCompressionState\n> = new WeakMap();\n\n\nexport function getCompressionStateByRxJsonSchema(\n schema: RxJsonSchema\n): CompressionState {\n /**\n * Because we cache the state by the JsonSchema,\n * it must be ausured that the given schema object\n * is never mutated.\n */\n overwritable.deepFreezeWhenDevMode(schema);\n\n let compressionState = COMPRESSION_STATE_BY_SCHEMA.get(schema);\n if (!compressionState) {\n const compressionSchema: KeyCompressionJsonSchema = flatClone(schema) as any;\n delete (compressionSchema as any).primaryKey;\n\n const table = createCompressionTable(\n compressionSchema,\n DEFAULT_COMPRESSION_FLAG,\n [\n /**\n * Do not compress the primary field\n * for easier debugging.\n */\n getPrimaryFieldOfPrimaryKey(schema.primaryKey),\n '_rev',\n '_attachments',\n '_deleted',\n '_meta'\n ]\n );\n\n delete (compressionSchema as any).primaryKey;\n const compressedSchema: RxJsonSchema = createCompressedJsonSchema(\n table,\n compressionSchema\n ) as RxJsonSchema;\n\n // also compress primary key\n if (typeof schema.primaryKey !== 'string') {\n const composedPrimary: CompositePrimaryKey = schema.primaryKey;\n const newComposedPrimary: CompositePrimaryKey = {\n key: compressedPath(table, composedPrimary.key as string),\n fields: composedPrimary.fields.map(field => compressedPath(table, field as string)),\n separator: composedPrimary.separator\n };\n compressedSchema.primaryKey = newComposedPrimary;\n } else {\n compressedSchema.primaryKey = compressedPath(table, schema.primaryKey);\n }\n\n /**\n * the key compression module does not know about indexes\n * in the schema, so we have to also compress them here.\n */\n if (schema.indexes) {\n const newIndexes = schema.indexes.map(idx => {\n if (isMaybeReadonlyArray(idx)) {\n return idx.map(subIdx => compressedPath(table, subIdx));\n } else {\n return compressedPath(table, idx);\n }\n });\n compressedSchema.indexes = newIndexes;\n }\n\n compressionState = {\n table,\n schema,\n compressedSchema\n };\n COMPRESSION_STATE_BY_SCHEMA.set(schema, compressionState);\n }\n return compressionState;\n}\n\nexport function wrappedKeyCompressionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n const statics: RxStorageStatics = Object.assign(\n {},\n args.storage.statics,\n {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery {\n if (schema.keyCompression) {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n mutateableQuery = compressQuery(\n compressionState.table,\n mutateableQuery as any\n ) as any;\n return args.storage.statics.prepareQuery(\n compressionState.compressedSchema,\n mutateableQuery\n );\n }\n return args.storage.statics.prepareQuery(\n schema,\n mutateableQuery\n );\n },\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator {\n if (!schema.keyCompression) {\n return args.storage.statics.getSortComparator(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const comparator = args.storage.statics.getSortComparator(compressionState.schema, preparedQuery);\n return (a, b) => {\n const compressedDocDataA = compressObject(\n compressionState.table,\n a as any\n );\n const compressedDocDataB = compressObject(\n compressionState.table,\n b as any\n );\n const res = comparator(compressedDocDataA, compressedDocDataB);\n return res;\n };\n }\n },\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher> {\n if (!schema.keyCompression) {\n return args.storage.statics.getQueryMatcher(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const matcher = args.storage.statics.getQueryMatcher(compressionState.schema, preparedQuery);\n return (docData) => {\n const compressedDocData = compressObject(\n compressionState.table,\n docData\n );\n const ret = matcher(compressedDocData);\n return ret;\n };\n }\n }\n }\n );\n\n return Object.assign(\n {},\n args.storage,\n {\n statics,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!params.schema.keyCompression) {\n return args.storage.createStorageInstance(params);\n }\n\n const compressionState = getCompressionStateByRxJsonSchema(params.schema);\n function modifyToStorage(docData: RxDocumentWriteData) {\n return compressDocumentData(compressionState, docData);\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n return decompressDocumentData(compressionState, docData);\n }\n\n /**\n * Because this wrapper resolves the key-compression,\n * we can set the flag to false\n * which allows underlying storages to detect wrong conficturations\n * like when keyCompression is set to false but no key-compression module is used.\n */\n const childSchema = flatClone(compressionState.compressedSchema);\n childSchema.keyCompression = false;\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: childSchema\n }\n )\n );\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage\n );\n }\n }\n );\n}\n\nexport function compressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n /**\n * Do not send attachments to compressObject()\n * because it will deep clone which does not work on Blob or Buffer.\n */\n docData = flatCloneDocWithMeta(docData);\n const attachments = docData._attachments;\n delete docData._attachments;\n\n docData = compressObject(\n compressionState.table,\n docData\n );\n docData._attachments = attachments;\n return docData;\n}\n\nexport function decompressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n return decompressObject(\n compressionState.table,\n docData\n );\n}\n"],"mappings":";;;;;;;;;AASA;AAWA;AAGA;AACA;AACA;AAaA;AAtCA;AACA;AACA;AACA;;AA8CA;AACA;AACA;AACA;AACA,IAAMA,2BAGL,GAAG,IAAIC,OAAO,EAAE;AAGV,SAASC,iCAAiC,CAC7CC,MAAyB,EACT;EAChB;AACJ;AACA;AACA;AACA;EACIC,0BAAY,CAACC,qBAAqB,CAACF,MAAM,CAAC;EAE1C,IAAIG,gBAAgB,GAAGN,2BAA2B,CAACO,GAAG,CAACJ,MAAM,CAAC;EAC9D,IAAI,CAACG,gBAAgB,EAAE;IACnB,IAAME,iBAA2C,GAAG,IAAAC,eAAS,EAACN,MAAM,CAAQ;IAC5E,OAAQK,iBAAiB,CAASE,UAAU;IA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8C,OAA4B,EACT;EACnB,OAAO,IAAAe,0CAAgB,EACnB7D,gBAAgB,CAACK,KAAK,EACtByC,OAAO,CACV;AACL"} \ No newline at end of file +{"version":3,"file":"index.js","names":["COMPRESSION_STATE_BY_SCHEMA","WeakMap","getCompressionStateByRxJsonSchema","schema","overwritable","deepFreezeWhenDevMode","compressionState","get","compressionSchema","flatClone","primaryKey","table","createCompressionTable","DEFAULT_COMPRESSION_FLAG","getPrimaryFieldOfPrimaryKey","compressedSchema","createCompressedJsonSchema","composedPrimary","newComposedPrimary","key","compressedPath","fields","map","field","separator","indexes","newIndexes","idx","isMaybeReadonlyArray","subIdx","set","wrappedKeyCompressionStorage","args","statics","Object","assign","storage","prepareQuery","mutateableQuery","keyCompression","compressQuery","getSortComparator","preparedQuery","comparator","a","b","compressedDocDataA","compressObject","compressedDocDataB","res","getQueryMatcher","matcher","docData","compressedDocData","ret","createStorageInstance","params","modifyToStorage","modifyFromStorage","decompressDocumentData","compressDocumentData","childSchema","instance","wrapRxStorageInstance","flatCloneDocWithMeta","attachments","_attachments","decompressObject"],"sources":["../../../../src/plugins/key-compression/index.ts"],"sourcesContent":["/**\n * this plugin adds the keycompression-capabilities to rxdb\n * if you dont use this, ensure that you set disableKeyComression to false in your schema\n */\n\nimport type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport {\n createCompressionTable,\n CompressionTable,\n JsonSchema as KeyCompressionJsonSchema,\n compressObject,\n decompressObject,\n compressedPath,\n DEFAULT_COMPRESSION_FLAG,\n createCompressedJsonSchema,\n compressQuery\n} from 'jsonschema-key-compression';\nimport {\n overwritable\n} from '../../overwritable';\nimport { wrapRxStorageInstance } from '../../plugin-helpers';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../../rx-storage-helper';\n\nimport type {\n RxJsonSchema,\n CompositePrimaryKey,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxDocumentData,\n RxStorageStatics,\n FilledMangoQuery,\n PreparedQuery,\n RxDocumentWriteData\n} from '../../types';\nimport {\n flatClone,\n isMaybeReadonlyArray\n} from '../../plugins/utils';\n\ndeclare type CompressionState = {\n table: CompressionTable;\n schema: RxJsonSchema;\n compressedSchema: RxJsonSchema;\n};\n\n/**\n * Cache the compression table and the compressed schema\n * by the storage instance for better performance.\n */\nconst COMPRESSION_STATE_BY_SCHEMA: WeakMap<\nRxJsonSchema,\nCompressionState\n> = new WeakMap();\n\n\nexport function getCompressionStateByRxJsonSchema(\n schema: RxJsonSchema\n): CompressionState {\n /**\n * Because we cache the state by the JsonSchema,\n * it must be ausured that the given schema object\n * is never mutated.\n */\n overwritable.deepFreezeWhenDevMode(schema);\n\n let compressionState = COMPRESSION_STATE_BY_SCHEMA.get(schema);\n if (!compressionState) {\n const compressionSchema: KeyCompressionJsonSchema = flatClone(schema) as any;\n delete (compressionSchema as any).primaryKey;\n\n const table = createCompressionTable(\n compressionSchema,\n DEFAULT_COMPRESSION_FLAG,\n [\n /**\n * Do not compress the primary field\n * for easier debugging.\n */\n getPrimaryFieldOfPrimaryKey(schema.primaryKey),\n '_rev',\n '_attachments',\n '_deleted',\n '_meta'\n ]\n );\n\n delete (compressionSchema as any).primaryKey;\n const compressedSchema: RxJsonSchema = createCompressedJsonSchema(\n table,\n compressionSchema\n ) as RxJsonSchema;\n\n // also compress primary key\n if (typeof schema.primaryKey !== 'string') {\n const composedPrimary: CompositePrimaryKey = schema.primaryKey;\n const newComposedPrimary: CompositePrimaryKey = {\n key: compressedPath(table, composedPrimary.key as string),\n fields: composedPrimary.fields.map(field => compressedPath(table, field as string)),\n separator: composedPrimary.separator\n };\n compressedSchema.primaryKey = newComposedPrimary;\n } else {\n compressedSchema.primaryKey = compressedPath(table, schema.primaryKey);\n }\n\n /**\n * the key compression module does not know about indexes\n * in the schema, so we have to also compress them here.\n */\n if (schema.indexes) {\n const newIndexes = schema.indexes.map(idx => {\n if (isMaybeReadonlyArray(idx)) {\n return idx.map(subIdx => compressedPath(table, subIdx));\n } else {\n return compressedPath(table, idx);\n }\n });\n compressedSchema.indexes = newIndexes;\n }\n\n compressionState = {\n table,\n schema,\n compressedSchema\n };\n COMPRESSION_STATE_BY_SCHEMA.set(schema, compressionState);\n }\n return compressionState;\n}\n\nexport function wrappedKeyCompressionStorage(\n args: {\n storage: RxStorage;\n }\n): RxStorage {\n const statics: RxStorageStatics = Object.assign(\n {},\n args.storage.statics,\n {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery {\n if (schema.keyCompression) {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n mutateableQuery = compressQuery(\n compressionState.table,\n mutateableQuery as any\n ) as any;\n return args.storage.statics.prepareQuery(\n compressionState.compressedSchema,\n mutateableQuery\n );\n }\n return args.storage.statics.prepareQuery(\n schema,\n mutateableQuery\n );\n },\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator {\n if (!schema.keyCompression) {\n return args.storage.statics.getSortComparator(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const comparator = args.storage.statics.getSortComparator(compressionState.schema, preparedQuery);\n return (a, b) => {\n const compressedDocDataA = compressObject(\n compressionState.table,\n a as any\n );\n const compressedDocDataB = compressObject(\n compressionState.table,\n b as any\n );\n const res = comparator(compressedDocDataA, compressedDocDataB);\n return res;\n };\n }\n },\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher> {\n if (!schema.keyCompression) {\n return args.storage.statics.getQueryMatcher(schema, preparedQuery);\n } else {\n const compressionState = getCompressionStateByRxJsonSchema(schema);\n const matcher = args.storage.statics.getQueryMatcher(compressionState.schema, preparedQuery);\n return (docData) => {\n const compressedDocData = compressObject(\n compressionState.table,\n docData\n );\n const ret = matcher(compressedDocData);\n return ret;\n };\n }\n }\n }\n );\n\n return Object.assign(\n {},\n args.storage,\n {\n statics,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n if (!params.schema.keyCompression) {\n return args.storage.createStorageInstance(params);\n }\n\n const compressionState = getCompressionStateByRxJsonSchema(params.schema);\n function modifyToStorage(docData: RxDocumentWriteData) {\n return compressDocumentData(compressionState, docData);\n }\n function modifyFromStorage(docData: RxDocumentData): Promise> {\n return decompressDocumentData(compressionState, docData);\n }\n\n /**\n * Because this wrapper resolves the key-compression,\n * we can set the flag to false\n * which allows underlying storages to detect wrong conficturations\n * like when keyCompression is set to false but no key-compression module is used.\n */\n const childSchema = flatClone(compressionState.compressedSchema);\n childSchema.keyCompression = false;\n\n const instance = await args.storage.createStorageInstance(\n Object.assign(\n {},\n params,\n {\n schema: childSchema\n }\n )\n );\n\n return wrapRxStorageInstance(\n instance,\n modifyToStorage,\n modifyFromStorage\n );\n }\n }\n );\n}\n\nexport function compressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n /**\n * Do not send attachments to compressObject()\n * because it will deep clone which does not work on Blob or Buffer.\n */\n docData = flatCloneDocWithMeta(docData);\n const attachments = docData._attachments;\n delete docData._attachments;\n\n docData = compressObject(\n compressionState.table,\n docData\n );\n docData._attachments = attachments;\n return docData;\n}\n\nexport function decompressDocumentData(\n compressionState: CompressionState,\n docData: RxDocumentData\n): RxDocumentData {\n return decompressObject(\n compressionState.table,\n docData\n );\n}\n"],"mappings":";;;;;;;;;;;;AASA;AAWA;AAGA;AACA;AACA;AAaA;AAtCA;AACA;AACA;AACA;;AA8CA;AACA;AACA;AACA;AACA,IAAMA,2BAGL,GAAG,IAAIC,OAAO,EAAE;AAGV,SAASC,iCAAiC,CAC7CC,MAAyB,EACT;EAChB;AACJ;AACA;AACA;AACA;EACIC,0BAAY,CAACC,qBAAqB,CAACF,MAAM,CAAC;EAE1C,IAAIG,gBAAgB,GAAGN,2BAA2B,CAACO,GAAG,CAACJ,MAAM,CAAC;EAC9D,IAAI,CAACG,gBAAgB,EAAE;IACnB,IAAME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KAAK,EACtByC,OAAO,CACV;EACDA,OAAO,CAACc,YAAY,GAAGD,WAAW;EAClC,OAAOb,OAAO;AAClB;AAEO,SAASO,sBAAsB,CAClCrD,gBAAkC,EAClC8C,OAA4B,EACT;EACnB,OAAO,IAAAe,0CAAgB,EACnB7D,gBAAgB,CAACK,KAAK,EACtByC,OAAO,CACV;AACL"} \ No newline at end of file diff --git a/dist/lib/plugins/leader-election/index.js b/dist/lib/plugins/leader-election/index.js index 2556f491e5b..86a1b4b22b4 100644 --- a/dist/lib/plugins/leader-election/index.js +++ b/dist/lib/plugins/leader-election/index.js @@ -12,7 +12,7 @@ exports.rxdb = exports.prototypes = void 0; exports.waitForLeadership = waitForLeadership; var _broadcastChannel = require("broadcast-channel"); var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); -var _util = require("../../util"); +var _utils = require("../utils"); /** * this plugin adds the leader-election-capabilities to rxdb */ @@ -69,7 +69,7 @@ function isLeader() { } function waitForLeadership() { if (!this.multiInstance) { - return _util.PROMISE_RESOLVE_TRUE; + return _utils.PROMISE_RESOLVE_TRUE; } else { return this.leaderElector().awaitLeadership().then(function () { return true; diff --git a/dist/lib/plugins/leader-election/index.js.map b/dist/lib/plugins/leader-election/index.js.map index d75a3c32177..95a40c9de0a 100644 --- a/dist/lib/plugins/leader-election/index.js.map +++ b/dist/lib/plugins/leader-election/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["LEADER_ELECTORS_OF_DB","WeakMap","LEADER_ELECTOR_BY_BROADCAST_CHANNEL","getLeaderElectorByBroadcastChannel","broadcastChannel","elector","get","createLeaderElection","set","getForDatabase","getBroadcastChannelReference","token","name","oldDestroy","destroy","bind","removeBroadcastChannelReference","leaderElector","isLeader","multiInstance","waitForLeadership","PROMISE_RESOLVE_TRUE","awaitLeadership","then","onDestroy","db","has","die","rxdb","prototypes","RxDatabase","proto","RxDBLeaderElectionPlugin","hooks","preDestroyRxDatabase","after"],"sources":["../../../../src/plugins/leader-election/index.ts"],"sourcesContent":["/**\n * this plugin adds the leader-election-capabilities to rxdb\n */\n\nimport {\n createLeaderElection,\n LeaderElector,\n BroadcastChannel\n} from 'broadcast-channel';\nimport {\n getBroadcastChannelReference,\n removeBroadcastChannelReference\n} from '../../rx-storage-multiinstance';\n\nimport type {\n RxDatabase,\n RxPlugin\n} from '../../types';\nimport {\n PROMISE_RESOLVE_TRUE\n} from '../../util';\n\nconst LEADER_ELECTORS_OF_DB: WeakMap = new WeakMap();\nconst LEADER_ELECTOR_BY_BROADCAST_CHANNEL: WeakMap = new WeakMap();\n\n\n/**\n * Returns the leader elector of a broadcast channel.\n * Used to ensure we reuse the same elector for the channel each time.\n */\nexport function getLeaderElectorByBroadcastChannel(broadcastChannel: BroadcastChannel): LeaderElector {\n let elector = LEADER_ELECTOR_BY_BROADCAST_CHANNEL.get(broadcastChannel);\n if (!elector) {\n elector = createLeaderElection(broadcastChannel);\n LEADER_ELECTOR_BY_BROADCAST_CHANNEL.set(broadcastChannel, elector);\n }\n return elector;\n}\n\n/**\n * @overwrites RxDatabase().leaderElector for caching\n */\nexport function getForDatabase(this: RxDatabase): LeaderElector {\n\n\n const broadcastChannel = getBroadcastChannelReference(\n this.token,\n this.name,\n this\n );\n\n /**\n * Clean up the reference on RxDatabase.destroy()\n */\n const oldDestroy = this.destroy.bind(this);\n this.destroy = function () {\n removeBroadcastChannelReference(this.token, this);\n return oldDestroy();\n };\n\n\n let elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n if (!elector) {\n elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n LEADER_ELECTORS_OF_DB.set(\n this,\n elector\n );\n }\n\n /**\n * Overwrite for caching\n */\n this.leaderElector = () => elector;\n\n return elector;\n}\n\nexport function isLeader(this: RxDatabase): boolean {\n if (!this.multiInstance) {\n return true;\n }\n return this.leaderElector().isLeader;\n}\n\nexport function waitForLeadership(this: RxDatabase): Promise {\n if (!this.multiInstance) {\n return PROMISE_RESOLVE_TRUE;\n } else {\n return this.leaderElector()\n .awaitLeadership()\n .then(() => true);\n }\n}\n\n/**\n * runs when the database gets destroyed\n */\nexport function onDestroy(db: RxDatabase) {\n const has = LEADER_ELECTORS_OF_DB.get(db);\n if (has) {\n has.die();\n }\n}\n\nexport const rxdb = true;\nexport const prototypes = {\n RxDatabase: (proto: any) => {\n proto.leaderElector = getForDatabase;\n proto.isLeader = isLeader;\n proto.waitForLeadership = waitForLeadership;\n }\n};\n\nexport const RxDBLeaderElectionPlugin: RxPlugin = {\n name: 'leader-election',\n rxdb,\n prototypes,\n hooks: {\n preDestroyRxDatabase: {\n after: onDestroy\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAIA;AAKA;AASA;AAlBA;AACA;AACA;;AAoBA,IAAMA,qBAAyD,GAAG,IAAIC,OAAO,EAAE;AAC/E,IAAMC,mCAA6E,GAAG,IAAID,OAAO,EAAE;;AAGnG;AACA;AACA;AACA;AACO,SAASE,kCAAkC,CAACC,gBAAkC,EAAiB;EAClG,IAAIC,OAAO,GAAGH,mCAAmC,CAACI,GAAG,CAACF,gBAAgB,CAAC;EACvE,IAAI,CAACC,OAAO,EAAE;IACVA,OAAO,GAAG,IAAAE,sCAAoB,EAACH,gBAAgB,CAAC;IAChDF,mCAAmC,CAACM,GAAG,CAACJ,gBAAgB,EAAEC,OAAO,CAAC;EACtE;EACA,OAAOA,OAAO;AAClB;;AAEA;AACA;AACA;AACO,SAASI,cAAc,GAAkC;EAG5D,IAAML,gBAAgB,GAAG,IAAAM,oDAA4B,EACjD,IAAI,CAACC,KAAK,EACV,IAAI,CAACC,IAAI,EACT,IAAI,CACP;;EAED;AACJ;AACA;EACI,IAAMC,UAAU,GAAG,IAAI,CAACC,OAAO,CAACC,IAAI,CAAC,IAAI,CAAC;EAC1C,IAAI,CAACD,OAAO,GAAG,YAAY;IACvB,IAAAE,uDAA+B,EAAC,IAAI,CAACL,KAAK,EAAE,IAAI,CAAC;IACjD,OAAOE,UAAU,EAAE;EACvB,CAAC;EAGD,IAAI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AAoB,EAAE;MAClBC,KAAK,EAAEX;IACX;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["LEADER_ELECTORS_OF_DB","WeakMap","LEADER_ELECTOR_BY_BROADCAST_CHANNEL","getLeaderElectorByBroadcastChannel","broadcastChannel","elector","get","createLeaderElection","set","getForDatabase","getBroadcastChannelReference","token","name","oldDestroy","destroy","bind","removeBroadcastChannelReference","leaderElector","isLeader","multiInstance","waitForLeadership","PROMISE_RESOLVE_TRUE","awaitLeadership","then","onDestroy","db","has","die","rxdb","prototypes","RxDatabase","proto","RxDBLeaderElectionPlugin","hooks","preDestroyRxDatabase","after"],"sources":["../../../../src/plugins/leader-election/index.ts"],"sourcesContent":["/**\n * this plugin adds the leader-election-capabilities to rxdb\n */\n\nimport {\n createLeaderElection,\n LeaderElector,\n BroadcastChannel\n} from 'broadcast-channel';\nimport {\n getBroadcastChannelReference,\n removeBroadcastChannelReference\n} from '../../rx-storage-multiinstance';\n\nimport type {\n RxDatabase,\n RxPlugin\n} from '../../types';\nimport { PROMISE_RESOLVE_TRUE } from '../utils';\n\nconst LEADER_ELECTORS_OF_DB: WeakMap = new WeakMap();\nconst LEADER_ELECTOR_BY_BROADCAST_CHANNEL: WeakMap = new WeakMap();\n\n\n/**\n * Returns the leader elector of a broadcast channel.\n * Used to ensure we reuse the same elector for the channel each time.\n */\nexport function getLeaderElectorByBroadcastChannel(broadcastChannel: BroadcastChannel): LeaderElector {\n let elector = LEADER_ELECTOR_BY_BROADCAST_CHANNEL.get(broadcastChannel);\n if (!elector) {\n elector = createLeaderElection(broadcastChannel);\n LEADER_ELECTOR_BY_BROADCAST_CHANNEL.set(broadcastChannel, elector);\n }\n return elector;\n}\n\n/**\n * @overwrites RxDatabase().leaderElector for caching\n */\nexport function getForDatabase(this: RxDatabase): LeaderElector {\n\n\n const broadcastChannel = getBroadcastChannelReference(\n this.token,\n this.name,\n this\n );\n\n /**\n * Clean up the reference on RxDatabase.destroy()\n */\n const oldDestroy = this.destroy.bind(this);\n this.destroy = function () {\n removeBroadcastChannelReference(this.token, this);\n return oldDestroy();\n };\n\n\n let elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n if (!elector) {\n elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n LEADER_ELECTORS_OF_DB.set(\n this,\n elector\n );\n }\n\n /**\n * Overwrite for caching\n */\n this.leaderElector = () => elector;\n\n return elector;\n}\n\nexport function isLeader(this: RxDatabase): boolean {\n if (!this.multiInstance) {\n return true;\n }\n return this.leaderElector().isLeader;\n}\n\nexport function waitForLeadership(this: RxDatabase): Promise {\n if (!this.multiInstance) {\n return PROMISE_RESOLVE_TRUE;\n } else {\n return this.leaderElector()\n .awaitLeadership()\n .then(() => true);\n }\n}\n\n/**\n * runs when the database gets destroyed\n */\nexport function onDestroy(db: RxDatabase) {\n const has = LEADER_ELECTORS_OF_DB.get(db);\n if (has) {\n has.die();\n }\n}\n\nexport const rxdb = true;\nexport const prototypes = {\n RxDatabase: (proto: any) => {\n proto.leaderElector = getForDatabase;\n proto.isLeader = isLeader;\n proto.waitForLeadership = waitForLeadership;\n }\n};\n\nexport const RxDBLeaderElectionPlugin: RxPlugin = {\n name: 'leader-election',\n rxdb,\n prototypes,\n hooks: {\n preDestroyRxDatabase: {\n after: onDestroy\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;AAIA;AAKA;AASA;AAlBA;AACA;AACA;;AAkBA,IAAMA,qBAAyD,GAAG,IAAIC,OAAO,EAAE;AAC/E,IAAMC,mCAA6E,GAAG,IAAID,OAAO,EAAE;;AAGnG;AACA;AACA;AACA;AACO,SAASE,kCAAkC,CAACC,gBAAkC,EAAiB;EAClG,IAAIC,OAAO,GAAGH,mCAAmC,CAACI,GAAG,CAACF,gBAAgB,CAAC;EACvE,IAAI,CAACC,OAAO,EAAE;IACVA,OAAO,GAAG,IAAAE,sCAAoB,EAACH,gBAAgB,CAAC;IAChDF,mCAAmC,CAACM,GAAG,CAACJ,gBAA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AG,EAAE;IACLA,GAAG,CAACC,GAAG,EAAE;EACb;AACJ;AAEO,IAAMC,IAAI,GAAG,IAAI;AAAC;AAClB,IAAMC,UAAU,GAAG;EACtBC,UAAU,EAAE,oBAACC,KAAU,EAAK;IACxBA,KAAK,CAACd,aAAa,GAAGR,cAAc;IACpCsB,KAAK,CAACb,QAAQ,GAAGA,QAAQ;IACzBa,KAAK,CAACX,iBAAiB,GAAGA,iBAAiB;EAC/C;AACJ,CAAC;AAAC;AAEK,IAAMY,wBAAkC,GAAG;EAC9CpB,IAAI,EAAE,iBAAiB;EACvBgB,IAAI,EAAJA,IAAI;EACJC,UAAU,EAAVA,UAAU;EACVI,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEX;IACX;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/local-documents/local-documents-helper.js b/dist/lib/plugins/local-documents/local-documents-helper.js index 16d66093c0f..d2e35b14a7b 100644 --- a/dist/lib/plugins/local-documents/local-documents-helper.js +++ b/dist/lib/plugins/local-documents/local-documents-helper.js @@ -1,60 +1,57 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.RX_LOCAL_DOCUMENT_SCHEMA = void 0; +exports.RX_LOCAL_DOCUMENT_SCHEMA = exports.LOCAL_DOC_STATE_BY_PARENT_RESOLVED = exports.LOCAL_DOC_STATE_BY_PARENT = void 0; exports.closeStateByParent = closeStateByParent; exports.createLocalDocStateByParent = createLocalDocStateByParent; exports.createLocalDocumentStorageInstance = createLocalDocumentStorageInstance; exports.getCollectionLocalInstanceName = getCollectionLocalInstanceName; exports.getLocalDocStateByParent = getLocalDocStateByParent; -exports.removeLocalDocumentsStorageInstance = void 0; +exports.removeLocalDocumentsStorageInstance = removeLocalDocumentsStorageInstance; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _operators = require("rxjs/operators"); var _docCache = require("../../doc-cache"); +var _incrementalWrite = require("../../incremental-write"); var _rxError = require("../../rx-error"); var _rxSchemaHelper = require("../../rx-schema-helper"); var _rxStorageHelper = require("../../rx-storage-helper"); -var _util = require("../../util"); -var removeLocalDocumentsStorageInstance = function removeLocalDocumentsStorageInstance(storage, databaseName, collectionName) { - try { - var databaseInstanceToken = (0, _util.randomCouchString)(10); - return Promise.resolve(createLocalDocumentStorageInstance(databaseInstanceToken, storage, databaseName, collectionName, {}, false)).then(function (storageInstance) { - return Promise.resolve(storageInstance.remove()).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.removeLocalDocumentsStorageInstance = removeLocalDocumentsStorageInstance; +var _utils = require("../../plugins/utils"); +var _rxLocalDocument = require("./rx-local-document"); var LOCAL_DOC_STATE_BY_PARENT = new WeakMap(); +exports.LOCAL_DOC_STATE_BY_PARENT = LOCAL_DOC_STATE_BY_PARENT; +var LOCAL_DOC_STATE_BY_PARENT_RESOLVED = new WeakMap(); +exports.LOCAL_DOC_STATE_BY_PARENT_RESOLVED = LOCAL_DOC_STATE_BY_PARENT_RESOLVED; function createLocalDocStateByParent(parent) { var database = parent.database ? parent.database : parent; var collectionName = parent.database ? parent.name : ''; - var statePromise = function () { - try { - return Promise.resolve(createLocalDocumentStorageInstance(database.token, database.storage, database.name, collectionName, database.instanceCreationOptions, database.multiInstance)).then(function (storageInstance) { - storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(database, storageInstance, RX_LOCAL_DOCUMENT_SCHEMA); - var docCache = new _docCache.DocCache(); - - /** - * Update cached local documents on events. - */ - var sub = parent.$.pipe((0, _operators.filter)(function (cE) { - return cE.isLocal; - })).subscribe(function (cE) { - var doc = docCache.get(cE.documentId); - if (doc) { - doc._handleChangeEvent(cE); - } - }); - parent._subs.push(sub); - - /** - * Emit the changestream into the collections change stream - */ - return Promise.resolve(database.storageToken).then(function (databaseStorageToken) { - var subLocalDocs = storageInstance.changeStream().subscribe(function (eventBulk) { + var statePromise = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var storageInstance, docCache, incrementalWriteQueue, databaseStorageToken, subLocalDocs, state; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return createLocalDocumentStorageInstance(database.token, database.storage, database.name, collectionName, database.instanceCreationOptions, database.multiInstance); + case 2: + storageInstance = _context.sent; + storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(database, storageInstance, RX_LOCAL_DOCUMENT_SCHEMA); + docCache = new _docCache.DocumentCache('id', parent.$.pipe((0, _operators.filter)(function (cE) { + return cE.isLocal; + })), function (docData) { + return (0, _rxLocalDocument.createRxLocalDocument)(docData, parent); + }); + incrementalWriteQueue = new _incrementalWrite.IncrementalWriteQueue(storageInstance, 'id', function () {}, function () {}); + /** + * Emit the changestream into the collections change stream + */ + _context.next = 8; + return database.storageToken; + case 8: + databaseStorageToken = _context.sent; + subLocalDocs = storageInstance.changeStream().subscribe(function (eventBulk) { var changeEventBulk = { id: eventBulk.id, internal: false, @@ -70,18 +67,21 @@ function createLocalDocStateByParent(parent) { database.$emit(changeEventBulk); }); parent._subs.push(subLocalDocs); - return { + state = { database: database, parent: parent, storageInstance: storageInstance, - docCache: docCache + docCache: docCache, + incrementalWriteQueue: incrementalWriteQueue }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }(); + LOCAL_DOC_STATE_BY_PARENT_RESOLVED.set(parent, state); + return _context.abrupt("return", state); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))(); LOCAL_DOC_STATE_BY_PARENT.set(parent, statePromise); } function getLocalDocStateByParent(parent) { @@ -120,6 +120,30 @@ function closeStateByParent(parent) { }); } } +function removeLocalDocumentsStorageInstance(_x, _x2, _x3) { + return _removeLocalDocumentsStorageInstance.apply(this, arguments); +} +function _removeLocalDocumentsStorageInstance() { + _removeLocalDocumentsStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(storage, databaseName, collectionName) { + var databaseInstanceToken, storageInstance; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + databaseInstanceToken = (0, _utils.randomCouchString)(10); + _context2.next = 3; + return createLocalDocumentStorageInstance(databaseInstanceToken, storage, databaseName, collectionName, {}, false); + case 3: + storageInstance = _context2.sent; + _context2.next = 6; + return storageInstance.remove(); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _removeLocalDocumentsStorageInstance.apply(this, arguments); +} function getCollectionLocalInstanceName(collectionName) { return 'plugin-local-documents-' + collectionName; } diff --git a/dist/lib/plugins/local-documents/local-documents-helper.js.map b/dist/lib/plugins/local-documents/local-documents-helper.js.map index d02dc2cad4d..635d415f440 100644 --- a/dist/lib/plugins/local-documents/local-documents-helper.js.map +++ b/dist/lib/plugins/local-documents/local-documents-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"local-documents-helper.js","names":["removeLocalDocumentsStorageInstance","storage","databaseName","collectionName","databaseInstanceToken","randomCouchString","createLocalDocumentStorageInstance","storageInstance","remove","LOCAL_DOC_STATE_BY_PARENT","WeakMap","createLocalDocStateByParent","parent","database","name","statePromise","token","instanceCreationOptions","multiInstance","getWrappedStorageInstance","RX_LOCAL_DOCUMENT_SCHEMA","docCache","DocCache","sub","$","pipe","filter","cE","isLocal","subscribe","doc","get","documentId","_handleChangeEvent","_subs","push","storageToken","databaseStorageToken","subLocalDocs","changeStream","eventBulk","changeEventBulk","id","internal","undefined","events","map","ev","storageChangeEventToRxChangeEvent","databaseToken","checkpoint","context","$emit","set","getLocalDocStateByParent","newRxError","collection","createStorageInstance","getCollectionLocalInstanceName","schema","options","closeStateByParent","then","state","close","fillWithDefaultSettings","title","version","primaryKey","type","properties","maxLength","data","additionalProperties","required"],"sources":["../../../../src/plugins/local-documents/local-documents-helper.ts"],"sourcesContent":["import { filter } from 'rxjs/operators';\nimport { DocCache } from '../../doc-cache';\nimport { newRxError } from '../../rx-error';\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent\n} from '../../rx-storage-helper';\nimport type {\n LocalDocumentParent,\n LocalDocumentState,\n RxChangeEvent,\n RxChangeEventBulk,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxLocalDocument,\n RxLocalDocumentData,\n RxStorage\n} from '../../types';\nimport { randomCouchString } from '../../util';\n\nconst LOCAL_DOC_STATE_BY_PARENT: WeakMap> = new WeakMap();\n\n\nexport function createLocalDocStateByParent(parent: LocalDocumentParent): void {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n const statePromise = (async () => {\n let storageInstance = await createLocalDocumentStorageInstance(\n database.token,\n database.storage,\n database.name,\n collectionName,\n database.instanceCreationOptions,\n database.multiInstance\n );\n storageInstance = getWrappedStorageInstance(\n database,\n storageInstance,\n RX_LOCAL_DOCUMENT_SCHEMA\n );\n const docCache = new DocCache>();\n\n /**\n * Update cached local documents on events.\n */\n const sub = parent.$\n .pipe(\n filter(cE => (cE as RxChangeEvent).isLocal)\n )\n .subscribe((cE: RxChangeEvent) => {\n const doc = docCache.get(cE.documentId);\n if (doc) {\n doc._handleChangeEvent(cE);\n }\n });\n parent._subs.push(sub);\n\n /**\n * Emit the changestream into the collections change stream\n */\n const databaseStorageToken = await database.storageToken;\n const subLocalDocs = storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: parent.database ? parent.name : undefined,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n true,\n ev,\n parent.database ? parent as any : undefined\n )),\n databaseToken: database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n database.$emit(changeEventBulk);\n });\n parent._subs.push(subLocalDocs);\n\n return {\n database,\n parent,\n storageInstance,\n docCache\n };\n })();\n LOCAL_DOC_STATE_BY_PARENT.set(parent, statePromise);\n}\n\nexport function getLocalDocStateByParent(parent: LocalDocumentParent): Promise {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (!statePromise) {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n throw newRxError('LD8', {\n database: database.name,\n collection: collectionName\n });\n }\n return statePromise;\n}\n\n\nexport function createLocalDocumentStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n collectionName: string,\n instanceCreationOptions: any,\n multiInstance: boolean\n) {\n return storage.createStorageInstance({\n databaseInstanceToken,\n databaseName: databaseName,\n /**\n * Use a different collection name for the local documents instance\n * so that the local docs can be kept while deleting the normal instance\n * after migration.\n */\n collectionName: getCollectionLocalInstanceName(collectionName),\n schema: RX_LOCAL_DOCUMENT_SCHEMA,\n options: instanceCreationOptions,\n multiInstance\n });\n}\n\nexport function closeStateByParent(parent: LocalDocumentParent) {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (statePromise) {\n LOCAL_DOC_STATE_BY_PARENT.delete(parent);\n return statePromise.then(state => state.storageInstance.close());\n }\n}\n\nexport async function removeLocalDocumentsStorageInstance(\n storage: RxStorage,\n databaseName: string,\n collectionName: string\n) {\n const databaseInstanceToken = randomCouchString(10);\n const storageInstance = await createLocalDocumentStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n collectionName,\n {},\n false\n );\n await storageInstance.remove();\n}\n\n\nexport function getCollectionLocalInstanceName(collectionName: string): string {\n return 'plugin-local-documents-' + collectionName;\n}\n\nexport const RX_LOCAL_DOCUMENT_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n title: 'RxLocalDocument',\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 128\n },\n data: {\n type: 'object',\n additionalProperties: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,KAAK,EAAE;IAAA,EAAC;EACpE;AACJ;AAoBO,SAASN,8BAA8B,CAACvD,cAAsB,EAAU;EAC3E,OAAO,yBAAyB,GAAGA,cAAc;AACrD;AAEO,IAAMiB,wBAA2E,GAAG,IAAA6C,uCAAuB,EAAC;EAC/GC,KAAK,EAAE,iBAAiB;EACxBC,OAAO,EAAE,CAAC;EACVC,UAAU,EAAE,IAAI;EAChBC,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACR5B,EAAE,EAAE;MACA2B,IAAI,EAAE,QAAQ;MACdE,SAAS,EAAE;IACf,CAAC;IACDC,IAAI,EAAE;MACFH,IAAI,EAAE,QAAQ;MACdI,oBAAoB,EAAE;IAC1B;EACJ,CAAC;EACDC,QAAQ,EAAE,CACN,IAAI,EACJ,MAAM;AAEd,CAAC,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"local-documents-helper.js","names":["LOCAL_DOC_STATE_BY_PARENT","WeakMap","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","createLocalDocStateByParent","parent","database","collectionName","name","statePromise","createLocalDocumentStorageInstance","token","storage","instanceCreationOptions","multiInstance","storageInstance","getWrappedStorageInstance","RX_LOCAL_DOCUMENT_SCHEMA","docCache","DocumentCache","$","pipe","filter","cE","isLocal","docData","createRxLocalDocument","incrementalWriteQueue","IncrementalWriteQueue","storageToken","databaseStorageToken","subLocalDocs","changeStream","subscribe","eventBulk","changeEventBulk","id","internal","undefined","events","map","ev","storageChangeEventToRxChangeEvent","databaseToken","checkpoint","context","$emit","_subs","push","state","set","getLocalDocStateByParent","get","newRxError","collection","databaseInstanceToken","databaseName","createStorageInstance","getCollectionLocalInstanceName","schema","options","closeStateByParent","then","close","removeLocalDocumentsStorageInstance","randomCouchString","remove","fillWithDefaultSettings","title","version","primaryKey","type","properties","maxLength","data","additionalProperties","required"],"sources":["../../../../src/plugins/local-documents/local-documents-helper.ts"],"sourcesContent":["import { filter } from 'rxjs/operators';\nimport { DocumentCache } from '../../doc-cache';\nimport { IncrementalWriteQueue } from '../../incremental-write';\nimport { newRxError } from '../../rx-error';\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent\n} from '../../rx-storage-helper';\nimport type {\n LocalDocumentParent,\n LocalDocumentState,\n RxChangeEvent,\n RxChangeEventBulk,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxLocalDocumentData,\n RxStorage\n} from '../../types';\nimport { randomCouchString } from '../../plugins/utils';\nimport { createRxLocalDocument } from './rx-local-document';\n\nexport const LOCAL_DOC_STATE_BY_PARENT: WeakMap> = new WeakMap();\nexport const LOCAL_DOC_STATE_BY_PARENT_RESOLVED: WeakMap = new WeakMap();\n\n\nexport function createLocalDocStateByParent(parent: LocalDocumentParent): void {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n const statePromise = (async () => {\n let storageInstance = await createLocalDocumentStorageInstance(\n database.token,\n database.storage,\n database.name,\n collectionName,\n database.instanceCreationOptions,\n database.multiInstance\n );\n storageInstance = getWrappedStorageInstance(\n database,\n storageInstance,\n RX_LOCAL_DOCUMENT_SCHEMA\n );\n const docCache = new DocumentCache(\n 'id',\n parent.$.pipe(\n filter(cE => (cE as RxChangeEvent).isLocal)\n ),\n docData => createRxLocalDocument(docData, parent) as any\n );\n\n const incrementalWriteQueue = new IncrementalWriteQueue(\n storageInstance,\n 'id',\n () => { },\n () => { }\n );\n\n /**\n * Emit the changestream into the collections change stream\n */\n const databaseStorageToken = await database.storageToken;\n const subLocalDocs = storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: parent.database ? parent.name : undefined,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n true,\n ev,\n parent.database ? parent as any : undefined\n )),\n databaseToken: database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n database.$emit(changeEventBulk);\n });\n parent._subs.push(subLocalDocs);\n\n const state = {\n database,\n parent,\n storageInstance,\n docCache,\n incrementalWriteQueue\n };\n LOCAL_DOC_STATE_BY_PARENT_RESOLVED.set(parent, state);\n return state;\n })();\n LOCAL_DOC_STATE_BY_PARENT.set(parent, statePromise);\n}\n\nexport function getLocalDocStateByParent(parent: LocalDocumentParent): Promise {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (!statePromise) {\n const database: RxDatabase = parent.database ? parent.database : parent as any;\n const collectionName = parent.database ? parent.name : '';\n throw newRxError('LD8', {\n database: database.name,\n collection: collectionName\n });\n }\n return statePromise;\n}\n\n\nexport function createLocalDocumentStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n collectionName: string,\n instanceCreationOptions: any,\n multiInstance: boolean\n) {\n return storage.createStorageInstance({\n databaseInstanceToken,\n databaseName: databaseName,\n /**\n * Use a different collection name for the local documents instance\n * so that the local docs can be kept while deleting the normal instance\n * after migration.\n */\n collectionName: getCollectionLocalInstanceName(collectionName),\n schema: RX_LOCAL_DOCUMENT_SCHEMA,\n options: instanceCreationOptions,\n multiInstance\n });\n}\n\nexport function closeStateByParent(parent: LocalDocumentParent) {\n const statePromise = LOCAL_DOC_STATE_BY_PARENT.get(parent);\n if (statePromise) {\n LOCAL_DOC_STATE_BY_PARENT.delete(parent);\n return statePromise.then(state => state.storageInstance.close());\n }\n}\n\nexport async function removeLocalDocumentsStorageInstance(\n storage: RxStorage,\n databaseName: string,\n collectionName: string\n) {\n const databaseInstanceToken = randomCouchString(10);\n const storageInstance = await createLocalDocumentStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n collectionName,\n {},\n false\n );\n await storageInstance.remove();\n}\n\n\nexport function getCollectionLocalInstanceName(collectionName: string): string {\n return 'plugin-local-documents-' + collectionName;\n}\n\nexport const RX_LOCAL_DOCUMENT_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n title: 'RxLocalDocument',\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 128\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n required: [\n 'id',\n 'data'\n ]\n});\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AAeA;AACA;AAEO,IAAMA,yBAAoF,GAAG,IAAIC,OAAO,EAAE;AAAC;AAC3G,IAAMC,kCAAoF,GAAG,IAAID,OAAO,EAAE;AAAC;AAG3G,SAASE,2BAA2B,CAACC,MAA2B,EAAQ;EAC3E,IAAMC,QAAoB,GAAGD,MAAM,CAACC,QAAQ,GAAGD,MAAM,CAACC,QAAQ,GAAGD,MAAa;EAC9E,IAAME,cAAc,GAAGF,MAAM,CAACC,QAAQ,GAAGD,MAAM,CAACG,IAAI,GAAG,EAAE;EACzD,IAAMC,YAAY,GAAG,8EAAC;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OACUC,kCAAkC,CAC1DJ,QAAQ,CAACK,KAAK,EACdL,QAAQ,CAACM,OAAO,EAChBN,QAAQ,CAACE,IAAI,EACbD,cAAc,EACdD,QAAQ,CAACO,uBAAuB,EAChCP,QAAQ,CAACQ,aAAa,CACzB;QAAA;UAPGC,eAAe;UAQnBA,eAAe,GAAG,IAAAC,0CAAyB,EACvCV,QAAQ,EACRS,eAAe,EACfE,wBAAwB,CAC3B;UACKC,QAAQ,GAAG,IAAIC,uBAAa,CAC9B,IAAI,EACJd,MAAM,CAACe,CAAC,CAACC,IAAI,CACT,IAAAC,iBAAM,EAAC,UAAAC,EAAE;YAAA,OAAKA,EAAE,CAAwBC,OAAO;UAAA,EAAC,CACnD,EACD,UAAAC,OAAO;YAAA,OAAI,IAAAC,sCAAqB,EAACD,OAAO,EAAEpB,MAAM,CAAC;UAAA,CAAO,CAC3D;UAEKsB,qBAAqB,GAAG,IAAIC,uCAAqB,CACnDb,eAAe,EACf,IAAI,EACJ,YAAM,CAAE,CA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C,YAAoB,EACpBjD,cAAsB;IAAA;IAAA;MAAA;QAAA;UAEhBgD,qBAAqB,GAAG,IAAAU,wBAAiB,EAAC,EAAE,CAAC;UAAA;UAAA,OACrBvD,kCAAkC,CAC5D6C,qBAAqB,EACrB3C,OAAO,EACP4C,YAAY,EACZjD,cAAc,EACd,CAAC,CAAC,EACF,KAAK,CACR;QAAA;UAPKQ,eAAe;UAAA;UAAA,OAQfA,eAAe,CAACmD,MAAM,EAAE;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACjC;EAAA;AAAA;AAGM,SAASR,8BAA8B,CAACnD,cAAsB,EAAU;EAC3E,OAAO,yBAAyB,GAAGA,cAAc;AACrD;AAEO,IAAMU,wBAA2E,GAAG,IAAAkD,uCAAuB,EAAC;EAC/GC,KAAK,EAAE,iBAAiB;EACxBC,OAAO,EAAE,CAAC;EACVC,UAAU,EAAE,IAAI;EAChBC,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRpC,EAAE,EAAE;MACAmC,IAAI,EAAE,QAAQ;MACdE,SAAS,EAAE;IACf,CAAC;IACDC,IAAI,EAAE;MACFH,IAAI,EAAE,QAAQ;MACdI,oBAAoB,EAAE;IAC1B;EACJ,CAAC;EACDC,QAAQ,EAAE,CACN,IAAI,EACJ,MAAM;AAEd,CAAC,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/local-documents/local-documents.js b/dist/lib/plugins/local-documents/local-documents.js index 3c7a6d0b03c..5fcc4694e48 100644 --- a/dist/lib/plugins/local-documents/local-documents.js +++ b/dist/lib/plugins/local-documents/local-documents.js @@ -1,136 +1,189 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.getLocal = void 0; +exports.getLocal = getLocal; exports.getLocal$ = getLocal$; -exports.insertLocal = void 0; +exports.insertLocal = insertLocal; exports.upsertLocal = upsertLocal; -var _util = require("../../util"); +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utils = require("../../plugins/utils"); var _operators = require("rxjs/operators"); -var _rxLocalDocument = require("./rx-local-document"); var _localDocumentsHelper = require("./local-documents-helper"); var _rxStorageHelper = require("../../rx-storage-helper"); -var getLocal = function getLocal(id) { - try { - var _this3 = this; - return Promise.resolve((0, _localDocumentsHelper.getLocalDocStateByParent)(_this3)).then(function (state) { - var docCache = state.docCache; - - // check in doc-cache - var found = docCache.get(id); - return found ? Promise.resolve(found) : (0, _rxStorageHelper.getSingleDocument)(state.storageInstance, id).then(function (docData) { - if (!docData) { - return null; - } - var doc = (0, _rxLocalDocument.createRxLocalDocument)(id, docData, _this3, state); - return doc; - })["catch"](function () { - return null; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.getLocal = getLocal; /** * save the local-document-data * throws if already exists */ -var insertLocal = function insertLocal(id, data) { - try { - var _this = this; - return Promise.resolve((0, _localDocumentsHelper.getLocalDocStateByParent)(_this)).then(function (state) { - // create new one - var docData = { - id: id, - data: data, - _deleted: false, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }; - return (0, _rxStorageHelper.writeSingle)(state.storageInstance, { - document: docData - }, 'local-document-insert').then(function (res) { - docData = (0, _util.flatClone)(docData); - docData._rev = res._rev; - var newDoc = (0, _rxLocalDocument.createRxLocalDocument)(id, docData, _this, state); - return newDoc; - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; +function insertLocal(_x, _x2) { + return _insertLocal.apply(this, arguments); +} /** * save the local-document-data * overwrites existing if exists */ -exports.insertLocal = insertLocal; +function _insertLocal() { + _insertLocal = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(id, data) { + var state, docData; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _localDocumentsHelper.getLocalDocStateByParent)(this); + case 2: + state = _context3.sent; + // create new one + docData = { + id: id, + data: data, + _deleted: false, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }; + return _context3.abrupt("return", (0, _rxStorageHelper.writeSingle)(state.storageInstance, { + document: docData + }, 'local-document-insert').then(function (newDocData) { + return state.docCache.getCachedRxDocument(newDocData); + })); + case 5: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + return _insertLocal.apply(this, arguments); +} function upsertLocal(id, data) { - var _this2 = this; + var _this = this; return this.getLocal(id).then(function (existing) { if (!existing) { // create new one - var docPromise = _this2.insertLocal(id, data); + var docPromise = _this.insertLocal(id, data); return docPromise; } else { // update existing - return existing.atomicUpdate(function () { + return existing.incrementalModify(function () { return data; - }).then(function () { - return existing; }); } }); } -function getLocal$(id) { - var _this4 = this; - return this.$.pipe((0, _operators.startWith)(null), (0, _operators.mergeMap)(function (cE) { - try { - if (cE) { - return Promise.resolve({ - changeEvent: cE - }); - } else { - return Promise.resolve(_this4.getLocal(id)).then(function (doc) { - return { - doc: doc - }; - }); +function getLocal(_x3) { + return _getLocal.apply(this, arguments); +} +function _getLocal() { + _getLocal = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(id) { + var state, docCache, found; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return (0, _localDocumentsHelper.getLocalDocStateByParent)(this); + case 2: + state = _context4.sent; + docCache = state.docCache; // check in doc-cache + found = docCache.getLatestDocumentDataIfExists(id); + if (!found) { + _context4.next = 7; + break; + } + return _context4.abrupt("return", Promise.resolve(docCache.getCachedRxDocument(found))); + case 7: + return _context4.abrupt("return", (0, _rxStorageHelper.getSingleDocument)(state.storageInstance, id).then(function (docData) { + if (!docData) { + return null; + } + return state.docCache.getCachedRxDocument(docData); + })); + case 8: + case "end": + return _context4.stop(); } - } catch (e) { - return Promise.reject(e); - } - }), (0, _operators.mergeMap)(function (changeEventOrDoc) { - try { - if (changeEventOrDoc.changeEvent) { - var cE = changeEventOrDoc.changeEvent; - if (!cE.isLocal || cE.documentId !== id) { - return Promise.resolve({ - use: false - }); - } else { - return Promise.resolve(_this4.getLocal(id)).then(function (doc) { - return { + }, _callee4, this); + })); + return _getLocal.apply(this, arguments); +} +function getLocal$(id) { + var _this2 = this; + return this.$.pipe((0, _operators.startWith)(null), (0, _operators.mergeMap)( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(cE) { + var doc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!cE) { + _context.next = 4; + break; + } + return _context.abrupt("return", { + changeEvent: cE + }); + case 4: + _context.next = 6; + return _this2.getLocal(id); + case 6: + doc = _context.sent; + return _context.abrupt("return", { + doc: doc + }); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref.apply(this, arguments); + }; + }()), (0, _operators.mergeMap)( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(changeEventOrDoc) { + var cE, doc; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!changeEventOrDoc.changeEvent) { + _context2.next = 12; + break; + } + cE = changeEventOrDoc.changeEvent; + if (!(!cE.isLocal || cE.documentId !== id)) { + _context2.next = 6; + break; + } + return _context2.abrupt("return", { + use: false + }); + case 6: + _context2.next = 8; + return _this2.getLocal(id); + case 8: + doc = _context2.sent; + return _context2.abrupt("return", { use: true, doc: doc - }; - }); + }); + case 10: + _context2.next = 13; + break; + case 12: + return _context2.abrupt("return", { + use: true, + doc: changeEventOrDoc.doc + }); + case 13: + case "end": + return _context2.stop(); } - } else { - return Promise.resolve({ - use: true, - doc: changeEventOrDoc.doc - }); - } - } catch (e) { - return Promise.reject(e); - } - }), (0, _operators.filter)(function (filterFlagged) { + }, _callee2); + })); + return function (_x5) { + return _ref2.apply(this, arguments); + }; + }()), (0, _operators.filter)(function (filterFlagged) { return filterFlagged.use; }), (0, _operators.map)(function (filterFlagged) { return filterFlagged.doc; diff --git a/dist/lib/plugins/local-documents/local-documents.js.map b/dist/lib/plugins/local-documents/local-documents.js.map index d697a319d2c..64c3b945e57 100644 --- a/dist/lib/plugins/local-documents/local-documents.js.map +++ b/dist/lib/plugins/local-documents/local-documents.js.map @@ -1 +1 @@ -{"version":3,"file":"local-documents.js","names":["getLocal","id","getLocalDocStateByParent","state","docCache","found","get","Promise","resolve","getSingleDocument","storageInstance","then","docData","doc","createRxLocalDocument","insertLocal","data","_deleted","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","writeSingle","document","res","flatClone","newDoc","upsertLocal","existing","docPromise","atomicUpdate","getLocal$","$","pipe","startWith","mergeMap","cE","changeEvent","changeEventOrDoc","isLocal","documentId","use","filter","filterFlagged","map"],"sources":["../../../../src/plugins/local-documents/local-documents.ts"],"sourcesContent":["import {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta\n} from '../../util';\n\nimport type {\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\n\nimport {\n filter,\n map,\n startWith,\n mergeMap\n} from 'rxjs/operators';\nimport { Observable } from 'rxjs';\n\nimport { createRxLocalDocument } from './rx-local-document';\nimport { getLocalDocStateByParent } from './local-documents-helper';\nimport { getSingleDocument, writeSingle } from '../../rx-storage-helper';\n\n\n\n/**\n * save the local-document-data\n * throws if already exists\n */\nexport async function insertLocal = any>(\n this: RxDatabase | RxCollection,\n id: string,\n data: DocData\n): Promise> {\n const state = await getLocalDocStateByParent(this);\n\n // create new one\n let docData: RxDocumentWriteData> = {\n id: id,\n data,\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n return writeSingle(\n state.storageInstance,\n {\n document: docData\n },\n 'local-document-insert'\n ).then(res => {\n docData = flatClone(docData);\n docData._rev = res._rev;\n const newDoc = createRxLocalDocument(id, docData as any, this, state);\n return newDoc as any;\n });\n}\n\n/**\n * save the local-document-data\n * overwrites existing if exists\n */\nexport function upsertLocal = any>(\n this: any,\n id: string,\n data: DocData\n): Promise> {\n return this.getLocal(id)\n .then((existing: RxDocument) => {\n if (!existing) {\n // create new one\n const docPromise = this.insertLocal(id, data);\n return docPromise;\n } else {\n // update existing\n return existing.atomicUpdate(() => {\n return data;\n }).then(() => existing);\n }\n });\n}\n\nexport async function getLocal(this: any, id: string): Promise | null> {\n const state = await getLocalDocStateByParent(this);\n const docCache = state.docCache;\n\n // check in doc-cache\n const found = docCache.get(id);\n if (found) {\n return Promise.resolve(found as any);\n }\n\n // if not found, check in storage instance\n return getSingleDocument(state.storageInstance, id)\n .then((docData) => {\n if (!docData) {\n return null;\n }\n const doc = createRxLocalDocument(id, docData, this, state);\n return doc as any;\n })\n .catch(() => null);\n}\n\nexport function getLocal$(this: RxCollection, id: string): Observable | null> {\n return this.$.pipe(\n startWith(null),\n mergeMap(async (cE: RxChangeEvent | null) => {\n if (cE) {\n return {\n changeEvent: cE\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n doc: doc\n };\n }\n }),\n mergeMap(async (changeEventOrDoc) => {\n if (changeEventOrDoc.changeEvent) {\n const cE = changeEventOrDoc.changeEvent;\n if (!cE.isLocal || cE.documentId !== id) {\n return {\n use: false\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n use: true,\n doc: doc\n };\n }\n } else {\n return {\n use: true,\n doc: changeEventOrDoc.doc\n };\n }\n }),\n filter(filterFlagged => filterFlagged.use),\n map(filterFlagged => {\n return filterFlagged.doc as any;\n })\n );\n}\n"],"mappings":";;;;;;;;;AAAA;AAgBA;AAQA;AACA;AACA;AAAyE,IA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C9B,IAAMD,EAAE,GAAGE,gBAAgB,CAACD,WAAW;QACvC,IAAI,CAACD,EAAE,CAACG,OAAO,IAAIH,EAAE,CAACI,UAAU,KAAKxC,EAAE,EAAE;UACrC,uBAAO;YACHyC,GAAG,EAAE;UACT,CAAC;QACL,CAAC,MAAM;UAAA,uBACe,MAAI,CAAC1C,QAAQ,CAACC,EAAE,CAAC,iBAA7BY,GAAG;YACT,OAAO;cACH6B,GAAG,EAAE,IAAI;cACT7B,GAAG,EAAEA;YACT,CAAC;UAAC;QACN;MACJ,CAAC,MAAM;QACH,uBAAO;UACH6B,GAAG,EAAE,IAAI;UACT7B,GAAG,EAAE0B,gBAAgB,CAAC1B;QAC1B,CAAC;MACL;IACJ,CAAC;MAAA;IAAA;EAAA,EAAC,EACF,IAAA8B,iBAAM,EAAC,UAAAC,aAAa;IAAA,OAAIA,aAAa,CAACF,GAAG;EAAA,EAAC,EAC1C,IAAAG,cAAG,EAAC,UAAAD,aAAa,EAAI;IACjB,OAAOA,aAAa,CAAC/B,GAAG;EAC5B,CAAC,CAAC,CACL;AACL"} \ No newline at end of file +{"version":3,"file":"local-documents.js","names":["insertLocal","id","data","getLocalDocStateByParent","state","docData","_deleted","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","writeSingle","storageInstance","document","then","newDocData","docCache","getCachedRxDocument","upsertLocal","getLocal","existing","docPromise","incrementalModify","found","getLatestDocumentDataIfExists","Promise","resolve","getSingleDocument","getLocal$","$","pipe","startWith","mergeMap","cE","changeEvent","doc","changeEventOrDoc","isLocal","documentId","use","filter","filterFlagged","map"],"sources":["../../../../src/plugins/local-documents/local-documents.ts"],"sourcesContent":["import {\n getDefaultRevision,\n getDefaultRxDocumentMeta\n} from '../../plugins/utils';\n\nimport type {\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\n\nimport {\n filter,\n map,\n startWith,\n mergeMap\n} from 'rxjs/operators';\nimport { Observable } from 'rxjs';\n\nimport { getLocalDocStateByParent } from './local-documents-helper';\nimport { getSingleDocument, writeSingle } from '../../rx-storage-helper';\n\n\n\n/**\n * save the local-document-data\n * throws if already exists\n */\nexport async function insertLocal = any>(\n this: RxDatabase | RxCollection,\n id: string,\n data: DocData\n): Promise> {\n const state = await getLocalDocStateByParent(this);\n\n // create new one\n const docData: RxDocumentWriteData> = {\n id: id,\n data,\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n return writeSingle(\n state.storageInstance,\n {\n document: docData\n },\n 'local-document-insert'\n ).then(newDocData => state.docCache.getCachedRxDocument(newDocData) as any);\n}\n\n/**\n * save the local-document-data\n * overwrites existing if exists\n */\nexport function upsertLocal = any>(\n this: any,\n id: string,\n data: DocData\n): Promise> {\n return this.getLocal(id)\n .then((existing: RxDocument) => {\n if (!existing) {\n // create new one\n const docPromise = this.insertLocal(id, data);\n return docPromise;\n } else {\n // update existing\n return existing.incrementalModify(() => {\n return data;\n });\n }\n });\n}\n\nexport async function getLocal(this: any, id: string): Promise | null> {\n const state = await getLocalDocStateByParent(this);\n const docCache = state.docCache;\n\n // check in doc-cache\n const found = docCache.getLatestDocumentDataIfExists(id);\n if (found) {\n return Promise.resolve(\n docCache.getCachedRxDocument(found) as any\n );\n }\n\n // if not found, check in storage instance\n return getSingleDocument(state.storageInstance, id)\n .then((docData) => {\n if (!docData) {\n return null;\n }\n return state.docCache.getCachedRxDocument(docData) as any;\n });\n}\n\nexport function getLocal$(this: RxCollection, id: string): Observable | null> {\n return this.$.pipe(\n startWith(null),\n mergeMap(async (cE: RxChangeEvent | null) => {\n if (cE) {\n return {\n changeEvent: cE\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n doc: doc\n };\n }\n }),\n mergeMap(async (changeEventOrDoc) => {\n if (changeEventOrDoc.changeEvent) {\n const cE = changeEventOrDoc.changeEvent;\n if (!cE.isLocal || cE.documentId !== id) {\n return {\n use: false\n };\n } else {\n const doc = await this.getLocal(id);\n return {\n use: true,\n doc: doc\n };\n }\n } else {\n return {\n use: true,\n doc: changeEventOrDoc.doc\n };\n }\n }),\n filter(filterFlagged => filterFlagged.use),\n map(filterFlagged => {\n return filterFlagged.doc as any;\n })\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAeA;AAQA;AACA;AAIA;AACA;AACA;AACA;AAHA,SAIsBA,WAAW;EAAA;AAAA;AA0BjC;AACA;AACA;AACA;AAHA;EAAA,6FA1BO,kBAEHC,EAAU,EACVC,IAAa;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEO,IAAAC,8CAAwB,EAAC,IAAI,CAAC;QAAA;UAA5CC,KAAK;UAEX;UACMC,OAA0D,GAAG;YAC/DJ,EAAE,EAAEA,EAAE;YACNC,IAAI,EAAJA,IAAI;YACJI,QAAQ,EAAE,KAAK;YACfC,KAAK,EAAE,IAAAC,+BAAwB,GAAE;YACjCC,IAAI,EAAE,IAAAC,yBAAkB,GAAE;YAC1BC,YAAY,EAAE,CAAC;UACnB,CAAC;UAAA,kCAEM,IAAAC,4BAAW,EACdR,KAAK,CAACS,eAAe,EACrB;YACIC,QAAQ,EAAET;UACd,CAAC,EACD,uBAAuB,CAC1B,CAACU,IAAI,CAAC,UAAAC,UAAU;YAAA,OAAIZ,KAAK,CAACa,QAAQ,CAACC,mBAAmB,CAACF,UAAU,CAAC;UAAA,CAAO,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAC9E;EAAA;AAAA;AAMM,SAASG,WAAW,CAEvBlB,EAAU,EACVC,IAAa,EACoB;EAAA;EACjC,OAAO,IAAI,CAACkB,QAAQ,CAACnB,EAAE,CAAC,CACnBc,IAAI,CAAC,UAACM,QAAoB,EAAK;IAC5B,IAAI,CAACA,QAAQ,EAAE;MACX;MACA,IAAMC,UAAU,GAAG,KAAI,CAACtB,WAAW,CAACC,EAAE,EAAEC,IAAI,CAAC;MAC7C,O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;cACHA,GAAG,EAAEA;YACT,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CAER;IAAA;MAAA;IAAA;EAAA,IAAC,EACF,IAAAH,mBAAQ;IAAA,0FAAC,kBAAOI,gBAAgB;MAAA;MAAA;QAAA;UAAA;YAAA,KACxBA,gBAAgB,CAACF,WAAW;cAAA;cAAA;YAAA;YACtBD,EAAE,GAAGG,gBAAgB,CAACF,WAAW;YAAA,MACnC,CAACD,EAAE,CAACI,OAAO,IAAIJ,EAAE,CAACK,UAAU,KAAKtC,EAAE;cAAA;cAAA;YAAA;YAAA,kCAC5B;cACHuC,GAAG,EAAE;YACT,CAAC;UAAA;YAAA;YAAA,OAEiB,MAAI,CAACpB,QAAQ,CAACnB,EAAE,CAAC;UAAA;YAA7BmC,GAAG;YAAA,kCACF;cACHI,GAAG,EAAE,IAAI;cACTJ,GAAG,EAAEA;YACT,CAAC;UAAA;YAAA;YAAA;UAAA;YAAA,kCAGE;cACHI,GAAG,EAAE,IAAI;cACTJ,GAAG,EAAEC,gBAAgB,CAACD;YAC1B,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CAER;IAAA;MAAA;IAAA;EAAA,IAAC,EACF,IAAAK,iBAAM,EAAC,UAAAC,aAAa;IAAA,OAAIA,aAAa,CAACF,GAAG;EAAA,EAAC,EAC1C,IAAAG,cAAG,EAAC,UAAAD,aAAa,EAAI;IACjB,OAAOA,aAAa,CAACN,GAAG;EAC5B,CAAC,CAAC,CACL;AACL"} \ No newline at end of file diff --git a/dist/lib/plugins/local-documents/rx-local-document.js b/dist/lib/plugins/local-documents/rx-local-document.js index 8ad4b41e6f1..903aa179ef1 100644 --- a/dist/lib/plugins/local-documents/rx-local-document.js +++ b/dist/lib/plugins/local-documents/rx-local-document.js @@ -5,185 +5,27 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.createRxLocalDocument = createRxLocalDocument; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _objectPath = _interopRequireDefault(require("object-path")); var _operators = require("rxjs/operators"); var _overwritable = require("../../overwritable"); +var _rxChangeEvent = require("../../rx-change-event"); var _rxDocument = require("../../rx-document"); var _rxError = require("../../rx-error"); var _rxStorageHelper = require("../../rx-storage-helper"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _localDocumentsHelper = require("./local-documents-helper"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} var RxDocumentParent = (0, _rxDocument.createRxDocumentConstructor)(); var RxLocalDocumentClass = /*#__PURE__*/function (_RxDocumentParent) { (0, _inheritsLoose2["default"])(RxLocalDocumentClass, _RxDocumentParent); - function RxLocalDocumentClass(id, jsonData, parent, state) { - var _this; - _this = _RxDocumentParent.call(this, null, jsonData) || this; - _this.id = id; - _this.parent = parent; - _this.state = state; - return _this; + function RxLocalDocumentClass(id, jsonData, parent) { + var _this2; + _this2 = _RxDocumentParent.call(this, null, jsonData) || this; + _this2.id = id; + _this2.parent = parent; + return _this2; } return RxLocalDocumentClass; }(RxDocumentParent); @@ -194,22 +36,6 @@ var RxLocalDocumentPrototype = { // // overwrites // - _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) { - return; - } - switch (changeEvent.operation) { - case 'UPDATE': - this._dataSync$.next(changeEvent.documentData); - break; - case 'DELETE': - // remove from docCache to assure new upserted RxDocuments will be a new instance - var docCache = this.state.docCache; - docCache["delete"](this.primary); - this._dataSync$.next(changeEvent.documentData); - break; - } - }, get allAttachments$() { // this is overwritten here because we cannot re-set getters on the prototype throw (0, _rxError.newRxError)('LD1', { @@ -223,10 +49,22 @@ var RxLocalDocumentPrototype = { return this.id; }, get $() { - return this._dataSync$.asObservable(); + var _this3 = this; + var _this = this; + return _this.parent.$.pipe((0, _operators.filter)(function (changeEvent) { + return changeEvent.isLocal; + }), (0, _operators.filter)(function (changeEvent) { + return changeEvent.documentId === _this3.primary; + }), (0, _operators.map)(function (changeEvent) { + return (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + }), (0, _operators.startWith)(this._data), (0, _operators.distinctUntilChanged)(function (prev, curr) { + return prev._rev === curr._rev; + }), (0, _operators.shareReplay)(_utils.RXJS_SHARE_REPLAY_DEFAULTS)); }, - $emit: function $emit(changeEvent) { - return this.parent.$emit(changeEvent); + getLatest: function getLatest() { + var state = (0, _utils.getFromMapOrThrow)(_localDocumentsHelper.LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent); + var latestDocData = state.docCache.getLatestDocumentData(this.primary); + return state.docCache.getCachedRxDocument(latestDocData); }, get: function get(objPath) { objPath = 'data.' + objPath; @@ -244,123 +82,143 @@ var RxLocalDocumentPrototype = { }, get$: function get$(objPath) { objPath = 'data.' + objPath; - if (objPath.includes('.item.')) { - throw (0, _rxError.newRxError)('LD3', { - objPath: objPath - }); - } - if (objPath === this.primaryPath) { - throw (0, _rxError.newRxError)('LD4'); + if (_overwritable.overwritable.isDevMode()) { + if (objPath.includes('.item.')) { + throw (0, _rxError.newRxError)('LD3', { + objPath: objPath + }); + } + if (objPath === this.primaryPath) { + throw (0, _rxError.newRxError)('LD4'); + } } - return this._dataSync$.pipe((0, _operators.map)(function (data) { + return this.$.pipe((0, _operators.map)(function (data) { return _objectPath["default"].get(data, objPath); }), (0, _operators.distinctUntilChanged)()); }, - atomicUpdate: function atomicUpdate(mutationFunction) { - var _this2 = this; - return new Promise(function (res, rej) { - _this2._atomicQueue = _this2._atomicQueue.then(function () { - try { - var _temp3 = function _temp3(_result2) { - if (_exit) return _result2; - res(_this2); - }; - var _exit = false; - var done = false; - // we need a hacky while loop to stay incide the chain-link of _atomicQueue - // while still having the option to run a retry on conflicts - var _temp2 = _for(function () { - return !_exit && !done; - }, void 0, function () { - var oldDocData = _this2._dataSync$.getValue(); - return Promise.resolve(mutationFunction((0, _util.clone)(oldDocData.data), _this2)).then(function (newData) { - var _temp = _catch(function () { - // always await because mutationFunction might be async - - var newDocData = (0, _util.flatClone)(oldDocData); - newDocData.data = newData; - return Promise.resolve(_this2._saveData(newDocData, oldDocData)).then(function () { - done = true; - }); - }, function (err) { - /** - * conflicts cannot happen by just using RxDB in one process - * There are two ways they still can appear which is - * replication and multi-tab usage - * Because atomicUpdate has a mutation function, - * we can just re-run the mutation until there is no conflict - */ - var isConflict = (0, _rxError.isBulkWriteConflictError)(err); - if (isConflict) {} else { - rej(err); - _exit = true; - } - }); - if (_temp && _temp.then) return _temp.then(function () {}); - }); - }); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); + incrementalModify: function () { + var _incrementalModify = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(mutationFunction) { + var _this4 = this; + var state; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, _localDocumentsHelper.getLocalDocStateByParent)(this.parent); + case 2: + state = _context2.sent; + return _context2.abrupt("return", state.incrementalWriteQueue.addWrite(this._data, /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(docData) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return mutationFunction(docData.data, _this4); + case 2: + docData.data = _context.sent; + return _context.abrupt("return", docData); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x2) { + return _ref.apply(this, arguments); + }; + }()).then(function (result) { + return state.docCache.getCachedRxDocument(result); + })); + case 4: + case "end": + return _context2.stop(); } - }); - }); - }, - atomicPatch: function atomicPatch(patch) { - return this.atomicUpdate(function (docData) { - Object.entries(patch).forEach(function (_ref) { - var k = _ref[0], - v = _ref[1]; + }, _callee2, this); + })); + function incrementalModify(_x) { + return _incrementalModify.apply(this, arguments); + } + return incrementalModify; + }(), + incrementalPatch: function incrementalPatch(patch) { + return this.incrementalModify(function (docData) { + Object.entries(patch).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; docData[k] = v; }); return docData; }); }, - _saveData: function _saveData(newData) { - try { - var _this3 = this; - return Promise.resolve((0, _localDocumentsHelper.getLocalDocStateByParent)(_this3.parent)).then(function (state) { - var oldData = _this3._dataSync$.getValue(); - newData.id = _this3.id; - return state.storageInstance.bulkWrite([{ - previous: oldData, - document: newData - }], 'local-document-save-data').then(function (res) { - var docResult = res.success[newData.id]; - if (!docResult) { - throw (0, _util.getFromObjectOrThrow)(res.error, newData.id); - } - newData = (0, _util.flatClone)(newData); - newData._rev = docResult._rev; - }); - }); - } catch (e) { - return Promise.reject(e); + _saveData: function () { + var _saveData2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(newData) { + var state, oldData; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _localDocumentsHelper.getLocalDocStateByParent)(this.parent); + case 2: + state = _context3.sent; + oldData = this._data; + newData.id = this.id; + return _context3.abrupt("return", state.storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }], 'local-document-save-data').then(function (res) { + var docResult = res.success[newData.id]; + if (!docResult) { + throw (0, _utils.getFromObjectOrThrow)(res.error, newData.id); + } + newData = (0, _utils.flatClone)(newData); + newData._rev = docResult._rev; + })); + case 6: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function _saveData(_x3) { + return _saveData2.apply(this, arguments); } - }, - remove: function remove() { - try { - var _this4 = this; - return Promise.resolve((0, _localDocumentsHelper.getLocalDocStateByParent)(_this4.parent)).then(function (state) { - var writeData = { - id: _this4.id, - data: {}, - _deleted: true, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }; - return (0, _rxStorageHelper.writeSingle)(state.storageInstance, { - previous: _this4._data, - document: writeData - }, 'local-document-remove').then(function () { - _this4.state.docCache["delete"](_this4.id); - }); - }); - } catch (e) { - return Promise.reject(e); + return _saveData; + }(), + remove: function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var state, writeData; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return (0, _localDocumentsHelper.getLocalDocStateByParent)(this.parent); + case 2: + state = _context4.sent; + writeData = { + id: this._data.id, + data: {}, + _deleted: true, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }; + return _context4.abrupt("return", (0, _rxStorageHelper.writeSingle)(state.storageInstance, { + previous: this._data, + document: writeData + }, 'local-document-remove').then(function (writeResult) { + return state.docCache.getCachedRxDocument(writeResult); + })); + case 5: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function remove() { + return _remove.apply(this, arguments); } - } + return remove; + }() }; var INIT_DONE = false; var _init = function _init() { @@ -391,11 +249,11 @@ var _init = function _init() { return RxLocalDocumentPrototype[k] = getThrowingFun(k); }); }; -function createRxLocalDocument(id, data, parent, state) { +function createRxLocalDocument(data, parent) { _init(); - var newDoc = new RxLocalDocumentClass(id, data, parent, state); - newDoc.__proto__ = RxLocalDocumentPrototype; - state.docCache.set(id, newDoc); + var newDoc = new RxLocalDocumentClass(data.id, data, parent); + Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype); + newDoc.prototype = RxLocalDocumentPrototype; return newDoc; } //# sourceMappingURL=rx-local-document.js.map \ No newline at end of file diff --git a/dist/lib/plugins/local-documents/rx-local-document.js.map b/dist/lib/plugins/local-documents/rx-local-document.js.map index df932d31cee..a94c2761989 100644 --- a/dist/lib/plugins/local-documents/rx-local-document.js.map +++ b/dist/lib/plugins/local-documents/rx-local-document.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-local-document.js","names":["body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","RxDocumentParent","createRxDocumentConstructor","RxLocalDocumentClass","id","jsonData","parent","RxLocalDocumentPrototype","isLocal","_handleChangeEvent","changeEvent","documentId","primary","operation","_dataSync$","next","documentData","docCache","allAttachments$","newRxError","document","primaryPath","$","asObservable","$emit","get","objPath","_data","undefined","newRxTypeError","valueObj","objectPath","overwritable","deepFreezeWhenDevMode","get$","includes","pipe","map","data","distinctUntilChanged","atomicUpdate","mutationFunction","Promise","res","rej","_atomicQueue","done","oldDocData","getValue","clone","newData","newDocData","flatClone","_saveData","err","isConflict","isBulkWriteConflictError","atomicPatch","patch","docData","Object","entries","forEach","k","getLocalDocStateByParent","oldData","storageInstance","bulkWrite","previous","docResult","success","getFromObjectOrThrow","error","_rev","remove","writeData","_deleted","_meta","getDefaultRxDocumentMeta","getDefaultRevision","_attachments","writeSingle","INIT_DONE","_init","docBaseProto","basePrototype","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","__proto__","set"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { distinctUntilChanged, map } from 'rxjs/operators';\nimport { overwritable } from '../../overwritable';\nimport { basePrototype, createRxDocumentConstructor } from '../../rx-document';\nimport { isBulkWriteConflictError, newRxError, newRxTypeError } from '../../rx-error';\nimport { writeSingle } from '../../rx-storage-helper';\nimport type {\n LocalDocumentAtomicUpdateFunction,\n LocalDocumentState,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\nimport {\n clone,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromObjectOrThrow\n} from '../../util';\nimport { getLocalDocStateByParent } from './local-documents-helper';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase,\n public readonly state: LocalDocumentState\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n\n _handleChangeEvent(\n this: any,\n changeEvent: RxChangeEvent\n ) {\n if (changeEvent.documentId !== this.primary) {\n return;\n }\n switch (changeEvent.operation) {\n case 'UPDATE':\n this._dataSync$.next(changeEvent.documentData);\n break;\n case 'DELETE':\n // remove from docCache to assure new upserted RxDocuments will be a new instance\n const docCache = this.state.docCache;\n docCache.delete(this.primary);\n this._dataSync$.next(changeEvent.documentData);\n break;\n }\n },\n\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $() {\n return (this as RxDocument)._dataSync$.asObservable();\n },\n $emit(this: any, changeEvent: RxChangeEvent) {\n return this.parent.$emit(changeEvent);\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = objectPath.get(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n\n return this._dataSync$\n .pipe(\n map(data => objectPath.get(data, objPath)),\n distinctUntilChanged()\n );\n },\n atomicUpdate(mutationFunction: LocalDocumentAtomicUpdateFunction) {\n return new Promise((res, rej) => {\n this._atomicQueue = this._atomicQueue\n .then(async () => {\n let done = false;\n // we need a hacky while loop to stay incide the chain-link of _atomicQueue\n // while still having the option to run a retry on conflicts\n while (!done) {\n const oldDocData = this._dataSync$.getValue();\n const newData = await mutationFunction(clone(oldDocData.data), this);\n try {\n // always await because mutationFunction might be async\n\n const newDocData = flatClone(oldDocData);\n newDocData.data = newData;\n\n await this._saveData(newDocData, oldDocData);\n done = true;\n } catch (err) {\n /**\n * conflicts cannot happen by just using RxDB in one process\n * There are two ways they still can appear which is\n * replication and multi-tab usage\n * Because atomicUpdate has a mutation function,\n * we can just re-run the mutation until there is no conflict\n */\n const isConflict = isBulkWriteConflictError(err as any);\n if (isConflict) {\n // conflict error -> retrying\n } else {\n rej(err);\n return;\n }\n }\n }\n res(this);\n });\n });\n },\n atomicPatch(patch: Partial) {\n return this.atomicUpdate((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._dataSync$.getValue() as any;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[newData.id];\n if (!docResult) {\n throw getFromObjectOrThrow(res.error, newData.id);\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: any): Promise {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then(() => {\n this.state.docCache.delete(this.id);\n });\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n id: string,\n data: RxDocumentData>,\n parent: any,\n state: LocalDocumentState\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(id, data, parent, state);\n newDoc.__proto__ = RxLocalDocumentPrototype;\n state.docCache.set(id, newDoc as any);\n return newDoc as any;\n}\n"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA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,CACI,UAAU,EACV,QAAQ,EACR,eAAe,EACf,eAAe,EACf,gBAAgB,CACnB,CAACD,OAAO,CAAC,UAACC,CAAS;IAAA,OAAKxD,wBAAwB,CAACwD,CAAC,CAAC,GAAG8B,cAAc,CAAC9B,CAAC,CAAC;EAAA,EAAC;AAC7E,CAAC;AAIM,SAASgC,qBAAqB,CACjC3F,EAAU,EACVkC,IAAkD,EAClDhC,MAAW,EACX3B,KAAyB,EACD;EACxBwG,KAAK,EAAE;EACP,IAAMa,MAAM,GAAG,IAAI7F,oBAAoB,CAACC,EAAE,EAAEkC,IAAI,EAAEhC,MAAM,EAAE3B,KAAK,CAAC;EAChEqH,MAAM,CAACC,SAAS,GAAG1F,wBAAwB;EAC3C5B,KAAK,CAACsC,QAAQ,CAACiF,GAAG,CAAC9F,EAAE,EAAE4F,MAAM,CAAQ;EACrC,OAAOA,MAAM;AACjB"} \ No newline at end of file +{"version":3,"file":"rx-local-document.js","names":["RxDocumentParent","createRxDocumentConstructor","RxLocalDocumentClass","id","jsonData","parent","RxLocalDocumentPrototype","isLocal","allAttachments$","newRxError","document","primaryPath","primary","$","_this","pipe","filter","changeEvent","documentId","map","getDocumentDataOfRxChangeEvent","startWith","_data","distinctUntilChanged","prev","curr","_rev","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","getLatest","state","getFromMapOrThrow","LOCAL_DOC_STATE_BY_PARENT_RESOLVED","latestDocData","docCache","getLatestDocumentData","getCachedRxDocument","get","objPath","undefined","newRxTypeError","valueObj","objectPath","overwritable","deepFreezeWhenDevMode","get$","isDevMode","includes","data","incrementalModify","mutationFunction","getLocalDocStateByParent","incrementalWriteQueue","addWrite","docData","then","result","incrementalPatch","patch","Object","entries","forEach","k","v","_saveData","newData","oldData","storageInstance","bulkWrite","previous","res","docResult","success","getFromObjectOrThrow","error","flatClone","remove","writeData","_deleted","_meta","getDefaultRxDocumentMeta","getDefaultRevision","_attachments","writeSingle","writeResult","INIT_DONE","_init","docBaseProto","basePrototype","props","getOwnPropertyNames","key","exists","getOwnPropertyDescriptor","desc","defineProperty","getThrowingFun","functionName","createRxLocalDocument","newDoc","setPrototypeOf","prototype"],"sources":["../../../../src/plugins/local-documents/rx-local-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { Observable } from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs/operators';\nimport { overwritable } from '../../overwritable';\nimport { getDocumentDataOfRxChangeEvent } from '../../rx-change-event';\nimport {\n basePrototype,\n createRxDocumentConstructor\n} from '../../rx-document';\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error';\nimport { writeSingle } from '../../rx-storage-helper';\nimport type {\n LocalDocumentModifyFunction,\n RxCollection,\n RxDatabase,\n RxDocument,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocument,\n RxLocalDocumentData\n} from '../../types';\nimport {\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromMapOrThrow,\n getFromObjectOrThrow,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils';\nimport { getLocalDocStateByParent, LOCAL_DOC_STATE_BY_PARENT_RESOLVED } from './local-documents-helper';\n\nconst RxDocumentParent = createRxDocumentConstructor() as any;\n\nclass RxLocalDocumentClass extends RxDocumentParent {\n constructor(\n public readonly id: string,\n jsonData: DocData,\n public readonly parent: RxCollection | RxDatabase\n ) {\n super(null, jsonData);\n }\n}\n\n\n\nconst RxLocalDocumentPrototype: any = {\n get isLocal() {\n return true;\n },\n\n //\n // overwrites\n //\n get allAttachments$() {\n // this is overwritten here because we cannot re-set getters on the prototype\n throw newRxError('LD1', {\n document: this\n });\n },\n get primaryPath() {\n return 'id';\n },\n get primary() {\n return this.id;\n },\n get $(): Observable> {\n const _this: RxLocalDocumentClass = this as any;\n return _this.parent.$.pipe(\n filter(changeEvent => changeEvent.isLocal),\n filter(changeEvent => changeEvent.documentId === this.primary),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(this._data),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n },\n getLatest(this: RxLocalDocument): RxLocalDocument {\n const state = getFromMapOrThrow(LOCAL_DOC_STATE_BY_PARENT_RESOLVED, this.parent);\n const latestDocData = state.docCache.getLatestDocumentData(this.primary);\n return state.docCache.getCachedRxDocument(latestDocData) as any;\n },\n get(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (!this._data) {\n return undefined;\n }\n if (typeof objPath !== 'string') {\n throw newRxTypeError('LD2', {\n objPath\n });\n }\n\n let valueObj = objectPath.get(this._data, objPath);\n valueObj = overwritable.deepFreezeWhenDevMode(valueObj);\n return valueObj;\n },\n get$(this: RxDocument, objPath: string) {\n objPath = 'data.' + objPath;\n\n if (overwritable.isDevMode()) {\n if (objPath.includes('.item.')) {\n throw newRxError('LD3', {\n objPath\n });\n }\n if (objPath === this.primaryPath) {\n throw newRxError('LD4');\n }\n }\n return this.$\n .pipe(\n map(data => objectPath.get(data, objPath)),\n distinctUntilChanged()\n );\n },\n async incrementalModify(\n this: RxLocalDocument,\n mutationFunction: LocalDocumentModifyFunction\n ) {\n const state = await getLocalDocStateByParent(this.parent);\n\n return state.incrementalWriteQueue.addWrite(\n this._data as any,\n async (docData) => {\n docData.data = await mutationFunction(docData.data, this);\n return docData;\n }\n ).then(result => state.docCache.getCachedRxDocument(result as any));\n },\n incrementalPatch(patch: Partial) {\n return this.incrementalModify((docData: any) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n docData[k] = v;\n });\n return docData;\n });\n },\n async _saveData(this: RxLocalDocument, newData: RxDocumentData) {\n const state = await getLocalDocStateByParent(this.parent);\n const oldData: RxDocumentData = this._data;\n newData.id = (this as any).id;\n return state.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'local-document-save-data')\n .then((res) => {\n const docResult = res.success[newData.id];\n if (!docResult) {\n throw getFromObjectOrThrow(res.error, newData.id);\n }\n newData = flatClone(newData);\n newData._rev = docResult._rev;\n });\n },\n\n async remove(this: RxLocalDocument): Promise> {\n const state = await getLocalDocStateByParent(this.parent);\n const writeData: RxDocumentWriteData = {\n id: this._data.id,\n data: {},\n _deleted: true,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n return writeSingle(state.storageInstance, {\n previous: this._data,\n document: writeData\n }, 'local-document-remove')\n .then((writeResult) => state.docCache.getCachedRxDocument(writeResult) as any);\n }\n};\n\n\n\nlet INIT_DONE = false;\nconst _init = () => {\n if (INIT_DONE) return;\n else INIT_DONE = true;\n\n // add functions of RxDocument\n const docBaseProto = basePrototype;\n const props = Object.getOwnPropertyNames(docBaseProto);\n props.forEach(key => {\n const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key);\n if (exists) return;\n const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key);\n Object.defineProperty(RxLocalDocumentPrototype, key, desc);\n });\n\n\n /**\n * Overwrite things that do not work on local documents\n * with a throwing function.\n */\n const getThrowingFun = (k: string) => () => {\n throw newRxError('LD6', {\n functionName: k\n });\n };\n [\n 'populate',\n 'update',\n 'putAttachment',\n 'getAttachment',\n 'allAttachments'\n ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k));\n};\n\n\n\nexport function createRxLocalDocument(\n data: RxDocumentData>,\n parent: any\n): RxLocalDocument {\n _init();\n const newDoc = new RxLocalDocumentClass(data.id, data, parent);\n Object.setPrototypeOf(newDoc, RxLocalDocumentPrototype);\n newDoc.prototype = RxLocalDocumentPrototype;\n return newDoc as any;\n}\n"],"mappings":";;;;;;;;;;AAAA;AAEA;AAOA;AACA;AACA;AAIA;AAIA;AAWA;AAQA;AAEA,IAAMA,gBAAgB,GAAG,IAAAC,uCAA2B,GAAS;AAAC,IAExDC,oBAAoB;EAAA;EACtB,8BACoBC,EAAU,EAC1BC,QAAiB,EACDC,MAAiC,EACnD;IA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Ac,CAACD,MAAM,EAAE7F,wBAAwB,CAAC;EACvD6F,MAAM,CAACE,SAAS,GAAG/F,wBAAwB;EAC3C,OAAO6F,MAAM;AACjB"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/index.js.map b/dist/lib/plugins/lokijs/index.js.map deleted file mode 100644 index 2f920be0f8f..00000000000 --- a/dist/lib/plugins/lokijs/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/lokijs/index.ts"],"sourcesContent":["export * from './rx-storage-lokijs';\nexport * from './lokijs-helper';\nexport * from './rx-storage-instance-loki';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/loki-save-queue.js.map b/dist/lib/plugins/lokijs/loki-save-queue.js.map deleted file mode 100644 index 88879f53ae2..00000000000 --- a/dist/lib/plugins/lokijs/loki-save-queue.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"loki-save-queue.js","names":["LokiSaveQueue","lokiDatabase","databaseSettings","writesSinceLastRun","saveQueue","PROMISE_RESOLVE_VOID","saveQueueC","addWrite","run","adapter","then","requestIdlePromise","writeAmount","Promise","res","rej","saveDatabase","err","autosaveCallback"],"sources":["../../../../src/plugins/lokijs/loki-save-queue.ts"],"sourcesContent":["import type { LokiDatabaseSettings } from '../../types';\nimport {\n PROMISE_RESOLVE_VOID,\n requestIdlePromise\n} from '../../util';\n\n/**\n * The autosave feature of lokijs has strange behaviors\n * and often runs a save in critical moments when other\n * more important tasks are running.\n * So instead we use a custom save queue that ensures we\n * only run loki.saveDatabase() when nothing else is running.\n */\nexport class LokiSaveQueue {\n public writesSinceLastRun: number = 0;\n\n /**\n * Ensures that we do not run multiple saves\n * in parallel\n */\n public saveQueue: Promise = PROMISE_RESOLVE_VOID;\n // track amount of non-finished save calls in the queue.\n public saveQueueC = 0;\n\n constructor(\n public readonly lokiDatabase: Loki,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n\n }\n\n public addWrite() {\n this.writesSinceLastRun = this.writesSinceLastRun + 1;\n this.run();\n }\n\n public run() {\n if (\n // no persistence adapter given, so we do not need to save\n !this.databaseSettings.adapter ||\n // do not add more then two pending calls to the queue.\n this.saveQueueC > 2\n\n ) {\n return this.saveQueue;\n }\n\n this.saveQueueC = this.saveQueueC + 1;\n this.saveQueue = this.saveQueue\n .then(async () => {\n /**\n * Always wait until the JavaScript process is idle.\n * This ensures that CPU blocking writes are finished\n * before we proceed.\n */\n await requestIdlePromise();\n\n // no write happened since the last save call\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n /**\n * Because LokiJS is a in-memory database,\n * we can just wait until the JavaScript process is idle\n * via requestIdlePromise(). Then we know that nothing important\n * is running at the moment.\n */\n await requestIdlePromise().then(() => requestIdlePromise());\n\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n const writeAmount = this.writesSinceLastRun;\n this.writesSinceLastRun = 0;\n return new Promise((res, rej) => {\n this.lokiDatabase.saveDatabase(err => {\n if (err) {\n this.writesSinceLastRun = this.writesSinceLastRun + writeAmount;\n rej(err);\n } else {\n if (this.databaseSettings.autosaveCallback) {\n this.databaseSettings.autosaveCallback();\n }\n res();\n }\n });\n });\n })\n .catch(() => { })\n .then(() => {\n this.saveQueueC = this.saveQueueC - 1;\n });\n return this.saveQueue;\n }\n}\n"],"mappings":";;;;;;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOaA,aAAa;EAGtB;AACJ;AACA;AACA;;EAEI;;EAGA,uBACoBC,YAAkB,EAClBC,gBAAsC,EACxD;IAAA,KAbKC,kBAAkB,GAAW,CAAC;IAAA,KAM9BC,SAAS,GAAkB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,GAAG,CAAC;gBACZ,CAAC,MAAM;kBACH,IAAI,KAAI,CAACf,gBAAgB,CAACgB,gBAAgB,EAAE;oBACxC,KAAI,CAAChB,gBAAgB,CAACgB,gBAAgB,EAAE;kBAC5C;kBACAJ,GAAG,EAAE;gBACT;cACJ,CAAC,CAAC;YACN,CAAC,CAAC;UAAC;QAAA;MACP,CAAC;QAAA;MAAA;IAAA,EAAC,SACI,CAAC,YAAM,CAAE,CAAC,CAAC,CAChBJ,IAAI,CAAC,YAAM;MACR,KAAI,CAACJ,UAAU,GAAG,KAAI,CAACA,UAAU,GAAG,CAAC;IACzC,CAAC,CAAC;IACN,OAAO,IAAI,CAACF,SAAS;EACzB,CAAC;EAAA;AAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/lokijs-helper.js b/dist/lib/plugins/lokijs/lokijs-helper.js deleted file mode 100644 index 426b554d34a..00000000000 --- a/dist/lib/plugins/lokijs/lokijs-helper.js +++ /dev/null @@ -1,615 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.closeLokiCollections = exports.RX_STORAGE_NAME_LOKIJS = exports.OPEN_LOKIJS_STORAGE_INSTANCES = exports.LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = exports.LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = exports.LOKIJS_COLLECTION_DEFAULT_OPTIONS = exports.CHANGES_COLLECTION_SUFFIX = void 0; -exports.getLokiDatabase = getLokiDatabase; -exports.getLokiLeaderElector = getLokiLeaderElector; -exports.getLokiSortComparator = getLokiSortComparator; -exports.requestRemoteInstance = exports.mustUseLocalState = exports.handleRemoteRequest = void 0; -exports.stripLokiKey = stripLokiKey; -exports.waitUntilHasLeader = void 0; -var _rxStorageInstanceLoki = require("./rx-storage-instance-loki"); -var _lokijs = _interopRequireDefault(require("lokijs")); -var _unload = require("unload"); -var _util = require("../../util"); -var _lokiSaveQueue = require("./loki-save-queue"); -var _rxError = require("../../rx-error"); -var _objectPath = _interopRequireDefault(require("object-path")); -var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); -var _leaderElection = require("../leader-election"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -/** - * If the local state must be used, that one is returned. - * Returns false if a remote instance must be used. - */ -var mustUseLocalState = function mustUseLocalState(instance) { - try { - if (instance.closed) { - /** - * If this happens, it means that RxDB made a call to an already closed storage instance. - * This must never happen because when RxDB closes a collection or database, - * all tasks must be cleared so that no more calls are made the the storage. - */ - throw (0, _rxError.newRxError)('SNH', { - args: { - instanceClosed: instance.closed, - databaseName: instance.databaseName, - collectionName: instance.collectionName - } - }); - } - if (instance.internals.localState) { - return Promise.resolve(instance.internals.localState); - } - var leaderElector = (0, _util.ensureNotFalsy)(instance.internals.leaderElector); - return Promise.resolve(waitUntilHasLeader(leaderElector)).then(function () { - /** - * It might already have a localState after the applying - * because another subtask also called mustUSeLocalState() - */ - if (instance.internals.localState) { - return instance.internals.localState; - } - if (leaderElector.isLeader && !instance.internals.localState) { - // own is leader, use local instance - instance.internals.localState = (0, _rxStorageInstanceLoki.createLokiLocalState)({ - databaseInstanceToken: instance.databaseInstanceToken, - databaseName: instance.databaseName, - collectionName: instance.collectionName, - options: instance.options, - schema: instance.schema, - multiInstance: instance.internals.leaderElector ? true : false - }, instance.databaseSettings); - return (0, _util.ensureNotFalsy)(instance.internals.localState); - } else { - // other is leader, send message to remote leading instance - return false; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.mustUseLocalState = mustUseLocalState; -var waitUntilHasLeader = function waitUntilHasLeader(leaderElector) { - try { - var _temp7 = _for(function () { - return !leaderElector.hasLeader; - }, void 0, function () { - return Promise.resolve(leaderElector.applyOnce()).then(function () { - return Promise.resolve((0, _util.promiseWait)(0)).then(function () {}); - }); - }); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -exports.waitUntilHasLeader = waitUntilHasLeader; -/** - * Handles a request that came from a remote instance via requestRemoteInstance() - * Runs the requested operation over the local db instance and sends back the result. - */ -var handleRemoteRequest = function handleRemoteRequest(instance, msg) { - try { - var _temp6 = function () { - if (msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE && msg.requestId && msg.databaseName === instance.databaseName && msg.collectionName === instance.collectionName && !msg.response) { - var _temp5 = function _temp5() { - var response = { - response: true, - requestId: msg.requestId, - databaseName: instance.databaseName, - collectionName: instance.collectionName, - result: _result, - isError: _isError, - type: msg.type - }; - (0, _util.ensureNotFalsy)(instance.internals.leaderElector).broadcastChannel.postMessage(response); - }; - var operation = msg.operation; - var params = msg.params; - var _result; - var _isError = false; - var _temp4 = _catch(function () { - var _ref2; - return Promise.resolve((_ref2 = instance)[operation].apply(_ref2, params)).then(function (_operation) { - _result = _operation; - }); - }, function (err) { - console.dir(err); - _isError = true; - _result = err; - }); - return _temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4); - } - }(); - return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -exports.handleRemoteRequest = handleRemoteRequest; -/** - * For multi-instance usage, we send requests to the RxStorage - * to the current leading instance over the BroadcastChannel. - */ -var requestRemoteInstance = function requestRemoteInstance(instance, operation, params) { - try { - var isRxStorageInstanceLoki = typeof instance.query === 'function'; - var messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE; - var leaderElector = (0, _util.ensureNotFalsy)(instance.internals.leaderElector); - return Promise.resolve(waitUntilHasLeader(leaderElector)).then(function () { - var broadcastChannel = leaderElector.broadcastChannel; - var whenDeathListener; - var leaderDeadPromise = new Promise(function (res) { - whenDeathListener = function whenDeathListener(msg) { - if (msg.context === 'leader' && msg.action === 'death') { - res({ - retry: true - }); - } - }; - broadcastChannel.addEventListener('internal', whenDeathListener); - }); - var requestId = (0, _util.randomCouchString)(12); - var responseListener; - var responsePromise = new Promise(function (res, _rej) { - responseListener = function responseListener(msg) { - if (msg.type === messageType && msg.response === true && msg.requestId === requestId) { - if (msg.isError) { - res({ - retry: false, - error: msg.result - }); - } else { - res({ - retry: false, - result: msg.result - }); - } - } - }; - broadcastChannel.addEventListener('message', responseListener); - }); - - // send out the request to the other instance - broadcastChannel.postMessage({ - response: false, - type: messageType, - operation: operation, - params: params, - requestId: requestId, - databaseName: instance.databaseName, - collectionName: instance.collectionName - }); - return Promise.race([leaderDeadPromise, responsePromise]).then(function (firstResolved) { - // clean up listeners - broadcastChannel.removeEventListener('message', responseListener); - broadcastChannel.removeEventListener('internal', whenDeathListener); - if (firstResolved.retry) { - var _ref; - /** - * The leader died while a remote request was running - * we re-run the whole operation. - * We cannot just re-run requestRemoteInstance() - * because the current instance might be the new leader now - * and then we have to use the local state instead of requesting the remote. - */ - return (_ref = instance)[operation].apply(_ref, params); - } else { - if (firstResolved.error) { - throw firstResolved.error; - } else { - return firstResolved.result; - } - } - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.requestRemoteInstance = requestRemoteInstance; -var closeLokiCollections = function closeLokiCollections(databaseName, collections) { - try { - return Promise.resolve(LOKI_DATABASE_STATE_BY_NAME.get(databaseName)).then(function (databaseState) { - if (!databaseState) { - // already closed - return; - } - return Promise.resolve(databaseState.saveQueue.run()).then(function () { - collections.forEach(function (collection) { - var collectionName = collection.name; - delete databaseState.collections[collectionName]; - }); - var _temp3 = function () { - if (Object.keys(databaseState.collections).length === 0) { - // all collections closed -> also close database - LOKI_DATABASE_STATE_BY_NAME["delete"](databaseName); - databaseState.unloads.forEach(function (u) { - return u.remove(); - }); - return Promise.resolve(new Promise(function (res, rej) { - databaseState.database.close(function (err) { - if (err) { - rej(err); - } else { - res(); - } - }); - })).then(function () {}); - } - }(); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * This function is at lokijs-helper - * because we need it in multiple places. - */ -exports.closeLokiCollections = closeLokiCollections; -var CHANGES_COLLECTION_SUFFIX = '-rxdb-changes'; -exports.CHANGES_COLLECTION_SUFFIX = CHANGES_COLLECTION_SUFFIX; -var LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request'; -exports.LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE; -var LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object'; -exports.LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE; -var RX_STORAGE_NAME_LOKIJS = 'lokijs'; - -/** - * Loki attaches a $loki property to all data - * which must be removed before returning the data back to RxDB. - */ -exports.RX_STORAGE_NAME_LOKIJS = RX_STORAGE_NAME_LOKIJS; -function stripLokiKey(docData) { - if (!docData.$loki) { - return docData; - } - var cloned = (0, _util.flatClone)(docData); - - /** - * In RxDB version 12.0.0, - * we introduced the _meta field that already contains the last write time. - * To be backwards compatible, we have to move the $lastWriteAt to the _meta field. - * TODO remove this in the next major version. - */ - if (cloned.$lastWriteAt) { - cloned._meta = { - lwt: cloned.$lastWriteAt - }; - delete cloned.$lastWriteAt; - } - delete cloned.$loki; - return cloned; -} - -/** - * Used to check in tests if all instances have been cleaned up. - */ -var OPEN_LOKIJS_STORAGE_INSTANCES = new Set(); -exports.OPEN_LOKIJS_STORAGE_INSTANCES = OPEN_LOKIJS_STORAGE_INSTANCES; -var LOKIJS_COLLECTION_DEFAULT_OPTIONS = { - disableChangesApi: true, - disableMeta: true, - disableDeltaChangesApi: true, - disableFreeze: true, - // TODO use 'immutable' like WatermelonDB does it - cloneMethod: 'shallow-assign', - clone: false, - transactional: false, - autoupdate: false -}; -exports.LOKIJS_COLLECTION_DEFAULT_OPTIONS = LOKIJS_COLLECTION_DEFAULT_OPTIONS; -var LOKI_DATABASE_STATE_BY_NAME = new Map(); -function getLokiDatabase(databaseName, databaseSettings) { - var databaseState = LOKI_DATABASE_STATE_BY_NAME.get(databaseName); - if (!databaseState) { - /** - * We assume that as soon as an adapter is passed, - * the database has to be persistend. - */ - var hasPersistence = !!databaseSettings.adapter; - databaseState = function () { - try { - var _temp2 = function _temp2() { - /** - * Autosave database on process end - */ - var unloads = []; - if (hasPersistence) { - unloads.push((0, _unload.add)(function () { - return lokiSaveQueue.run(); - })); - } - var state = { - database: database, - databaseSettings: useSettings, - saveQueue: lokiSaveQueue, - collections: {}, - unloads: unloads - }; - return state; - }; - var persistenceMethod = hasPersistence ? 'adapter' : 'memory'; - if (databaseSettings.persistenceMethod) { - persistenceMethod = databaseSettings.persistenceMethod; - } - var useSettings = Object.assign( - // defaults - { - autoload: hasPersistence, - persistenceMethod: persistenceMethod, - verbose: true - }, databaseSettings, - // overwrites - { - /** - * RxDB uses its custom load and save handling - * so we disable the LokiJS save/load handlers. - */ - autoload: false, - autosave: false, - throttledSaves: false - }); - var database = new _lokijs["default"](databaseName + '.db', (0, _util.flatClone)(useSettings)); - var lokiSaveQueue = new _lokiSaveQueue.LokiSaveQueue(database, useSettings); - - /** - * Wait until all data is loaded from persistence adapter. - * Wrap the loading into the saveQueue to ensure that when many - * collections are created at the same time, the load-calls do not interfere - * with each other and cause error logs. - */ - var _temp = function () { - if (hasPersistence) { - var loadDatabasePromise = new Promise(function (res, rej) { - try { - database.loadDatabase({ - recursiveWait: false - }, function (err) { - if (useSettings.autoloadCallback) { - useSettings.autoloadCallback(err); - } - if (err) { - rej(err); - } else { - res(); - } - }); - } catch (err) { - rej(err); - } - }); - lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(function () { - return loadDatabasePromise; - }); - return Promise.resolve(loadDatabasePromise).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } - }(); - LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState); - } - return databaseState; -} -function getLokiSortComparator(_schema, query) { - if (!query.sort) { - throw (0, _rxError.newRxError)('SNH', { - query: query - }); - } - var sortOptions = query.sort; - var fun = function fun(a, b) { - var compareResult = 0; // 1 | -1 - sortOptions.find(function (sortPart) { - var fieldName = Object.keys(sortPart)[0]; - var direction = Object.values(sortPart)[0]; - var directionMultiplier = direction === 'asc' ? 1 : -1; - var valueA = _objectPath["default"].get(a, fieldName); - var valueB = _objectPath["default"].get(b, fieldName); - if (valueA === valueB) { - return false; - } else { - if (valueA > valueB) { - compareResult = 1 * directionMultiplier; - return true; - } else { - compareResult = -1 * directionMultiplier; - return true; - } - } - }); - - /** - * Two different objects should never have the same sort position. - * We ensure this by having the unique primaryKey in the sort params - * which is added by RxDB if not existing yet. - */ - if (!compareResult) { - throw (0, _rxError.newRxError)('SNH', { - args: { - query: query, - a: a, - b: b - } - }); - } - return compareResult; - }; - return fun; -} -function getLokiLeaderElector(databaseInstanceToken, broadcastChannelRefObject, databaseName) { - var broadcastChannel = (0, _rxStorageMultiinstance.getBroadcastChannelReference)(databaseInstanceToken, databaseName, broadcastChannelRefObject); - var elector = (0, _leaderElection.getLeaderElectorByBroadcastChannel)(broadcastChannel); - return elector; -} -//# sourceMappingURL=lokijs-helper.js.map \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/lokijs-helper.js.map b/dist/lib/plugins/lokijs/lokijs-helper.js.map deleted file mode 100644 index 45153e18ae0..00000000000 --- a/dist/lib/plugins/lokijs/lokijs-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-helper.js","names":["body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","mustUseLocalState","instance","closed","newRxError","args","instanceClosed","databaseName","collectionName","internals","localState","leaderElector","ensureNotFalsy","waitUntilHasLeader","isLeader","createLokiLocalState","databaseInstanceToken","options","schema","multiInstance","databaseSettings","hasLeader","applyOnce","promiseWait","handleRemoteRequest","msg","type","LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE","requestId","response","isError","broadcastChannel","postMessage","operation","params","err","console","dir","requestRemoteInstance","isRxStorageInstanceLoki","query","messageType","LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE","whenDeathListener","leaderDeadPromise","Promise","res","context","action","retry","addEventListener","randomCouchString","responseListener","responsePromise","_rej","error","race","firstResolved","removeEventListener","closeLokiCollections","collections","LOKI_DATABASE_STATE_BY_NAME","get","databaseState","saveQueue","run","forEach","collection","name","Object","keys","length","unloads","u","remove","rej","database","close","CHANGES_COLLECTION_SUFFIX","RX_STORAGE_NAME_LOKIJS","stripLokiKey","docData","$loki","cloned","flatClone","$lastWriteAt","_meta","lwt","OPEN_LOKIJS_STORAGE_INSTANCES","Set","LOKIJS_COLLECTION_DEFAULT_OPTIONS","disableChangesApi","disableMeta","disableDeltaChangesApi","disableFreeze","cloneMethod","clone","transactional","autoupdate","Map","getLokiDatabase","hasPersistence","adapter","push","unloadAdd","lokiSaveQueue","useSettings","persistenceMethod","assign","autoload","verbose","autosave","throttledSaves","lokijs","LokiSaveQueue","loadDatabasePromise","loadDatabase","recursiveWait","autoloadCallback","set","getLokiSortComparator","_schema","sort","sortOptions","fun","a","b","compareResult","find","sortPart","fieldName","direction","values","directionMultiplier","valueA","objectPath","valueB","getLokiLeaderElector","broadcastChannelRefObject","getBroadcastChannelReference","elector","getLeaderElectorByBroadcastChannel"],"sources":["../../../../src/plugins/lokijs/lokijs-helper.ts"],"sourcesContent":["import { createLokiLocalState, RxStorageInstanceLoki } from './rx-storage-instance-loki';\nimport lokijs, { Collection } from 'lokijs';\nimport type {\n LokiDatabaseSettings,\n LokiDatabaseState,\n LokiLocalDatabaseState,\n LokiRemoteResponseBroadcastMessage,\n MangoQuery,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport {\n add as unloadAdd,\n AddReturn\n} from 'unload';\nimport { ensureNotFalsy, flatClone, promiseWait, randomCouchString } from '../../util';\nimport { LokiSaveQueue } from './loki-save-queue';\nimport type { DeterministicSortComparator } from 'event-reduce-js';\nimport { newRxError } from '../../rx-error';\nimport objectPath from 'object-path';\nimport {\n LeaderElector,\n OnMessageHandler\n} from 'broadcast-channel';\nimport { getBroadcastChannelReference } from '../../rx-storage-multiinstance';\nimport { getLeaderElectorByBroadcastChannel } from '../leader-election';\n\nexport const CHANGES_COLLECTION_SUFFIX = '-rxdb-changes';\nexport const LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request';\nexport const LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object';\nexport const RX_STORAGE_NAME_LOKIJS = 'lokijs';\n\n/**\n * Loki attaches a $loki property to all data\n * which must be removed before returning the data back to RxDB.\n */\nexport function stripLokiKey(docData: RxDocumentData & { $loki?: number; }): T {\n if (!docData.$loki) {\n return docData;\n }\n const cloned = flatClone(docData);\n\n /**\n * In RxDB version 12.0.0,\n * we introduced the _meta field that already contains the last write time.\n * To be backwards compatible, we have to move the $lastWriteAt to the _meta field.\n * TODO remove this in the next major version.\n */\n if ((cloned as any).$lastWriteAt) {\n cloned._meta = {\n lwt: (cloned as any).$lastWriteAt\n };\n delete (cloned as any).$lastWriteAt;\n }\n\n delete cloned.$loki;\n return cloned;\n}\n\n/**\n * Used to check in tests if all instances have been cleaned up.\n */\nexport const OPEN_LOKIJS_STORAGE_INSTANCES: Set> = new Set();\n\n\nexport const LOKIJS_COLLECTION_DEFAULT_OPTIONS: Partial> = {\n disableChangesApi: true,\n disableMeta: true,\n disableDeltaChangesApi: true,\n disableFreeze: true,\n // TODO use 'immutable' like WatermelonDB does it\n cloneMethod: 'shallow-assign',\n clone: false,\n transactional: false,\n autoupdate: false\n};\n\nconst LOKI_DATABASE_STATE_BY_NAME: Map> = new Map();\nexport function getLokiDatabase(\n databaseName: string,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n let databaseState: Promise | undefined = LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n /**\n * We assume that as soon as an adapter is passed,\n * the database has to be persistend.\n */\n const hasPersistence: boolean = !!databaseSettings.adapter;\n databaseState = (async () => {\n let persistenceMethod = hasPersistence ? 'adapter' : 'memory';\n if (databaseSettings.persistenceMethod) {\n persistenceMethod = databaseSettings.persistenceMethod;\n }\n const useSettings = Object.assign(\n // defaults\n {\n autoload: hasPersistence,\n persistenceMethod,\n verbose: true\n },\n databaseSettings,\n // overwrites\n {\n /**\n * RxDB uses its custom load and save handling\n * so we disable the LokiJS save/load handlers.\n */\n autoload: false,\n autosave: false,\n throttledSaves: false\n }\n );\n const database = new lokijs(\n databaseName + '.db',\n flatClone(useSettings)\n );\n const lokiSaveQueue = new LokiSaveQueue(\n database,\n useSettings\n );\n\n /**\n * Wait until all data is loaded from persistence adapter.\n * Wrap the loading into the saveQueue to ensure that when many\n * collections are created at the same time, the load-calls do not interfere\n * with each other and cause error logs.\n */\n if (hasPersistence) {\n const loadDatabasePromise = new Promise((res, rej) => {\n try {\n database.loadDatabase({\n recursiveWait: false\n }, (err) => {\n if (useSettings.autoloadCallback) {\n useSettings.autoloadCallback(err);\n }\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n } catch (err) {\n rej(err);\n }\n });\n lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(() => loadDatabasePromise);\n await loadDatabasePromise;\n }\n\n /**\n * Autosave database on process end\n */\n const unloads: AddReturn[] = [];\n if (hasPersistence) {\n unloads.push(\n unloadAdd(() => lokiSaveQueue.run())\n );\n }\n\n const state: LokiDatabaseState = {\n database,\n databaseSettings: useSettings,\n saveQueue: lokiSaveQueue,\n collections: {},\n unloads\n };\n\n return state;\n })();\n LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState);\n }\n return databaseState;\n}\n\nexport async function closeLokiCollections(\n databaseName: string,\n collections: Collection[]\n) {\n const databaseState = await LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n // already closed\n return;\n }\n await databaseState.saveQueue.run();\n collections.forEach(collection => {\n const collectionName = collection.name;\n delete databaseState.collections[collectionName];\n });\n if (Object.keys(databaseState.collections).length === 0) {\n // all collections closed -> also close database\n LOKI_DATABASE_STATE_BY_NAME.delete(databaseName);\n databaseState.unloads.forEach(u => u.remove());\n await new Promise((res, rej) => {\n databaseState.database.close(err => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n}\n\n/**\n * This function is at lokijs-helper\n * because we need it in multiple places.\n */\nexport function getLokiSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n const sortOptions: MangoQuerySortPart[] = query.sort;\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n let compareResult: number = 0; // 1 | -1\n sortOptions.find(sortPart => {\n const fieldName: string = Object.keys(sortPart)[0];\n const direction: MangoQuerySortDirection = Object.values(sortPart)[0];\n const directionMultiplier = direction === 'asc' ? 1 : -1;\n const valueA: any = objectPath.get(a as any, fieldName);\n const valueB: any = objectPath.get(b as any, fieldName);\n if (valueA === valueB) {\n return false;\n } else {\n if (valueA > valueB) {\n compareResult = 1 * directionMultiplier;\n return true;\n } else {\n compareResult = -1 * directionMultiplier;\n return true;\n }\n }\n });\n\n /**\n * Two different objects should never have the same sort position.\n * We ensure this by having the unique primaryKey in the sort params\n * which is added by RxDB if not existing yet.\n */\n if (!compareResult) {\n throw newRxError('SNH', { args: { query, a, b } });\n }\n\n return compareResult as any;\n };\n return fun;\n}\n\nexport function getLokiLeaderElector(\n databaseInstanceToken: string,\n broadcastChannelRefObject: any,\n databaseName: string\n): LeaderElector {\n const broadcastChannel = getBroadcastChannelReference(\n databaseInstanceToken,\n databaseName,\n broadcastChannelRefObject\n );\n const elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n return elector;\n}\n\n/**\n * For multi-instance usage, we send requests to the RxStorage\n * to the current leading instance over the BroadcastChannel.\n */\nexport async function requestRemoteInstance(\n instance: RxStorageInstanceLoki,\n operation: string,\n params: any[]\n): Promise {\n const isRxStorageInstanceLoki = typeof (instance as any).query === 'function';\n const messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE;\n\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n const broadcastChannel = leaderElector.broadcastChannel;\n\n type WinningPromise = {\n retry: boolean;\n result?: any;\n error?: any;\n };\n\n let whenDeathListener: OnMessageHandler;\n const leaderDeadPromise = new Promise(res => {\n whenDeathListener = (msg: any) => {\n if (msg.context === 'leader' && msg.action === 'death') {\n res({\n retry: true\n });\n }\n };\n broadcastChannel.addEventListener('internal', whenDeathListener);\n });\n const requestId = randomCouchString(12);\n let responseListener: OnMessageHandler;\n const responsePromise = new Promise((res, _rej) => {\n responseListener = (msg: any) => {\n if (\n msg.type === messageType &&\n msg.response === true &&\n msg.requestId === requestId\n ) {\n if (msg.isError) {\n res({\n retry: false,\n error: msg.result\n });\n } else {\n res({\n retry: false,\n result: msg.result\n });\n }\n }\n };\n broadcastChannel.addEventListener('message', responseListener);\n });\n\n // send out the request to the other instance\n broadcastChannel.postMessage({\n response: false,\n type: messageType,\n operation,\n params,\n requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n });\n\n\n return Promise.race([\n leaderDeadPromise,\n responsePromise\n ]).then(firstResolved => {\n\n // clean up listeners\n broadcastChannel.removeEventListener('message', responseListener);\n broadcastChannel.removeEventListener('internal', whenDeathListener);\n\n if (firstResolved.retry) {\n /**\n * The leader died while a remote request was running\n * we re-run the whole operation.\n * We cannot just re-run requestRemoteInstance()\n * because the current instance might be the new leader now\n * and then we have to use the local state instead of requesting the remote.\n */\n return (instance as any)[operation](...params);\n } else {\n if (firstResolved.error) {\n throw firstResolved.error;\n } else {\n return firstResolved.result;\n }\n }\n });\n}\n\n/**\n * Handles a request that came from a remote instance via requestRemoteInstance()\n * Runs the requested operation over the local db instance and sends back the result.\n */\nexport async function handleRemoteRequest(\n instance: RxStorageInstanceLoki,\n msg: any\n) {\n if (\n msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE &&\n msg.requestId &&\n msg.databaseName === instance.databaseName &&\n msg.collectionName === instance.collectionName &&\n !msg.response\n ) {\n const operation = (msg as any).operation;\n const params = (msg as any).params;\n let result: any;\n let isError = false;\n try {\n result = await (instance as any)[operation](...params);\n } catch (err) {\n console.dir(err);\n isError = true;\n result = err;\n }\n const response: LokiRemoteResponseBroadcastMessage = {\n response: true,\n requestId: msg.requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n result,\n isError,\n type: msg.type\n };\n ensureNotFalsy(instance.internals.leaderElector).broadcastChannel.postMessage(response);\n }\n}\n\n\nexport async function waitUntilHasLeader(leaderElector: LeaderElector) {\n while (\n !leaderElector.hasLeader\n ) {\n await leaderElector.applyOnce();\n await promiseWait(0);\n }\n}\n\n/**\n * If the local state must be used, that one is returned.\n * Returns false if a remote instance must be used.\n */\nexport async function mustUseLocalState(\n instance: RxStorageInstanceLoki\n): Promise {\n if (instance.closed) {\n /**\n * If this happens, it means that RxDB made a call to an already closed storage instance.\n * This must never happen because when RxDB closes a collection or database,\n * all tasks must be cleared so that no more calls are made the the storage.\n */\n throw newRxError('SNH', {\n args: {\n instanceClosed: instance.closed,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n }\n });\n }\n\n\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n\n /**\n * It might already have a localState after the applying\n * because another subtask also called mustUSeLocalState()\n */\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n\n if (\n leaderElector.isLeader &&\n !instance.internals.localState\n ) {\n // own is leader, use local instance\n instance.internals.localState = createLokiLocalState({\n databaseInstanceToken: instance.databaseInstanceToken,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n options: instance.options,\n schema: (instance as RxStorageInstanceLoki).schema,\n multiInstance: instance.internals.leaderElector ? true : false\n }, instance.databaseSettings);\n return ensureNotFalsy(instance.internals.localState);\n } else {\n // other is leader, send message to remote leading instance\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAAA;AACA;AAYA;AAIA;AACA;AAEA;AACA;AAKA;AACA;AAuhBO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IA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,IAAME,SAAkC,GAAG9D,MAAM,CAAC+D,MAAM,CAACH,QAAQ,CAAC,CAAC,CAAC,CAAC;MACrE,IAAMI,mBAAmB,GAAGF,SAAS,KAAK,KAAK,GAAG,CAAC,GAAG,CAAC,CAAC;MACxD,IAAMG,MAAW,GAAGC,sBAAU,CAACzE,GAAG,CAAC+D,CAAC,EAASK,SAAS,CAAC;MACvD,IAAMM,MAAW,GAAGD,sBAAU,CAACzE,GAAG,CAACgE,CAAC,EAASI,SAAS,CAAC;MACvD,IAAII,MAAM,KAAKE,MAAM,EAAE;QACnB,OAAO,KAAK;MAChB,CAAC,MAAM;QACH,IAAIF,MAAM,GAAGE,MAAM,EAAE;UACjBT,aAAa,GAAG,CAAC,GAAGM,mBAAmB;UACvC,OAAO,IAAI;QACf,CAAC,MAAM;UACHN,aAAa,GAAG,CAAC,CAAC,GAAGM,mBAAmB;UACxC,OAAO,IAAI;QACf;MACJ;IACJ,CAAC,CAAC;;IAEF;AACR;AACA;AACA;AACA;IACQ,IAAI,CAACN,aAAa,EAAE;MAChB,MAAM,IAAA3H,mBAAU,EAAC,KAAK,EAAE;QAAEC,IAAI,EAAE;UAAEmC,KAAK,EAALA,KAAK;UAAEqF,CAAC,EAADA,CAAC;UAAEC,CAAC,EAADA;QAAE;MAAE,CAAC,CAAC;IACtD;IAEA,OAAOC,aAAa;EACxB,CAAC;EACD,OAAOH,GAAG;AACd;AAEO,SAASa,oBAAoB,CAChCzH,qBAA6B,EAC7B0H,yBAA8B,EAC9BnI,YAAoB,EACP;EACb,IAAMwB,gBAAgB,GAAG,IAAA4G,oDAA4B,EACjD3H,qBAAqB,EACrBT,YAAY,EACZmI,yBAAyB,CAC5B;EACD,IAAME,OAAO,GAAG,IAAAC,kDAAkC,EAAC9G,gBAAgB,CAAC;EACpE,OAAO6G,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/rx-storage-instance-loki.js b/dist/lib/plugins/lokijs/rx-storage-instance-loki.js deleted file mode 100644 index ef5d279a41c..00000000000 --- a/dist/lib/plugins/lokijs/rx-storage-instance-loki.js +++ /dev/null @@ -1,401 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.createLokiStorageInstance = exports.createLokiLocalState = exports.RxStorageInstanceLoki = void 0; -var _rxjs = require("rxjs"); -var _util = require("../../util"); -var _rxError = require("../../rx-error"); -var _lokijsHelper = require("./lokijs-helper"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _rxStorageHelper = require("../../rx-storage-helper"); -var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); -var createLokiStorageInstance = function createLokiStorageInstance(storage, params, databaseSettings) { - try { - var _temp3 = function _temp3() { - var instance = new RxStorageInstanceLoki(params.databaseInstanceToken, storage, params.databaseName, params.collectionName, params.schema, _internals, params.options, databaseSettings); - (0, _rxStorageMultiinstance.addRxStorageMultiInstanceSupport)(_lokijsHelper.RX_STORAGE_NAME_LOKIJS, params, instance, _internals.leaderElector ? _internals.leaderElector.broadcastChannel : undefined); - if (params.multiInstance) { - /** - * Clean up the broadcast-channel reference on close() - */ - var closeBefore = instance.close.bind(instance); - instance.close = function () { - (0, _rxStorageMultiinstance.removeBroadcastChannelReference)(params.databaseInstanceToken, broadcastChannelRefObject); - return closeBefore(); - }; - var removeBefore = instance.remove.bind(instance); - instance.remove = function () { - (0, _rxStorageMultiinstance.removeBroadcastChannelReference)(params.databaseInstanceToken, broadcastChannelRefObject); - return removeBefore(); - }; - - /** - * Directly create the localState when/if the db becomes leader. - */ - (0, _util.ensureNotFalsy)(_internals.leaderElector).awaitLeadership().then(function () { - if (!instance.closed) { - (0, _lokijsHelper.mustUseLocalState)(instance); - } - }); - } - return instance; - }; - var _internals = {}; - var broadcastChannelRefObject = {}; - var _temp2 = function () { - if (params.multiInstance) { - var leaderElector = (0, _lokijsHelper.getLokiLeaderElector)(params.databaseInstanceToken, broadcastChannelRefObject, params.databaseName); - _internals.leaderElector = leaderElector; - } else { - // optimisation shortcut, directly create db is non multi instance. - _internals.localState = createLokiLocalState(params, databaseSettings); - return Promise.resolve(_internals.localState).then(function () {}); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createLokiStorageInstance = createLokiStorageInstance; -var createLokiLocalState = function createLokiLocalState(params, databaseSettings) { - try { - if (!params.options) { - params.options = {}; - } - return Promise.resolve((0, _lokijsHelper.getLokiDatabase)(params.databaseName, databaseSettings)).then(function (databaseState) { - /** - * Construct loki indexes from RxJsonSchema indexes. - * TODO what about compound indexes? Are they possible in lokijs? - */ - var indices = []; - if (params.schema.indexes) { - params.schema.indexes.forEach(function (idx) { - if (!(0, _util.isMaybeReadonlyArray)(idx)) { - indices.push(idx); - } - }); - } - /** - * LokiJS has no concept of custom primary key, they use a number-id that is generated. - * To be able to query fast by primary key, we always add an index to the primary. - */ - var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(params.schema.primaryKey); - indices.push(primaryKey); - var lokiCollectionName = params.collectionName + '-' + params.schema.version; - var collectionOptions = Object.assign({}, lokiCollectionName, { - indices: indices, - unique: [primaryKey] - }, _lokijsHelper.LOKIJS_COLLECTION_DEFAULT_OPTIONS); - var collection = databaseState.database.addCollection(lokiCollectionName, collectionOptions); - databaseState.collections[params.collectionName] = collection; - var ret = { - databaseState: databaseState, - collection: collection - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createLokiLocalState = createLokiLocalState; -var instanceId = (0, _util.now)(); -var RxStorageInstanceLoki = /*#__PURE__*/function () { - function RxStorageInstanceLoki(databaseInstanceToken, storage, databaseName, collectionName, schema, internals, options, databaseSettings) { - var _this = this; - this.changes$ = new _rxjs.Subject(); - this.instanceId = instanceId++; - this.closed = false; - this.databaseInstanceToken = databaseInstanceToken; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - this.databaseSettings = databaseSettings; - this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); - _lokijsHelper.OPEN_LOKIJS_STORAGE_INSTANCES.add(this); - if (this.internals.leaderElector) { - /** - * To run handleRemoteRequest(), - * the instance will call its own methods. - * But these methods could have already been swapped out by a RxStorageWrapper - * so we must store the original methods here and use them instead. - */ - var copiedSelf = { - bulkWrite: this.bulkWrite.bind(this), - changeStream: this.changeStream.bind(this), - cleanup: this.cleanup.bind(this), - close: this.close.bind(this), - query: this.query.bind(this), - count: this.count.bind(this), - findDocumentsById: this.findDocumentsById.bind(this), - collectionName: this.collectionName, - databaseName: this.databaseName, - conflictResultionTasks: this.conflictResultionTasks.bind(this), - getAttachmentData: this.getAttachmentData.bind(this), - getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this), - internals: this.internals, - options: this.options, - remove: this.remove.bind(this), - resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this), - schema: this.schema - }; - this.internals.leaderElector.awaitLeadership().then(function () { - // this instance is leader now, so it has to reply to queries from other instances - (0, _util.ensureNotFalsy)(_this.internals.leaderElector).broadcastChannel.addEventListener('message', function (msg) { - return (0, _lokijsHelper.handleRemoteRequest)(copiedSelf, msg); - }); - }); - } - } - var _proto = RxStorageInstanceLoki.prototype; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this2 = this; - if (documentWrites.length === 0) { - throw (0, _rxError.newRxError)('P2', { - args: { - documentWrites: documentWrites - } - }); - } - return Promise.resolve((0, _lokijsHelper.mustUseLocalState)(_this2)).then(function (localState) { - if (!localState) { - return (0, _lokijsHelper.requestRemoteInstance)(_this2, 'bulkWrite', [documentWrites]); - } - var ret = { - success: {}, - error: {} - }; - var docsInDb = new Map(); - var docsInDbWithLokiKey = new Map(); - documentWrites.forEach(function (writeRow) { - var id = writeRow.document[_this2.primaryPath]; - var documentInDb = localState.collection.by(_this2.primaryPath, id); - if (documentInDb) { - docsInDbWithLokiKey.set(id, documentInDb); - docsInDb.set(id, (0, _lokijsHelper.stripLokiKey)(documentInDb)); - } - }); - var categorized = (0, _rxStorageHelper.categorizeBulkWriteRows)(_this2, _this2.primaryPath, docsInDb, documentWrites, context); - ret.error = categorized.errors; - categorized.bulkInsertDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this2.primaryPath]; - localState.collection.insert((0, _util.flatClone)(writeRow.document)); - ret.success[docId] = writeRow.document; - }); - categorized.bulkUpdateDocs.forEach(function (writeRow) { - var docId = writeRow.document[_this2.primaryPath]; - var documentInDbWithLokiKey = (0, _util.getFromMapOrThrow)(docsInDbWithLokiKey, docId); - var writeDoc = Object.assign({}, writeRow.document, { - $loki: documentInDbWithLokiKey.$loki - }); - localState.collection.update(writeDoc); - ret.success[docId] = writeRow.document; - }); - localState.databaseState.saveQueue.addWrite(); - if (categorized.eventBulk.events.length > 0) { - var lastState = (0, _rxStorageHelper.getNewestOfDocumentStates)(_this2.primaryPath, Object.values(ret.success)); - categorized.eventBulk.checkpoint = { - id: lastState[_this2.primaryPath], - lwt: lastState._meta.lwt - }; - _this2.changes$.next(categorized.eventBulk); - } - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - try { - var _this3 = this; - return Promise.resolve((0, _lokijsHelper.mustUseLocalState)(_this3)).then(function (localState) { - if (!localState) { - return (0, _lokijsHelper.requestRemoteInstance)(_this3, 'findDocumentsById', [ids, deleted]); - } - var ret = {}; - ids.forEach(function (id) { - var documentInDb = localState.collection.by(_this3.primaryPath, id); - if (documentInDb && (!documentInDb._deleted || deleted)) { - ret[id] = (0, _lokijsHelper.stripLokiKey)(documentInDb); - } - }); - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - try { - var _this4 = this; - return Promise.resolve((0, _lokijsHelper.mustUseLocalState)(_this4)).then(function (localState) { - if (!localState) { - return (0, _lokijsHelper.requestRemoteInstance)(_this4, 'query', [preparedQuery]); - } - var query = localState.collection.chain().find(preparedQuery.selector); - if (preparedQuery.sort) { - query = query.sort((0, _lokijsHelper.getLokiSortComparator)(_this4.schema, preparedQuery)); - } - - /** - * Offset must be used before limit in LokiJS - * @link https://github.com/techfort/LokiJS/issues/570 - */ - if (preparedQuery.skip) { - query = query.offset(preparedQuery.skip); - } - if (preparedQuery.limit) { - query = query.limit(preparedQuery.limit); - } - var foundDocuments = query.data().map(function (lokiDoc) { - return (0, _lokijsHelper.stripLokiKey)(lokiDoc); - }); - return { - documents: foundDocuments - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.count = function count(preparedQuery) { - try { - var _this5 = this; - return Promise.resolve(_this5.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { - throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.'); - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _this6 = this; - return Promise.resolve((0, _lokijsHelper.mustUseLocalState)(_this6)).then(function (localState) { - if (!localState) { - return (0, _lokijsHelper.requestRemoteInstance)(_this6, 'getChangedDocumentsSince', [limit, checkpoint]); - } - var sinceLwt = checkpoint ? checkpoint.lwt : _util.RX_META_LWT_MINIMUM; - var query = localState.collection.chain().find({ - '_meta.lwt': { - $gte: sinceLwt - } - }).sort((0, _util.getSortDocumentsByLastWriteTimeComparator)(_this6.primaryPath)); - var changedDocs = query.data(); - var first = changedDocs[0]; - if (checkpoint && first && first[_this6.primaryPath] === checkpoint.id && first._meta.lwt === checkpoint.lwt) { - changedDocs.shift(); - } - changedDocs = changedDocs.slice(0, limit); - var lastDoc = (0, _util.lastOfArray)(changedDocs); - return { - documents: changedDocs.map(function (docData) { - return (0, _lokijsHelper.stripLokiKey)(docData); - }), - checkpoint: lastDoc ? { - id: lastDoc[_this6.primaryPath], - lwt: lastDoc._meta.lwt - } : checkpoint ? checkpoint : { - id: '', - lwt: 0 - } - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.changeStream = function changeStream() { - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(minimumDeletedTime) { - try { - var _this7 = this; - return Promise.resolve((0, _lokijsHelper.mustUseLocalState)(_this7)).then(function (localState) { - if (!localState) { - return (0, _lokijsHelper.requestRemoteInstance)(_this7, 'cleanup', [minimumDeletedTime]); - } - var deleteAmountPerRun = 10; - var maxDeletionTime = (0, _util.now)() - minimumDeletedTime; - var query = localState.collection.chain().find({ - _deleted: true, - '_meta.lwt': { - $lt: maxDeletionTime - } - }).limit(deleteAmountPerRun); - var foundDocuments = query.data(); - if (foundDocuments.length > 0) { - localState.collection.remove(foundDocuments); - localState.databaseState.saveQueue.addWrite(); - } - return foundDocuments.length !== deleteAmountPerRun; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.close = function close() { - try { - var _this8 = this; - if (_this8.closed) { - return Promise.reject(new Error('already closed')); - } - _this8.closed = true; - _this8.changes$.complete(); - _lokijsHelper.OPEN_LOKIJS_STORAGE_INSTANCES["delete"](_this8); - var _temp = function () { - if (_this8.internals.localState) { - return Promise.resolve(_this8.internals.localState).then(function (localState) { - return Promise.resolve((0, _lokijsHelper.getLokiDatabase)(_this8.databaseName, _this8.databaseSettings)).then(function (dbState) { - return Promise.resolve(dbState.saveQueue.run()).then(function () { - return Promise.resolve((0, _lokijsHelper.closeLokiCollections)(_this8.databaseName, [localState.collection])).then(function () {}); - }); - }); - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.remove = function remove() { - try { - var _this9 = this; - return Promise.resolve((0, _lokijsHelper.mustUseLocalState)(_this9)).then(function (localState) { - if (!localState) { - return (0, _lokijsHelper.requestRemoteInstance)(_this9, 'remove', []); - } - localState.databaseState.database.removeCollection(localState.collection.name); - return Promise.resolve(localState.databaseState.saveQueue.run()).then(function () { - return _this9.close(); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new _rxjs.Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstanceLoki; -}(); -exports.RxStorageInstanceLoki = RxStorageInstanceLoki; -//# sourceMappingURL=rx-storage-instance-loki.js.map \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/rx-storage-instance-loki.js.map b/dist/lib/plugins/lokijs/rx-storage-instance-loki.js.map deleted file mode 100644 index d05218486dc..00000000000 --- a/dist/lib/plugins/lokijs/rx-storage-instance-loki.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-loki.js","names":["createLokiStorageInstance","storage","params","databaseSettings","instance","RxStorageInstanceLoki","databaseInstanceToken","databaseName","collectionName","schema","internals","options","addRxStorageMultiInstanceSupport","RX_STORAGE_NAME_LOKIJS","leaderElector","broadcastChannel","undefined","multiInstance","closeBefore","close","bind","removeBroadcastChannelReference","broadcastChannelRefObject","removeBefore","remove","ensureNotFalsy","awaitLeadership","then","closed","mustUseLocalState","getLokiLeaderElector","localState","createLokiLocalState","getLokiDatabase","databaseState","indices","indexes","forEach","idx","isMaybeReadonlyArray","push","primaryKey","getPrimaryFieldOfPrimaryKey","lokiCollectionName","version","collectionOptions","Object","assign","unique","LOKIJS_COLLECTION_DEFAULT_OPTIONS","collection","database","addCollection","collections","ret","instanceId","now","changes$","Subject","primaryPath","OPEN_LOKIJS_STORAGE_INSTANCES","add","copiedSelf","bulkWrite","changeStream","cleanup","query","count","findDocumentsById","conflictResultionTasks","getAttachmentData","getChangedDocumentsSince","resolveConflictResultionTask","addEventListener","msg","handleRemoteRequest","documentWrites","context","length","newRxError","args","requestRemoteInstance","success","error","docsInDb","Map","docsInDbWithLokiKey","writeRow","id","document","documentInDb","by","set","stripLokiKey","categorized","categorizeBulkWriteRows","errors","bulkInsertDocs","docId","insert","flatClone","bulkUpdateDocs","documentInDbWithLokiKey","getFromMapOrThrow","writeDoc","$loki","update","saveQueue","addWrite","eventBulk","events","lastState","getNewestOfDocumentStates","values","checkpoint","lwt","_meta","next","ids","deleted","_deleted","preparedQuery","chain","find","selector","sort","getLokiSortComparator","skip","offset","limit","foundDocuments","data","map","lokiDoc","documents","result","mode","_documentId","_attachmentId","Error","sinceLwt","RX_META_LWT_MINIMUM","$gte","getSortDocumentsByLastWriteTimeComparator","changedDocs","first","shift","slice","lastDoc","lastOfArray","docData","asObservable","minimumDeletedTime","deleteAmountPerRun","maxDeletionTime","$lt","Promise","reject","complete","dbState","run","closeLokiCollections","removeCollection","name","_taskSolution"],"sources":["../../../../src/plugins/lokijs/rx-storage-instance-loki.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n flatClone,\n now,\n ensureNotFalsy,\n isMaybeReadonlyArray,\n getFromMapOrThrow,\n getSortDocumentsByLastWriteTimeComparator,\n RX_META_LWT_MINIMUM,\n lastOfArray\n} from '../../util';\nimport { newRxError } from '../../rx-error';\nimport type {\n RxStorageInstance,\n LokiSettings,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n MangoQuery,\n LokiStorageInternals,\n RxStorageInstanceCreationParams,\n LokiDatabaseSettings,\n LokiLocalDatabaseState,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n DeepReadonly,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n RxStorageCountResult\n} from '../../types';\nimport {\n closeLokiCollections,\n getLokiDatabase,\n OPEN_LOKIJS_STORAGE_INSTANCES,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS,\n stripLokiKey,\n getLokiSortComparator,\n getLokiLeaderElector,\n requestRemoteInstance,\n mustUseLocalState,\n handleRemoteRequest,\n RX_STORAGE_NAME_LOKIJS\n} from './lokijs-helper';\nimport type {\n Collection\n} from 'lokijs';\nimport type { RxStorageLoki } from './rx-storage-lokijs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport, removeBroadcastChannelReference } from '../../rx-storage-multiinstance';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceLoki implements RxStorageInstance<\n RxDocType,\n LokiStorageInternals,\n LokiSettings,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n\n public closed = false;\n\n constructor(\n public readonly databaseInstanceToken: string,\n public readonly storage: RxStorageLoki,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: LokiStorageInternals,\n public readonly options: Readonly,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n OPEN_LOKIJS_STORAGE_INSTANCES.add(this);\n if (this.internals.leaderElector) {\n\n\n /**\n * To run handleRemoteRequest(),\n * the instance will call its own methods.\n * But these methods could have already been swapped out by a RxStorageWrapper\n * so we must store the original methods here and use them instead.\n */\n const copiedSelf: RxStorageInstance = {\n bulkWrite: this.bulkWrite.bind(this),\n changeStream: this.changeStream.bind(this),\n cleanup: this.cleanup.bind(this),\n close: this.close.bind(this),\n query: this.query.bind(this),\n count: this.count.bind(this),\n findDocumentsById: this.findDocumentsById.bind(this),\n collectionName: this.collectionName,\n databaseName: this.databaseName,\n conflictResultionTasks: this.conflictResultionTasks.bind(this),\n getAttachmentData: this.getAttachmentData.bind(this),\n getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this),\n internals: this.internals,\n options: this.options,\n remove: this.remove.bind(this),\n resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this),\n schema: this.schema\n };\n\n this.internals.leaderElector.awaitLeadership().then(() => {\n // this instance is leader now, so it has to reply to queries from other instances\n ensureNotFalsy(this.internals.leaderElector).broadcastChannel\n .addEventListener('message', (msg) => handleRemoteRequest(copiedSelf as any, msg));\n });\n }\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n if (documentWrites.length === 0) {\n throw newRxError('P2', {\n args: {\n documentWrites\n }\n });\n }\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'bulkWrite', [documentWrites]);\n }\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const docsInDb: Map[StringKeys], RxDocumentData> = new Map();\n const docsInDbWithLokiKey: Map<\n RxDocumentData[StringKeys],\n RxDocumentData & { $loki: number; }\n > = new Map();\n documentWrites.forEach(writeRow => {\n const id = writeRow.document[this.primaryPath];\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (documentInDb) {\n docsInDbWithLokiKey.set(id as any, documentInDb);\n docsInDb.set(id as any, stripLokiKey(documentInDb));\n }\n });\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDb,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n localState.collection.insert(flatClone(writeRow.document));\n ret.success[docId as any] = writeRow.document;\n });\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n const documentInDbWithLokiKey = getFromMapOrThrow(docsInDbWithLokiKey, docId as any);\n const writeDoc: any = Object.assign(\n {},\n writeRow.document,\n {\n $loki: documentInDbWithLokiKey.$loki\n }\n );\n localState.collection.update(writeDoc);\n ret.success[docId as any] = writeRow.document;\n });\n localState.databaseState.saveQueue.addWrite();\n\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(categorized.eventBulk);\n }\n\n return ret;\n }\n async findDocumentsById(ids: string[], deleted: boolean): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'findDocumentsById', [ids, deleted]);\n }\n\n const ret: RxDocumentDataById = {};\n ids.forEach(id => {\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = stripLokiKey(documentInDb);\n }\n });\n return ret;\n }\n async query(preparedQuery: MangoQuery): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'query', [preparedQuery]);\n }\n\n let query = localState.collection\n .chain()\n .find(preparedQuery.selector);\n\n if (preparedQuery.sort) {\n query = query.sort(getLokiSortComparator(this.schema, preparedQuery));\n }\n\n /**\n * Offset must be used before limit in LokiJS\n * @link https://github.com/techfort/LokiJS/issues/570\n */\n if (preparedQuery.skip) {\n query = query.offset(preparedQuery.skip);\n }\n\n if (preparedQuery.limit) {\n query = query.limit(preparedQuery.limit);\n }\n\n const foundDocuments = query.data().map(lokiDoc => stripLokiKey(lokiDoc));\n return {\n documents: foundDocuments\n };\n }\n async count(\n preparedQuery: MangoQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.');\n }\n\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint | null\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'getChangedDocumentsSince', [limit, checkpoint]);\n }\n\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const query = localState.collection\n .chain()\n .find({\n '_meta.lwt': {\n $gte: sinceLwt\n }\n })\n .sort(getSortDocumentsByLastWriteTimeComparator(this.primaryPath as any));\n let changedDocs = query.data();\n\n const first = changedDocs[0];\n if (\n checkpoint &&\n first &&\n first[this.primaryPath] === checkpoint.id &&\n first._meta.lwt === checkpoint.lwt\n ) {\n changedDocs.shift();\n }\n\n changedDocs = changedDocs.slice(0, limit);\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs.map(docData => stripLokiKey(docData)),\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath],\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'cleanup', [minimumDeletedTime]);\n }\n\n const deleteAmountPerRun = 10;\n const maxDeletionTime = now() - minimumDeletedTime;\n const query = localState.collection\n .chain()\n .find({\n _deleted: true,\n '_meta.lwt': {\n $lt: maxDeletionTime\n }\n }).limit(deleteAmountPerRun);\n const foundDocuments = query.data();\n if (foundDocuments.length > 0) {\n localState.collection.remove(foundDocuments);\n localState.databaseState.saveQueue.addWrite();\n }\n\n return foundDocuments.length !== deleteAmountPerRun;\n }\n\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n OPEN_LOKIJS_STORAGE_INSTANCES.delete(this);\n\n if (this.internals.localState) {\n const localState = await this.internals.localState;\n const dbState = await getLokiDatabase(\n this.databaseName,\n this.databaseSettings\n );\n await dbState.saveQueue.run();\n await closeLokiCollections(\n this.databaseName,\n [\n localState.collection\n ]\n );\n }\n }\n async remove(): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'remove', []);\n }\n localState.databaseState.database.removeCollection(localState.collection.name);\n await localState.databaseState.saveQueue.run();\n return this.close();\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\nexport async function createLokiLocalState(\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n if (!params.options) {\n params.options = {};\n }\n\n const databaseState = await getLokiDatabase(\n params.databaseName,\n databaseSettings\n );\n\n /**\n * Construct loki indexes from RxJsonSchema indexes.\n * TODO what about compound indexes? Are they possible in lokijs?\n */\n const indices: string[] = [];\n if (params.schema.indexes) {\n params.schema.indexes.forEach(idx => {\n if (!isMaybeReadonlyArray(idx)) {\n indices.push(idx);\n }\n });\n }\n /**\n * LokiJS has no concept of custom primary key, they use a number-id that is generated.\n * To be able to query fast by primary key, we always add an index to the primary.\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n indices.push(primaryKey as string);\n\n const lokiCollectionName = params.collectionName + '-' + params.schema.version;\n const collectionOptions: Partial>> = Object.assign(\n {},\n lokiCollectionName,\n {\n indices: indices as string[],\n unique: [primaryKey]\n } as any,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS\n );\n\n const collection: Collection = databaseState.database.addCollection(\n lokiCollectionName,\n collectionOptions as any\n );\n databaseState.collections[params.collectionName] = collection;\n const ret: LokiLocalDatabaseState = {\n databaseState,\n collection\n };\n\n return ret;\n}\n\n\nexport async function createLokiStorageInstance(\n storage: RxStorageLoki,\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise> {\n const internals: LokiStorageInternals = {};\n\n const broadcastChannelRefObject: DeepReadonly = {};\n\n\n if (params.multiInstance) {\n const leaderElector = getLokiLeaderElector(\n params.databaseInstanceToken,\n broadcastChannelRefObject,\n params.databaseName\n );\n internals.leaderElector = leaderElector;\n } else {\n // optimisation shortcut, directly create db is non multi instance.\n internals.localState = createLokiLocalState(params, databaseSettings);\n await internals.localState;\n }\n\n const instance = new RxStorageInstanceLoki(\n params.databaseInstanceToken,\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n databaseSettings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_LOKIJS,\n params,\n instance,\n internals.leaderElector ? internals.leaderElector.broadcastChannel : undefined\n );\n\n if (params.multiInstance) {\n /**\n * Clean up the broadcast-channel reference on close()\n */\n const closeBefore = instance.close.bind(instance);\n instance.close = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return closeBefore();\n };\n const removeBefore = instance.remove.bind(instance);\n instance.remove = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return removeBefore();\n };\n\n /**\n * Directly create the localState when/if the db becomes leader.\n */\n ensureNotFalsy(internals.leaderElector)\n .awaitLeadership()\n .then(() => {\n if (!instance.closed) {\n mustUseLocalState(instance);\n }\n });\n }\n\n\n return instance;\n}\n"],"mappings":";;;;;;AAAA;AAIA;AAUA;AAwBA;AAiBA;AACA;AACA;AAAmH,IA4X7FA,yBAAyB,YAAzBA,yBAAyB,CAC3CC,OAAsB,EACtBC,MAAgE,EAChEC,gBAAsC;EAAA,IACG;IAAA;MAmBzC,IAAMC,QAAQ,GAAG,IAAIC,qBAAqB,CACtCH,MAAM,CAACI,qBAAqB,EAC5BL,OAAO,EACPC,MAAM,CAACK,YAAY,EACnBL,MAAM,CAACM,cAAc,EACrBN,MAAM,CAACO,MAAM,EACbC,UAAS,EACTR,MAAM,CAACS,OAAO,EACdR,gBAAgB,CACnB;MAED,IAAAS,wDAAgC,EAC5BC,oCAAsB,EACtBX,MAAM,EACNE,QAAQ,EACRM,UAAS,CAACI,aAAa,GAAGJ,UAAS,CAACI,aAAa,CAACC,gBAAgB,GAAGC,SAAS,CACjF;MAED,IAAId,MAAM,CAACe,aAAa,EAAE;QACtB;AACR;AACA;QACQ,IAAMC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,UAAU,CAACmB,UAAU,CACxB,CACJ;cAAA;YAAA;UAAA;QAAA;MAAA;MAAA;IAET,CAAC;MAAA;IAAA;EAAA;EAAA,OACK1B,MAAM;IAAA,IAAkB;MAAA,aACiB,IAAI;MAAA,uBAAtB,IAAAK,+BAAiB,SAAM,iBAA1CE,UAAU;QAChB,IAAI,CAACA,UAAU,EAAE;UACb,OAAO,IAAAkD,mCAAqB,UAAO,QAAQ,EAAE,EAAE,CAAC;QACpD;QACAlD,UAAU,CAACG,aAAa,CAACiB,QAAQ,CAAC+G,gBAAgB,CAACnI,UAAU,CAACmB,UAAU,CAACiH,IAAI,CAAC;QAAC,uBACzEpI,UAAU,CAACG,aAAa,CAACyE,SAAS,CAACqD,GAAG,EAAE;UAC9C,OAAO,OAAK7I,KAAK,EAAE;QAAC;MAAA;IACxB,CAAC;MAAA;IAAA;EAAA;EAAA,OAEDkD,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAIX,aAAO,EAAE;EACxB,CAAC;EAAA,OACKc,4BAA4B,yCAAC4F,aAAyD,EAAiB;IAAA;EAAE,CAAC;EAAA;AAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/rx-storage-lokijs.js.map b/dist/lib/plugins/lokijs/rx-storage-lokijs.js.map deleted file mode 100644 index b23627e1354..00000000000 --- a/dist/lib/plugins/lokijs/rx-storage-lokijs.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-lokijs.js","names":["RxStorageLokiStatics","prepareQuery","_schema","mutateableQuery","flatClone","Object","keys","ensureNotFalsy","selector","length","$and","_deleted","getSortComparator","schema","query","getLokiSortComparator","getQueryMatcher","fun","doc","docWithResetDeleted","fakeCollection","data","binaryIndices","setPrototypeOf","lokijs","Collection","prototype","fakeResultSet","collection","Resultset","find","ret","filteredrows","checkpointSchema","DEFAULT_CHECKPOINT_SCHEMA","RxStorageLoki","databaseSettings","name","RX_STORAGE_NAME_LOKIJS","statics","leaderElectorByLokiDbName","Map","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","createLokiStorageInstance","getRxStorageLoki","storage"],"sources":["../../../../src/plugins/lokijs/rx-storage-lokijs.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport lokijs from 'lokijs';\nimport type {\n LokiDatabaseSettings,\n LokiSettings,\n LokiStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageStatics\n} from '../../types';\nimport {\n ensureNotFalsy,\n flatClone\n} from '../../util';\nimport {\n createLokiStorageInstance,\n RxStorageInstanceLoki\n} from './rx-storage-instance-loki';\nimport { getLokiSortComparator, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper';\nimport type { LeaderElector } from 'broadcast-channel';\n\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\n\nexport const RxStorageLokiStatics: RxStorageStatics = {\n prepareQuery(\n _schema: RxJsonSchema>,\n mutateableQuery: MangoQuery\n ) {\n mutateableQuery = flatClone(mutateableQuery);\n if (Object.keys(ensureNotFalsy(mutateableQuery.selector)).length > 0) {\n mutateableQuery.selector = {\n $and: [\n {\n _deleted: false\n },\n mutateableQuery.selector\n ]\n };\n } else {\n mutateableQuery.selector = {\n _deleted: false\n };\n }\n\n return mutateableQuery;\n },\n\n\n getSortComparator(\n schema: RxJsonSchema>,\n query: MangoQuery\n ): DeterministicSortComparator {\n return getLokiSortComparator(schema, query);\n },\n\n /**\n * Returns a function that determines if a document matches a query selector.\n * It is important to have the exact same logix as lokijs uses, to be sure\n * that the event-reduce algorithm works correct.\n * But LokisJS does not export such a function, the query logic is deep inside of\n * the Resultset prototype.\n * Because I am lazy, I do not copy paste and maintain that code.\n * Instead we create a fake Resultset and apply the prototype method Resultset.prototype.find(),\n * same with Collection.\n */\n getQueryMatcher(\n _schema: RxJsonSchema,\n query: MangoQuery\n ): QueryMatcher> {\n const fun: QueryMatcher> = (doc: RxDocumentWriteData) => {\n if (doc._deleted) {\n return false;\n }\n const docWithResetDeleted = flatClone(doc);\n docWithResetDeleted._deleted = !!docWithResetDeleted._deleted;\n\n const fakeCollection = {\n data: [docWithResetDeleted],\n binaryIndices: {}\n };\n Object.setPrototypeOf(fakeCollection, (lokijs as any).Collection.prototype);\n const fakeResultSet: any = {\n collection: fakeCollection\n };\n Object.setPrototypeOf(fakeResultSet, (lokijs as any).Resultset.prototype);\n fakeResultSet.find(query.selector, true);\n\n const ret = fakeResultSet.filteredrows.length > 0;\n return ret;\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n};\n\nexport class RxStorageLoki implements RxStorage {\n public name = RX_STORAGE_NAME_LOKIJS;\n public statics = RxStorageLokiStatics;\n\n /**\n * Create one leader elector by db name.\n * This is done inside of the storage, not globally\n * to make it easier to test multi-tab behavior.\n */\n public leaderElectorByLokiDbName: Map = new Map();\n\n constructor(\n public databaseSettings: LokiDatabaseSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n return createLokiStorageInstance(this, params, this.databaseSettings);\n }\n}\n\nexport function getRxStorageLoki(\n databaseSettings: LokiDatabaseSettings = {}\n): RxStorageLoki {\n const storage = new RxStorageLoki(databaseSettings);\n return storage;\n}\n"],"mappings":";;;;;;;;AAIA;AAaA;AAIA;AAIA;AAGA;AACA;AAEO,IAAMA,oBAAsC,GAAG;EAClDC,YAAY,wBACRC,OAAgD,EAChDC,eAAsC,EACxC;IACEA,eAAe,GAAG,IAAAC,eAAS,EAACD,eAAe,CAAC;IAC5C,IAAIE,MAAM,CAACC,IAAI,CAAC,IAAAC,oBAAc,EAACJ,eAAe,CAACK,QAAQ,CAAC,CAAC,CAACC,MAAM,GAAG,CAAC,EAAE;MAClEN,eAAe,CAAC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EDgB,gBAAgB,EAAEC;AACtB,CAAC;AAAC;AAAA,IAEWC,aAAa;EAItB;AACJ;AACA;AACA;AACA;;EAUI,uBACWC,gBAAsC,EAC/C;IAAA,KAnBKC,IAAI,GAAGC,oCAAsB;IAAA,KAC7BC,OAAO,GAAGvC,oBAAoB;IAAA,KAO9BwC,yBAAyB,GAO3B,IAAIC,GAAG,EAAE;IAAA,KAGHL,gBAAsC,GAAtCA,gBAAsC;EAC7C;EAAC;EAAA,OAEEM,qBAAqB,GAA5B,+BACIC,MAAgE,EACvB;IACzC,IAAAC,wDAAuC,EAACD,MAAM,CAAC;IAC/C,OAAO,IAAAE,gDAAyB,EAAC,IAAI,EAAEF,MAAM,EAAE,IAAI,CAACP,gBAAgB,CAAC;EACzE,CAAC;EAAA;AAAA;AAAA;AAGE,SAASU,gBAAgB,GAEf;EAAA,IADbV,gBAAsC,uEAAG,CAAC,CAAC;EAE3C,IAAMW,OAAO,GAAG,IAAIZ,aAAa,CAACC,gBAAgB,CAAC;EACnD,OAAOW,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/binary-search-bounds.js.map b/dist/lib/plugins/memory/binary-search-bounds.js.map deleted file mode 100644 index 083025848dd..00000000000 --- a/dist/lib/plugins/memory/binary-search-bounds.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"binary-search-bounds.js","names":["ge","a","y","c","l","h","i","m","x","p","undefined","gt","lt","le","eq","norm","f","length","boundGE","boundGT","boundLT","boundLE","boundEQ"],"sources":["../../../../src/plugins/memory/binary-search-bounds.ts"],"sourcesContent":["/**\n * Everything in this file was copied and adapted from\n * @link https://github.com/mikolalysenko/binary-search-bounds\n *\n * TODO We should use the original npm module instead when this bug is fixed:\n * @link https://github.com/mikolalysenko/binary-search-bounds/pull/14\n */\n\n\n\ntype Compare = ((a: T, b: T) => number | null | undefined);\n\nfunction ge(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i: number = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x: any = a[m];\n const p: any = (c !== undefined) ? c(x, y) : (x - (y as any));\n if (p >= 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction gt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p > 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction lt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p < 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction le(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p <= 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction eq(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p === 0) {\n return m;\n }\n if (p <= 0) {\n l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return -1;\n}\n\nfunction norm(a: T[], y: T, c: Compare, l: any, h: any, f: any) {\n if (typeof c === 'function') {\n return f(a, y, c, (l === undefined) ? 0 : l | 0, (h === undefined) ? a.length - 1 : h | 0);\n }\n return f(a, y, undefined, (c === undefined) ? 0 : c | 0, (l === undefined) ? a.length - 1 : l | 0);\n}\n\n\nexport function boundGE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, ge);\n}\nexport function boundGT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, gt);\n}\nexport function boundLT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, lt);\n}\nexport function boundLE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, le);\n}\nexport function boundEQ(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, eq);\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,EAAE,CAAIC,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAS,GAAGD,CAAC,GAAG,CAAC;EACrB,OAAOD,CAAC,IAAIC,CAAC,EAAE;IACX,IAAME,CAAC,GAAIH,CAAC,GAAGC,CAAC,KAAM,CAAC;IACvB,IAAMG,CAAM,GAAGP,CAAC,CAACM,CAAC,CAAC;IACnB,IAAME,CAAM,GAAIN,CAAC,KAAKO,SAAS,GAAIP,CAAC,CAACK,CAAC,EAAEN,CAAC,CAAC,GAAIM,CAAC,GAAIN,CAAU;IAC7D,IAAIO,CAAC,IAAI,CAAC,EAAE;MACRH,CAAC,GAAGC,CAAC;MAAEF,CAAC,GAAGE,CAAC,GAAG,CAAC;IACpB,CAAC,MAAM;MACHH,CAAC,GAAGG,CAAC,GAAG,CAAC;IACb;EACJ;EACA,OAAOD,CAAC;AACZ;AAEA,SAASK,EAAE,CAAIV,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAC,GAAGD,CAAC,GAAG,CAAC;EACb,OAAOD,CAAC,IAAIC,CAAC,EAAE;IACX,IAAME,CAAC,GAAIH,CAAC,GAAGC,CAAC,KAAM,CAAC;IACvB,IAAMG,CAAC,GAAGP,CAAC,CAACM,CAAC,CAAC;IACd,IAAME,CAAM,GAAIN,CAAC,KAAKO,SAA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,GAAGP,CAAC,GAAG,CAAC,EAAGC,CAAC,KAAKM,SAAS,GAAIT,CAAC,CAACgB,MAAM,GAAG,CAAC,GAAGb,CAAC,GAAG,CAAC,CAAC;AACtG;AAGO,SAASc,OAAO,CAAIjB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEL,EAAE,CAAC;AAClC;AACO,SAASmB,OAAO,CAAIlB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEM,EAAE,CAAC;AAClC;AACO,SAASS,OAAO,CAAInB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEO,EAAE,CAAC;AAClC;AACO,SAASS,OAAO,CAAIpB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEQ,EAAE,CAAC;AAClC;AACO,SAASS,OAAO,CAAIrB,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAE;EACtE,OAAOU,IAAI,CAACd,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAES,EAAE,CAAC;AAClC"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/index.js.map b/dist/lib/plugins/memory/index.js.map deleted file mode 100644 index 48a9846c054..00000000000 --- a/dist/lib/plugins/memory/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["getRxStorageMemory","settings","storage","name","statics","RxStorageDexieStatics","collectionStates","Map","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","flatClone","collectionName","schema","version","useSettings","Object","assign","options","createMemoryStorageInstance"],"sources":["../../../../src/plugins/memory/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type { RxStorageInstanceCreationParams } from '../../types';\nimport { flatClone } from '../../util';\nimport { RxStorageDexieStatics } from '../dexie/dexie-statics';\nimport type {\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\nimport {\n createMemoryStorageInstance,\n RxStorageInstanceMemory\n} from './rx-storage-instance-memory';\n\nexport function getRxStorageMemory(\n settings: RxStorageMemorySettings = {}\n): RxStorageMemory {\n\n const storage: RxStorageMemory = {\n name: 'memory',\n statics: RxStorageDexieStatics,\n collectionStates: new Map(),\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n\n // TODO we should not need to append the schema version here.\n params = flatClone(params);\n params.collectionName = params.collectionName + '-' + params.schema.version;\n\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n\n\n return createMemoryStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './memory-helper';\nexport * from './binary-search-bounds';\nexport * from './memory-types';\nexport * from './memory-indexes';\nexport * from './rx-storage-instance-memory';\n"],"mappings":";;;;;;;;;AAAA;AAEA;AACA;AAMA;AAyCA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAJA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAnCO,SAASA,kBAAkB,GAEf;EAAA,IADfC,QAAiC,uEAAG,CAAC,CAAC;EAGtC,IAAMC,OAAwB,GAAG;IAC7BC,IAAI,EAAE,QAAQ;IACdC,OAAO,EAAEC,mCAAqB;IAC9BC,gBAAgB,EAAE,IAAIC,GAAG,EAAE;IAC3BC,qBAAqB,iCACjBC,MAA0F,EAC/C;MAC3C,IAAAC,wDAAuC,EAACD,MAAM,CAAC;;MAE/C;MACAA,MAAM,GAAG,IAAAE,eAAS,EAACF,MAAM,CAAC;MAC1BA,MAAM,CAACG,cAAc,GAAGH,MAAM,CAACG,cAAc,GAAG,GAAG,GAAGH,MAAM,CAACI,MAAM,CAACC,OAAO;MAE3E,IAAMC,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFhB,QAAQ,EACRQ,MAAM,CAACS,OAAO,CACjB;MAGD,OAAO,IAAAC,oDAA2B,EAAC,IAAI,EAAEV,MAAM,EAAEM,WAAW,CAAC;IACjE;EACJ,CAAC;EAED,OAAOb,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/memory-helper.js.map b/dist/lib/plugins/memory/memory-helper.js.map deleted file mode 100644 index 09c723438d3..00000000000 --- a/dist/lib/plugins/memory/memory-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"memory-helper.js","names":["getMemoryCollectionKey","databaseName","collectionName","ensureNotRemoved","instance","internals","removed","Error","attachmentMapKey","documentId","attachmentId","SORT_BY_INDEX_STRING","a","b","indexString","putWriteRowToState","docId","state","stateByIndex","row","docInState","documents","set","document","forEach","byIndex","docsWithIndex","newIndexString","getIndexableString","pushAtSortPosition","id","doc","insertPosition","previousIndexString","prev","splice","next","newRxError","args","indexBefore","boundEQ","compareDocsWithIndex","removeDocFromState","primaryPath","schema","Object","values","positionInIndex"],"sources":["../../../../src/plugins/memory/memory-helper.ts"],"sourcesContent":["import type {\n BulkWriteRow,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport type {\n DocWithIndexString,\n MemoryStorageInternals,\n MemoryStorageInternalsByIndex\n} from './memory-types';\nimport type { RxStorageInstanceMemory } from './rx-storage-instance-memory';\nimport {\n pushAtSortPosition\n} from 'array-push-at-sort-position';\nimport { newRxError } from '../../rx-error';\nimport { boundEQ } from './binary-search-bounds';\n\n\nexport function getMemoryCollectionKey(\n databaseName: string,\n collectionName: string\n): string {\n return databaseName + '--memory--' + collectionName;\n}\n\n\nexport function ensureNotRemoved(\n instance: RxStorageInstanceMemory\n) {\n if (instance.internals.removed) {\n throw new Error('removed');\n }\n}\n\nexport function attachmentMapKey(documentId: string, attachmentId: string): string {\n return documentId + '||' + attachmentId;\n}\n\nconst SORT_BY_INDEX_STRING = (a: DocWithIndexString, b: DocWithIndexString) => {\n if (a.indexString < b.indexString) {\n return -1;\n } else {\n return 1;\n }\n};\n\n\n\nexport function putWriteRowToState(\n docId: string,\n state: MemoryStorageInternals,\n stateByIndex: MemoryStorageInternalsByIndex[],\n row: BulkWriteRow,\n docInState?: RxDocumentData\n) {\n state.documents.set(docId, row.document as any);\n stateByIndex.forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const newIndexString = byIndex.getIndexableString(row.document as any);\n const [, insertPosition] = pushAtSortPosition(\n docsWithIndex,\n {\n id: docId,\n doc: row.document,\n indexString: newIndexString\n },\n SORT_BY_INDEX_STRING,\n true\n );\n\n /**\n * Remove previous if it was in the state\n */\n if (docInState) {\n const previousIndexString = byIndex.getIndexableString(docInState);\n if (previousIndexString === newIndexString) {\n /**\n * Index not changed -> The old doc must be before or after the new one.\n */\n const prev = docsWithIndex[insertPosition - 1];\n if (prev && prev.id === docId) {\n docsWithIndex.splice(insertPosition - 1, 1);\n } else {\n const next = docsWithIndex[insertPosition + 1];\n if (next.id === docId) {\n docsWithIndex.splice(insertPosition + 1, 1);\n } else {\n throw newRxError('SNH', {\n args: {\n row,\n byIndex\n }\n });\n }\n }\n } else {\n /**\n * Index changed, we must search for the old one and remove it.\n */\n const indexBefore = boundEQ(\n docsWithIndex,\n {\n indexString: previousIndexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(indexBefore, 1);\n }\n }\n });\n}\n\n\nexport function removeDocFromState(\n primaryPath: string,\n schema: RxJsonSchema>,\n state: MemoryStorageInternals,\n doc: RxDocumentData\n) {\n const docId: string = (doc as any)[primaryPath];\n state.documents.delete(docId);\n\n Object.values(state.byIndex).forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const indexString = byIndex.getIndexableString(doc);\n\n const positionInIndex = boundEQ(\n docsWithIndex,\n {\n indexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(positionInIndex, 1);\n });\n}\n\n\nexport function compareDocsWithIndex(\n a: DocWithIndexString,\n b: DocWithIndexString\n): 1 | 0 | -1 {\n if (a.indexString < b.indexString) {\n return -1;\n } else if (a.indexString === b.indexString) {\n return 0;\n } else {\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA;AAGA;AACA;AAGO,SAASA,sBAAsB,CAClCC,YAAoB,EACpBC,cAAsB,EAChB;EACN,OAAOD,YAAY,GAAG,YAAY,GAAGC,cAAc;AACvD;AAGO,SAASC,gBAAgB,CAC5BC,QAAsC,EACxC;EACE,IAAIA,QAAQ,CAACC,SAAS,CAACC,OAAO,EAAE;IAC5B,MAAM,IAAIC,KAAK,CAAC,SAAS,CAAC;EAC9B;AACJ;AAEO,SAASC,gBAAgB,CAACC,UAAkB,EAAEC,YAAoB,EAAU;EAC/E,OAAOD,UAAU,GAAG,IAAI,GAAGC,YAAY;AAC3C;AAEA,IAAMC,oBAAoB,GAAG,SAAvBA,oBAAoB,CAAIC,CAA0B,EAAEC,CAA0B,EAAK;EACrF,IAAID,CAAC,CAAC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,CAAC,MAAM;IACH,OAAO,CAAC;EACZ;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/memory-indexes.js.map b/dist/lib/plugins/memory/memory-indexes.js.map deleted file mode 100644 index 1a7ac72c89f..00000000000 --- a/dist/lib/plugins/memory/memory-indexes.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"memory-indexes.js","names":["addIndexesToInternalsState","state","schema","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","useIndexes","indexes","map","row","Array","isArray","slice","push","forEach","indexAr","unshift","byIndex","getMemoryIndexName","index","docsWithIndex","getIndexableString","getIndexableStringMonad","changesIndex","indexName","join"],"sources":["../../../../src/plugins/memory/memory-indexes.ts"],"sourcesContent":["import { getIndexableStringMonad } from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type { RxDocumentData, RxJsonSchema } from '../../types';\nimport type { MemoryStorageInternals } from './memory-types';\n\nexport function addIndexesToInternalsState(\n state: MemoryStorageInternals,\n schema: RxJsonSchema>\n) {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const useIndexes: string[][] = !schema.indexes ? [] : schema.indexes.map(row => Array.isArray(row) ? row.slice(0) : [row]) as any;\n\n // we need this as default index\n useIndexes.push([\n primaryPath\n ]);\n\n // we need this index for running cleanup()\n useIndexes.push([\n '_meta.lwt',\n primaryPath\n ]);\n\n\n useIndexes.forEach(indexAr => {\n /**\n * Running a query will only return non-deleted documents\n * so all indexes must have the the deleted field as first index field.\n */\n indexAr.unshift('_deleted');\n\n state.byIndex[getMemoryIndexName(indexAr)] = {\n index: indexAr,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, indexAr)\n };\n });\n\n // we need this index for the changes()\n const changesIndex = [\n '_meta.lwt',\n primaryPath\n ];\n const indexName = getMemoryIndexName(changesIndex);\n state.byIndex[indexName] = {\n index: changesIndex,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, changesIndex)\n };\n\n}\n\n\nexport function getMemoryIndexName(index: string[]): string {\n return index.join(',');\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAIO,SAASA,0BAA0B,CACtCC,KAAwC,EACxCC,MAA+C,EACjD;EACE,IAAMC,WAAW,GAAG,IAAAC,2CAA2B,EAACF,MAAM,CAACG,UAAU,CAAC;EAClE,IAAMC,UAAsB,GAAG,CAACJ,MAAM,CAACK,OAAO,GAAG,EAAE,GAAGL,MAAM,CAACK,OAAO,CAACC,GAAG,CAAC,UAAAC,GAAG;IAAA,OAAIC,KAAK,CAACC,OAAO,CAACF,GAAG,CAAC,GAAGA,GAAG,CAACG,KAAK,CAAC,CAAC,CAAC,GAAG,CAACH,GAAG,CAAC;EAAA,EAAQ;;EAEjI;EACAH,UAAU,CAACO,IAAI,CAAC,CACZV,WAAW,CACd,CAAC;;EAEF;EACAG,UAAU,CAACO,IAAI,CAAC,CACZ,WAAW,EACXV,WAAW,CACd,CAAC;EAGFG,UAAU,CAACQ,OAAO,CAAC,UAAAC,OAAO,EAAI;IAC1B;AACR;AACA;AACA;IACQA,OAAO,CAACC,OAAO,CAAC,UAAU,CAAC;IAE3Bf,KAAK,CAACgB,OAAO,CAACC,kBAAkB,CAACH,OAAO,CAAC,CAAC,GAAG;MACzCI,KAAK,EAAEJ,OAAO;MACdK,aAAa,EAAE,EAAE;MACjBC,kBAAkB,EAAE,IAAAC,oCAAuB,EAACpB,MAAM,EAAEa,OAAO;IAC/D,CAAC;EACL,CAAC,CAAC;;EAEF;EACA,IAAMQ,YAAY,GAAG,CACjB,WAAW,EACXpB,WAAW,CACd;EACD,IAAMqB,SAAS,GAAGN,kBAAkB,CAACK,YAAY,CAAC;EAClDtB,KAAK,CAACgB,OAAO,CAACO,SAAS,CAAC,GAAG;IACvBL,KAAK,EAAEI,YAAY;IACnBH,aAAa,EAAE,EAAE;IACjBC,kBAAkB,EAAE,IAAAC,oCAAuB,EAACpB,MAAM,EAAEqB,YAAY;EACpE,CAAC;AAEL;AAGO,SAASL,kBAAkB,CAACC,KAAe,EAAU;EACxD,OAAOA,KAAK,CAACM,IAAI,CAAC,GAAG,CAAC;AAC1B"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/memory-types.js.map b/dist/lib/plugins/memory/memory-types.js.map deleted file mode 100644 index 8ffb477cb52..00000000000 --- a/dist/lib/plugins/memory/memory-types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n DexiePreparedQuery,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxStorage\n} from '../../types';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n /**\n * We re-use the memory state when multiple instances\n * are created with the same params.\n * If refCount beomces 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n\nexport type MemoryPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/memory/rx-storage-instance-memory.js.map b/dist/lib/plugins/memory/rx-storage-instance-memory.js.map deleted file mode 100644 index 6de7c1766e3..00000000000 --- a/dist/lib/plugins/memory/rx-storage-instance-memory.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-memory.js","names":["RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","changes$","Subject","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","bulkWrite","documentWrites","context","ensureNotRemoved","ret","success","error","categorized","categorizeBulkWriteRows","documents","errors","stateByIndex","Object","values","byIndex","bulkInsertDocs","forEach","writeRow","docId","document","putWriteRowToState","undefined","bulkUpdateDocs","get","attachmentsMap","attachments","attachmentsAdd","attachment","set","attachmentMapKey","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","eventBulk","events","length","lastState","getNewestOfDocumentStates","checkpoint","id","lwt","_meta","next","Promise","resolve","findDocumentsById","docIds","withDeleted","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","RxStorageDexieStatics","getQueryMatcher","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","concat","lowerBound","startKeys","lowerBoundString","getStartIndexStringFromLowerBound","inclusiveStart","upperBound","endKeys","upperBoundString","getStartIndexStringFromUpperBound","inclusiveEnd","indexName","getMemoryIndexName","docsWithIndex","indexOfLower","boundGE","indexString","compareDocsWithIndex","indexOfUpper","boundLE","rows","done","currentDoc","doc","push","sortComparator","getSortComparator","sort","slice","count","result","mode","getChangedDocumentsSince","sinceLwt","RX_META_LWT_MINIMUM","sinceId","boundGT","lastDoc","lastOfArray","cleanup","minimumDeletedTime","maxDeletionTime","now","removeDocFromState","PROMISE_RESOLVE_TRUE","getAttachmentData","data","getFromMapOrThrow","changeStream","asObservable","remove","removed","collectionStates","getMemoryCollectionKey","close","reject","Error","complete","refCount","PROMISE_RESOLVE_VOID","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","addIndexesToInternalsState","instance"],"sources":["../../../../src/plugins/memory/rx-storage-instance-memory.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport {\n getFromMapOrThrow,\n lastOfArray,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM\n} from '../../util';\nimport { RxStorageDexieStatics } from '../dexie/dexie-statics';\nimport {\n boundGE,\n boundGT,\n boundLE\n} from './binary-search-bounds';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes';\nimport type {\n MemoryPreparedQuery,\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotRemoved(this);\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n this.internals.documents,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n undefined\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n this.internals.documents.get(docId as any)\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n /**\n * Handle attachments\n */\n const attachmentsMap = this.internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(categorized.eventBulk);\n }\n return Promise.resolve(ret);\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise> {\n const ret: RxDocumentDataById = {};\n docIds.forEach(docId => {\n const docInDb = this.internals.documents.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n });\n return Promise.resolve(ret);\n }\n\n query(preparedQuery: MemoryPreparedQuery): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n this.schema,\n preparedQuery\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n const index: string[] | undefined = ['_deleted'].concat(queryPlanFields);\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound,\n queryPlan.inclusiveEnd\n );\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGE(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n const indexOfUpper = boundLE(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n\n\n if (\n !currentDoc ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n\n if (!queryMatcher || queryMatcher(currentDoc.doc)) {\n rows.push(currentDoc.doc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort) ||\n indexOfLower >= docsWithIndex.length\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(this.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: MemoryPreparedQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n\n const index = ['_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n ['_meta.lwt', this.primaryPath as any],\n [\n sinceLwt,\n sinceId\n ],\n false\n );\n\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n // TODO use array.slice() so we do not have to iterate here\n const rows: RxDocumentData[] = [];\n while (rows.length < limit && indexOfLower < docsWithIndex.length) {\n const currentDoc = docsWithIndex[indexOfLower];\n rows.push(currentDoc.doc);\n indexOfLower++;\n }\n\n const lastDoc = lastOfArray(rows);\n return Promise.resolve({\n documents: rows,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n });\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ],\n false\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n ensureNotRemoved(this);\n const data = getFromMapOrThrow(\n this.internals.attachments,\n attachmentMapKey(documentId, attachmentId)\n );\n return Promise.resolve(data.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.changes$.asObservable();\n }\n\n async remove(): Promise {\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(this.databaseName, this.collectionName)\n );\n await this.close();\n }\n\n close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n\n this.internals.refCount = this.internals.refCount - 1;\n if (this.internals.refCount === 0) {\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(this.databaseName, this.collectionName)\n );\n }\n\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(params.databaseName, params.collectionName);\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;;;;;;AACA;AAIA;AAIA;AACA;AAqBA;AAQA;AACA;AAKA;AAQA;AAG0B,IASbA,uBAAuB;EAWhC,iCACoBC,OAAwB,EACxBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAA4C,EAC5CC,OAAyD,EACzDC,QAAiC,EACnD;IAAA,KAXKC,MAAM,GAAG,KAAK;IAAA,KACbC,QAAQ,GAAoG,IAAIC,aAAO,EAAE;IAAA,KAG7GT,OAAwB,GAAxBA,OAAwB;IAAA,KACxBC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAA4C,GAA5CA,SAA4C;IAAA,KAC5CC,OAAyD,GAAzDA,OAAyD;IAAA,KACzDC,QAAiC,GAAjCA,QAAiC;IAEjD,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,IAAIE,SAAS,GAAGJ,OAAO,CAACoI,gBAAgB,CAAChG,GAAG,CAAC8G,aAAa,CAAC;EAC3D,IAAI,CAAC9I,SAAS,EAAE;IACZA,SAAS,GAAG;MACR+H,OAAO,EAAE,KAAK;MACdO,QAAQ,EAAE,CAAC;MACXpH,SAAS,EAAE,IAAI6H,GAAG,EAAE;MACpB7G,WAAW,EAAE2G,MAAM,CAAC9I,MAAM,CAACmC,WAAW,GAAG,IAAI6G,GAAG,EAAE,GAAGjH,SAAgB;MACrEP,OAAO,EAAE,CAAC,CAAC;MACXkH,uBAAuB,EAAE,IAAIpI,aAAO;IACxC,CAAC;IACD,IAAA2I,yCAA0B,EAAChJ,SAAS,EAAE6I,MAAM,CAAC9I,MAAM,CAAC;IACpDH,OAAO,CAACoI,gBAAgB,CAAC3F,GAAG,CAACyG,aAAa,EAAE9I,SAAS,CAAC;EAC1D,CAAC,MAAM;IACHA,SAAS,CAACsI,QAAQ,GAAGtI,SAAS,CAACsI,QAAQ,GAAG,CAAC;EAC/C;EAEA,IAAMW,QAAQ,GAAG,IAAItJ,uBAAuB,CACxCC,OAAO,EACPiJ,MAAM,CAAChJ,YAAY,EACnBgJ,MAAM,CAAC/I,cAAc,EACrB+I,MAAM,CAAC9I,MAAM,EACbC,SAAS,EACT6I,MAAM,CAAC5I,OAAO,EACdC,QAAQ,CACX;EACD,OAAOoD,OAAO,CAACC,OAAO,CAAC0F,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/lib/plugins/migration/data-migrator.js b/dist/lib/plugins/migration/data-migrator.js index 9b237d752a8..90260261164 100644 --- a/dist/lib/plugins/migration/data-migrator.js +++ b/dist/lib/plugins/migration/data-migrator.js @@ -4,7 +4,10 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOldCollection = exports._migrateDocuments = exports._getOldCollections = exports.DataMigrator = void 0; +exports.DataMigrator = void 0; +exports._getOldCollections = _getOldCollections; +exports._migrateDocuments = _migrateDocuments; +exports.createOldCollection = createOldCollection; exports.deleteOldCollection = deleteOldCollection; exports.getBatchOfOldCollection = getBatchOfOldCollection; exports.getOldCollectionDocs = getOldCollectionDocs; @@ -14,9 +17,11 @@ exports.migrateOldCollection = migrateOldCollection; exports.migratePromise = migratePromise; exports.mustMigrate = mustMigrate; exports.runStrategyIfNotNull = runStrategyIfNotNull; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _rxSchema = require("../../rx-schema"); var _rxError = require("../../rx-error"); var _hooks = require("../../hooks"); @@ -34,190 +39,6 @@ var _rxQueryHelper = require("../../rx-query-helper"); * - This could have been done in much less code which would be easier to uderstand * */ -/** - * transform documents data and save them to the new collection - * @return status-action with status and migrated document - */ -var _migrateDocuments = function _migrateDocuments(oldCollection, documentsData) { - try { - // run hooks that might mutate documentsData - return Promise.resolve(Promise.all(documentsData.map(function (docData) { - return (0, _hooks.runAsyncPluginHooks)('preMigrateDocument', { - docData: docData, - oldCollection: oldCollection - }); - }))).then(function () { - // run the migration strategies on each document - return Promise.resolve(Promise.all(documentsData.map(function (docData) { - return migrateDocumentData(oldCollection, docData); - }))).then(function (migratedDocuments) { - function _temp3() { - // run hooks - return Promise.resolve(Promise.all(actions.map(function (action) { - return (0, _hooks.runAsyncPluginHooks)('postMigrateDocument', action); - }))).then(function () { - // remove the documents from the old collection storage instance - var bulkDeleteInputData = documentsData.map(function (docData) { - var writeDeleted = (0, _util.flatClone)(docData); - writeDeleted._deleted = true; - writeDeleted._attachments = {}; - return { - previous: docData, - document: writeDeleted - }; - }); - var _temp = function () { - if (bulkDeleteInputData.length) { - return Promise.resolve(oldCollection.storageInstance.bulkWrite(bulkDeleteInputData, 'data-migrator-delete')).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(function () { - return actions; - }) : actions; - }); - } - var bulkWriteToStorageInput = []; - var actions = []; - documentsData.forEach(function (docData, idx) { - var migratedDocData = migratedDocuments[idx]; - var action = { - res: null, - type: '', - migrated: migratedDocData, - doc: docData, - oldCollection: oldCollection, - newestCollection: oldCollection.newestCollection - }; - actions.push(action); - - /** - * Determiniticly handle the revision - * so migrating the same data on multiple instances - * will result in the same output. - */ - if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) { - /** - * Data not changed by migration strategies, keep the same revision. - * This ensures that other replicated instances that did not migrate already - * will still have the same document. - */ - migratedDocData._rev = docData._rev; - } else if (migratedDocData !== null) { - /** - * data changed, increase revision height - * so replicating instances use our new document data - */ - var newHeight = (0, _util.getHeightOfRevision)(docData._rev) + 1; - var newRevision = newHeight + '-' + (0, _util.createRevision)(oldCollection.newestCollection.database.hashFunction, migratedDocData); - migratedDocData._rev = newRevision; - } - if (migratedDocData) { - /** - * save to newest collection - * notice that this data also contains the attachments data - */ - var attachmentsBefore = migratedDocData._attachments; - var saveData = migratedDocData; - saveData._attachments = attachmentsBefore; - saveData._meta.lwt = (0, _util.now)(); - bulkWriteToStorageInput.push(saveData); - action.res = saveData; - action.type = 'success'; - } else { - /** - * Migration strategy returned null - * which means we should not migrate this document, - * just drop it. - */ - action.type = 'deleted'; - } - }); - - /** - * Write the documents to the newest collection. - * We need to add as revision - * because we provide the _rev by our own - * to have deterministic revisions in case the migration - * runs on multiple nodes which must lead to the equal storage state. - */ - var _temp2 = function () { - if (bulkWriteToStorageInput.length) { - /** - * To ensure that we really keep that revision, we - * hackly insert this document via the RxStorageInstance.originalStorageInstance - * so that getWrappedStorageInstance() does not overwrite its own revision. - */ - var originalStorageInstance = oldCollection.newestCollection.storageInstance.originalStorageInstance; - return Promise.resolve(originalStorageInstance.bulkWrite(bulkWriteToStorageInput.map(function (document) { - return { - document: document - }; - }), 'data-migrator-import')).then(function () {}); - } - }(); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * deletes this.storageInstance and removes it from the database.collectionsCollection - */ -exports._migrateDocuments = _migrateDocuments; -/** - * get an array with OldCollection-instances from all existing old storage-instances - */ -var _getOldCollections = function _getOldCollections(dataMigrator) { - try { - return Promise.resolve(getOldCollectionDocs(dataMigrator)).then(function (oldColDocs) { - return Promise.all(oldColDocs.map(function (colDoc) { - if (!colDoc) { - return null; - } - return createOldCollection(colDoc.data.schema.version, colDoc.data.schema, dataMigrator); - }).filter(function (colDoc) { - return colDoc !== null; - })); - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * returns true if a migration is needed - */ -exports._getOldCollections = _getOldCollections; -var createOldCollection = function createOldCollection(version, schemaObj, dataMigrator) { - try { - var database = dataMigrator.newestCollection.database; - var storageInstanceCreationParams = { - databaseInstanceToken: database.token, - databaseName: database.name, - collectionName: dataMigrator.newestCollection.name, - schema: schemaObj, - options: dataMigrator.newestCollection.instanceCreationOptions, - multiInstance: database.multiInstance - }; - (0, _hooks.runPluginHooks)('preCreateRxStorageInstance', storageInstanceCreationParams); - return Promise.resolve(database.storage.createStorageInstance(storageInstanceCreationParams)).then(function (storageInstance) { - var ret = { - version: version, - dataMigrator: dataMigrator, - newestCollection: dataMigrator.newestCollection, - database: database, - schema: (0, _rxSchema.createRxSchema)(schemaObj, false), - storageInstance: storageInstance - }; - ret.storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(ret.database, storageInstance, schemaObj); - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createOldCollection = createOldCollection; var DataMigrator = /*#__PURE__*/function () { function DataMigrator(newestCollection, migrationStrategies) { this._migrated = false; @@ -272,18 +93,30 @@ var DataMigrator = /*#__PURE__*/function () { return _getOldCollections(_this).then(function (ret) { _this.nonMigratedOldCollections = ret; _this.allOldCollections = _this.nonMigratedOldCollections.slice(0); - var getAllDocuments = function getAllDocuments(storageInstance, schema) { - try { - var storage = _this.database.storage; - var getAllQueryPrepared = storage.statics.prepareQuery(storageInstance.schema, (0, _rxQueryHelper.normalizeMangoQuery)(schema, {})); - return Promise.resolve(storageInstance.query(getAllQueryPrepared)).then(function (queryResult) { - var allDocs = queryResult.documents; - return allDocs; - }); - } catch (e) { - return Promise.reject(e); - } - }; + var getAllDocuments = /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageInstance, schema) { + var storage, getAllQueryPrepared, queryResult, allDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + storage = _this.database.storage; + getAllQueryPrepared = storage.statics.prepareQuery(storageInstance.schema, (0, _rxQueryHelper.normalizeMangoQuery)(schema, {})); + _context.next = 4; + return storageInstance.query(getAllQueryPrepared); + case 4: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function getAllDocuments(_x, _x2) { + return _ref.apply(this, arguments); + }; + }(); var countAll = Promise.all(_this.nonMigratedOldCollections.map(function (oldCol) { return getAllDocuments(oldCol.storageInstance, oldCol.schema.jsonSchema).then(function (allDocs) { return allDocs.length; @@ -297,10 +130,10 @@ var DataMigrator = /*#__PURE__*/function () { state.total = totalCount; stateSubject.next({ collection: _this.newestCollection, - state: (0, _util.flatClone)(state) + state: (0, _utils.flatClone)(state) }); var currentCol = _this.nonMigratedOldCollections.shift(); - var currentPromise = _util.PROMISE_RESOLVE_VOID; + var currentPromise = _utils.PROMISE_RESOLVE_VOID; var _loop = function _loop() { var migrationState$ = migrateOldCollection(currentCol, batchSize); currentPromise = currentPromise.then(function () { @@ -312,7 +145,7 @@ var DataMigrator = /*#__PURE__*/function () { state.percent = Math.round(state.handled / state.total * 100); stateSubject.next({ collection: _this.newestCollection, - state: (0, _util.flatClone)(state) + state: (0, _utils.flatClone)(state) }); }, error: function error(e) { @@ -345,7 +178,7 @@ var DataMigrator = /*#__PURE__*/function () { state.percent = 100; stateSubject.next({ collection: _this.newestCollection, - state: (0, _util.flatClone)(state) + state: (0, _utils.flatClone)(state) }); stateSubject.complete(); }); @@ -359,7 +192,7 @@ var DataMigrator = /*#__PURE__*/function () { if (!this._migratePromise) { this._migratePromise = mustMigrate(this).then(function (must) { if (!must) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } else { return new Promise(function (res, rej) { var state$ = _this2.migrate(batchSize); @@ -381,6 +214,47 @@ var DataMigrator = /*#__PURE__*/function () { return DataMigrator; }(); exports.DataMigrator = DataMigrator; +function createOldCollection(_x3, _x4, _x5) { + return _createOldCollection.apply(this, arguments); +} +function _createOldCollection() { + _createOldCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(version, schemaObj, dataMigrator) { + var database, storageInstanceCreationParams, storageInstance, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + database = dataMigrator.newestCollection.database; + storageInstanceCreationParams = { + databaseInstanceToken: database.token, + databaseName: database.name, + collectionName: dataMigrator.newestCollection.name, + schema: schemaObj, + options: dataMigrator.newestCollection.instanceCreationOptions, + multiInstance: database.multiInstance + }; + (0, _hooks.runPluginHooks)('preCreateRxStorageInstance', storageInstanceCreationParams); + _context2.next = 5; + return database.storage.createStorageInstance(storageInstanceCreationParams); + case 5: + storageInstance = _context2.sent; + ret = { + version: version, + dataMigrator: dataMigrator, + newestCollection: dataMigrator.newestCollection, + database: database, + schema: (0, _rxSchema.createRxSchema)(schemaObj, false), + storageInstance: storageInstance + }; + ret.storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(ret.database, storageInstance, schemaObj); + return _context2.abrupt("return", ret); + case 9: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _createOldCollection.apply(this, arguments); +} function getOldCollectionDocs(dataMigrator) { var collectionDocKeys = (0, _rxSchema.getPreviousVersions)(dataMigrator.currentSchema.jsonSchema).map(function (version) { return dataMigrator.name + '-' + version; @@ -391,9 +265,45 @@ function getOldCollectionDocs(dataMigrator) { return Object.values(docsObj); }); } + +/** + * get an array with OldCollection-instances from all existing old storage-instances + */ +function _getOldCollections(_x6) { + return _getOldCollections2.apply(this, arguments); +} +/** + * returns true if a migration is needed + */ +function _getOldCollections2() { + _getOldCollections2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(dataMigrator) { + var oldColDocs; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return getOldCollectionDocs(dataMigrator); + case 2: + oldColDocs = _context3.sent; + return _context3.abrupt("return", Promise.all(oldColDocs.map(function (colDoc) { + if (!colDoc) { + return null; + } + return createOldCollection(colDoc.data.schema.version, colDoc.data.schema, dataMigrator); + }).filter(function (colDoc) { + return colDoc !== null; + }))); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _getOldCollections2.apply(this, arguments); +} function mustMigrate(dataMigrator) { if (dataMigrator.currentSchema.version === 0) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } return getOldCollectionDocs(dataMigrator).then(function (oldColDocs) { if (oldColDocs.length === 0) { @@ -405,26 +315,26 @@ function mustMigrate(dataMigrator) { } function runStrategyIfNotNull(oldCollection, version, docOrNull) { if (docOrNull === null) { - return _util.PROMISE_RESOLVE_NULL; + return _utils.PROMISE_RESOLVE_NULL; } else { var ret = oldCollection.dataMigrator.migrationStrategies[version](docOrNull, oldCollection); - var retPromise = (0, _util.toPromise)(ret); + var retPromise = (0, _utils.toPromise)(ret); return retPromise; } } function getBatchOfOldCollection(oldCollection, batchSize) { - var _ref; + var _ref2; var storage = oldCollection.database.storage; var storageInstance = oldCollection.storageInstance; var preparedQuery = storage.statics.prepareQuery(storageInstance.schema, { selector: {}, - sort: [(_ref = {}, _ref[oldCollection.schema.primaryPath] = 'asc', _ref)], + sort: [(_ref2 = {}, _ref2[oldCollection.schema.primaryPath] = 'asc', _ref2)], limit: batchSize, skip: 0 }); return storageInstance.query(preparedQuery).then(function (result) { return result.documents.map(function (doc) { - doc = (0, _util.flatClone)(doc); + doc = (0, _utils.flatClone)(doc); return doc; }); }); @@ -442,8 +352,8 @@ function migrateDocumentData(oldCollection, docData) { * so we just flat clone it here * and attach it to the deep cloned document data. */ - var attachmentsBefore = (0, _util.flatClone)(docData._attachments); - var mutateableDocData = (0, _util.clone)(docData); + var attachmentsBefore = (0, _utils.flatClone)(docData._attachments); + var mutateableDocData = (0, _utils.clone)(docData); mutateableDocData._attachments = attachmentsBefore; var nextVersion = oldCollection.version + 1; @@ -461,7 +371,7 @@ function migrateDocumentData(oldCollection, docData) { } return currentPromise.then(function (doc) { if (doc === null) { - return _util.PROMISE_RESOLVE_NULL; + return _utils.PROMISE_RESOLVE_NULL; } /** @@ -471,7 +381,7 @@ function migrateDocumentData(oldCollection, docData) { * TODO remove this in the major version 13.0.0 */ if (!doc._meta) { - doc._meta = (0, _util.getDefaultRxDocumentMeta)(); + doc._meta = (0, _utils.getDefaultRxDocumentMeta)(); } return doc; }); @@ -487,6 +397,149 @@ function isDocumentDataWithoutRevisionEqual(doc1, doc2) { }); return (0, _fastDeepEqual["default"])(doc1NoRev, doc2NoRev); } + +/** + * transform documents data and save them to the new collection + * @return status-action with status and migrated document + */ +function _migrateDocuments(_x7, _x8) { + return _migrateDocuments2.apply(this, arguments); +} +/** + * deletes this.storageInstance and removes it from the database.collectionsCollection + */ +function _migrateDocuments2() { + _migrateDocuments2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(oldCollection, documentsData) { + var migratedDocuments, bulkWriteToStorageInput, actions, originalStorageInstance, bulkDeleteInputData; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return Promise.all(documentsData.map(function (docData) { + return (0, _hooks.runAsyncPluginHooks)('preMigrateDocument', { + docData: docData, + oldCollection: oldCollection + }); + })); + case 2: + _context4.next = 4; + return Promise.all(documentsData.map(function (docData) { + return migrateDocumentData(oldCollection, docData); + })); + case 4: + migratedDocuments = _context4.sent; + bulkWriteToStorageInput = []; + actions = []; + documentsData.forEach(function (docData, idx) { + var migratedDocData = migratedDocuments[idx]; + var action = { + res: null, + type: '', + migrated: migratedDocData, + doc: docData, + oldCollection: oldCollection, + newestCollection: oldCollection.newestCollection + }; + actions.push(action); + + /** + * Determiniticly handle the revision + * so migrating the same data on multiple instances + * will result in the same output. + */ + if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) { + /** + * Data not changed by migration strategies, keep the same revision. + * This ensures that other replicated instances that did not migrate already + * will still have the same document. + */ + migratedDocData._rev = docData._rev; + } else if (migratedDocData !== null) { + /** + * data changed, increase revision height + * so replicating instances use our new document data + */ + var newHeight = (0, _utils.getHeightOfRevision)(docData._rev) + 1; + var newRevision = newHeight + '-' + (0, _utils.createRevision)(oldCollection.newestCollection.database.token); + migratedDocData._rev = newRevision; + } + if (migratedDocData) { + /** + * save to newest collection + * notice that this data also contains the attachments data + */ + var attachmentsBefore = migratedDocData._attachments; + var saveData = migratedDocData; + saveData._attachments = attachmentsBefore; + saveData._meta.lwt = (0, _utils.now)(); + bulkWriteToStorageInput.push(saveData); + action.res = saveData; + action.type = 'success'; + } else { + /** + * Migration strategy returned null + * which means we should not migrate this document, + * just drop it. + */ + action.type = 'deleted'; + } + }); + + /** + * Write the documents to the newest collection. + * We need to add as revision + * because we provide the _rev by our own + * to have deterministic revisions in case the migration + * runs on multiple nodes which must lead to the equal storage state. + */ + if (!bulkWriteToStorageInput.length) { + _context4.next = 12; + break; + } + /** + * To ensure that we really keep that revision, we + * hackly insert this document via the RxStorageInstance.originalStorageInstance + * so that getWrappedStorageInstance() does not overwrite its own revision. + */ + originalStorageInstance = oldCollection.newestCollection.storageInstance.originalStorageInstance; + _context4.next = 12; + return originalStorageInstance.bulkWrite(bulkWriteToStorageInput.map(function (document) { + return { + document: document + }; + }), 'data-migrator-import'); + case 12: + _context4.next = 14; + return Promise.all(actions.map(function (action) { + return (0, _hooks.runAsyncPluginHooks)('postMigrateDocument', action); + })); + case 14: + // remove the documents from the old collection storage instance + bulkDeleteInputData = documentsData.map(function (docData) { + var writeDeleted = (0, _utils.flatClone)(docData); + writeDeleted._deleted = true; + writeDeleted._attachments = {}; + return { + previous: docData, + document: writeDeleted + }; + }); + if (!bulkDeleteInputData.length) { + _context4.next = 18; + break; + } + _context4.next = 18; + return oldCollection.storageInstance.bulkWrite(bulkDeleteInputData, 'data-migrator-delete'); + case 18: + return _context4.abrupt("return", actions); + case 19: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _migrateDocuments2.apply(this, arguments); +} function deleteOldCollection(oldCollection) { return oldCollection.storageInstance.remove().then(function () { return oldCollection.database.removeCollectionDoc(oldCollection.dataMigrator.name, oldCollection.schema); diff --git a/dist/lib/plugins/migration/data-migrator.js.map b/dist/lib/plugins/migration/data-migrator.js.map index 7913b551647..c22022f24ae 100644 --- a/dist/lib/plugins/migration/data-migrator.js.map +++ b/dist/lib/plugins/migration/data-migrator.js.map @@ -1 +1 @@ -{"version":3,"file":"data-migrator.js","names":["_migrateDocuments","oldCollection","documentsData","Promise","all","map","docData","runAsyncPluginHooks","migrateDocumentData","migratedDocuments","actions","action","bulkDeleteInputData","writeDeleted","flatClone","_deleted","_attachments","previous","document","length","storageInstance","bulkWrite","bulkWriteToStorageInput","forEach","idx","migratedDocData","res","type","migrated","doc","newestCollection","push","isDocumentDataWithoutRevisionEqual","_rev","newHeight","getHeightOfRevision","newRevision","createRevision","database","hashFunction","attachmentsBefore","saveData","_meta","lwt","now","originalStorageInstance","_getOldCollections","dataMigrator","getOldCollectionDocs","oldColDocs","colDoc","createOldCollection","data","schema","version","filter","schemaObj","storageInstanceCreationParams","databaseInstanceToken","token","databaseName","name","collectionName","options","instanceCreationOptions","multiInstance","runPluginHooks","storage","createStorageInstance","ret","createRxSchema","getWrappedStorageInstance","DataMigrator","migrationStrategies","_migrated","nonMigratedOldCollections","allOldCollections","currentSchema","migrate","batchSize","newRxError","state","done","total","handled","success","deleted","percent","stateSubject","Subject","allSubject","getMigrationStateByDatabase","allList","getValue","slice","asObservable","next","then","getAllDocuments","getAllQueryPrepared","statics","prepareQuery","normalizeMangoQuery","query","queryResult","allDocs","documents","countAll","oldCol","jsonSchema","totalCount","reduce","cur","prev","collection","currentCol","shift","currentPromise","PROMISE_RESOLVE_VOID","migrationState$","migrateOldCollection","sub","subscribe","subState","Math","round","error","e","unsubscribe","c","close","complete","pipe","withCollection","migratePromise","_migratePromise","mustMigrate","must","PROMISE_RESOLVE_FALSE","rej","state$","err","collectionDocKeys","getPreviousVersions","internalStore","findDocumentsById","key","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","docsObj","Object","values","runStrategyIfNotNull","docOrNull","PROMISE_RESOLVE_NULL","retPromise","toPromise","getBatchOfOldCollection","preparedQuery","selector","sort","primaryPath","limit","skip","result","mutateableDocData","clone","nextVersion","resolve","getDefaultRxDocumentMeta","doc1","doc2","doc1NoRev","assign","undefined","doc2NoRev","deepEqual","deleteOldCollection","remove","removeCollectionDoc","_migrate","observer","allBatchesDone","handleOneBatch","batch"],"sources":["../../../../src/plugins/migration/data-migrator.ts"],"sourcesContent":["/**\n * The DataMigrator handles the documents from collections with older schemas\n * and transforms/saves them into the newest collection\n */\n/**\n * TODO this should be completely rewritten because:\n * - This could have been done in much less code which would be easier to uderstand\n *\n */\nimport {\n Subject,\n Observable\n} from 'rxjs';\nimport deepEqual from 'fast-deep-equal';\nimport {\n clone,\n toPromise,\n flatClone,\n getHeightOfRevision,\n createRevision,\n PROMISE_RESOLVE_VOID,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_NULL,\n getDefaultRxDocumentMeta,\n now\n} from '../../util';\nimport {\n createRxSchema\n} from '../../rx-schema';\nimport {\n newRxError\n} from '../../rx-error';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from '../../hooks';\nimport type {\n RxCollection,\n RxDatabase,\n MigrationState,\n NumberFunctionMap,\n OldRxCollection,\n WithAttachmentsData,\n RxJsonSchema,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n InternalStoreCollectionDocType,\n RxStorageInstance\n} from '../../types';\nimport {\n RxSchema,\n getPreviousVersions\n} from '../../rx-schema';\nimport {\n getMigrationStateByDatabase,\n MigrationStateWithCollection\n} from './migration-state';\nimport { map } from 'rxjs/operators';\nimport {\n getWrappedStorageInstance\n} from '../../rx-storage-helper';\nimport {\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION\n} from '../../rx-database-internal-store';\nimport { normalizeMangoQuery } from '../../rx-query-helper';\n\nexport class DataMigrator {\n\n constructor(\n public newestCollection: RxCollection,\n public migrationStrategies: NumberFunctionMap\n ) {\n this.currentSchema = newestCollection.schema;\n this.database = newestCollection.database;\n this.name = newestCollection.name;\n }\n\n public currentSchema: RxSchema;\n public database: RxDatabase;\n public name: string;\n\n\n private _migrated: boolean = false;\n private _migratePromise?: Promise;\n private nonMigratedOldCollections: OldRxCollection[] = [];\n private allOldCollections: OldRxCollection[] = [];\n migrate(batchSize: number = 10): Observable {\n if (this._migrated) {\n throw newRxError('DM1');\n }\n this._migrated = true;\n\n const state = {\n done: false, // true if finished\n total: 0, // will be the doc-count\n handled: 0, // amount of handled docs\n success: 0, // handled docs which succeeded\n deleted: 0, // handled docs which got deleted\n percent: 0 // percentage\n };\n\n const stateSubject: Subject = new Subject();\n\n /**\n * Add to output of RxDatabase.migrationStates\n */\n const allSubject = getMigrationStateByDatabase(this.newestCollection.database);\n const allList = allSubject.getValue().slice(0);\n allList.push(stateSubject.asObservable());\n allSubject.next(allList);\n\n /**\n * TODO this is a side-effect which might throw\n * We did this because it is not possible to create new Observer(async(...))\n * @link https://github.com/ReactiveX/rxjs/issues/4074\n * In the future the whole migration plugin should be rewritten without rxjs\n * so we do not have this problem.\n */\n (() => {\n return _getOldCollections(this)\n .then(ret => {\n this.nonMigratedOldCollections = ret;\n this.allOldCollections = this.nonMigratedOldCollections.slice(0);\n\n const getAllDocuments = async (\n storageInstance: RxStorageInstance,\n schema: RxJsonSchema\n ): Promise[]> => {\n const storage = this.database.storage;\n const getAllQueryPrepared = storage.statics.prepareQuery(\n storageInstance.schema,\n normalizeMangoQuery(\n schema,\n {}\n )\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n };\n\n const countAll: Promise = Promise.all(\n this.nonMigratedOldCollections\n .map(oldCol => getAllDocuments(\n oldCol.storageInstance,\n oldCol.schema.jsonSchema\n ).then(allDocs => allDocs.length))\n );\n return countAll;\n })\n .then(countAll => {\n const totalCount: number = countAll\n .reduce((cur, prev) => prev = cur + prev, 0);\n state.total = totalCount;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n let currentCol = this.nonMigratedOldCollections.shift();\n let currentPromise = PROMISE_RESOLVE_VOID;\n while (currentCol) {\n const migrationState$ = migrateOldCollection(\n currentCol,\n batchSize\n );\n currentPromise = currentPromise.then(() => {\n return new Promise(res => {\n const sub = migrationState$.subscribe({\n next: (subState: any) => {\n state.handled++;\n (state as any)[subState.type] = (state as any)[subState.type] + 1;\n state.percent = Math.round(state.handled / state.total * 100);\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n },\n error: (e: any) => {\n sub.unsubscribe();\n // TODO we should not have to catch here.\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n stateSubject.error(e);\n },\n complete: () => {\n if (currentCol) {\n // TODO we should not have to catch here.\n currentCol.storageInstance.close().catch(() => { });\n }\n sub.unsubscribe();\n res();\n }\n });\n });\n });\n currentCol = this.nonMigratedOldCollections.shift();\n }\n return currentPromise;\n })\n .then(() => {\n state.done = true;\n state.percent = 100;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n stateSubject.complete();\n });\n })();\n\n\n return stateSubject.pipe(\n map(withCollection => withCollection.state)\n );\n }\n\n migratePromise(batchSize: number): Promise {\n if (!this._migratePromise) {\n this._migratePromise = mustMigrate(this)\n .then(must => {\n if (!must) {\n return PROMISE_RESOLVE_FALSE;\n } else {\n return new Promise((res, rej) => {\n const state$ = this.migrate(batchSize);\n (state$ as any).subscribe(null, rej, res);\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n })\n .catch(err => {\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n throw err;\n });\n }\n });\n }\n return this._migratePromise;\n }\n}\n\nexport async function createOldCollection(\n version: number,\n schemaObj: RxJsonSchema,\n dataMigrator: DataMigrator\n): Promise {\n const database = dataMigrator.newestCollection.database;\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: dataMigrator.newestCollection.name,\n schema: schemaObj,\n options: dataMigrator.newestCollection.instanceCreationOptions,\n multiInstance: database.multiInstance\n };\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n const storageInstance = await database.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n const ret: OldRxCollection = {\n version,\n dataMigrator,\n newestCollection: dataMigrator.newestCollection,\n database,\n schema: createRxSchema(schemaObj, false),\n storageInstance\n };\n\n ret.storageInstance = getWrappedStorageInstance(\n ret.database,\n storageInstance,\n schemaObj\n );\n\n return ret;\n}\n\n\nexport function getOldCollectionDocs(\n dataMigrator: DataMigrator\n): Promise[]> {\n\n const collectionDocKeys = getPreviousVersions(dataMigrator.currentSchema.jsonSchema)\n .map(version => dataMigrator.name + '-' + version);\n\n return dataMigrator.database.internalStore.findDocumentsById(\n collectionDocKeys.map(key => getPrimaryKeyOfInternalDocument(\n key,\n INTERNAL_CONTEXT_COLLECTION\n )),\n false\n ).then(docsObj => Object.values(docsObj));\n}\n\n/**\n * get an array with OldCollection-instances from all existing old storage-instances\n */\nexport async function _getOldCollections(\n dataMigrator: DataMigrator\n): Promise {\n const oldColDocs = await getOldCollectionDocs(dataMigrator);\n\n return Promise.all(\n oldColDocs\n .map(colDoc => {\n if (!colDoc) {\n return null as any;\n }\n return createOldCollection(\n colDoc.data.schema.version,\n colDoc.data.schema,\n dataMigrator\n );\n })\n .filter(colDoc => colDoc !== null)\n );\n}\n\n\n/**\n * returns true if a migration is needed\n */\nexport function mustMigrate(dataMigrator: DataMigrator): Promise {\n if (dataMigrator.currentSchema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return getOldCollectionDocs(dataMigrator)\n .then(oldColDocs => {\n if (oldColDocs.length === 0) {\n return false;\n } else {\n return true;\n }\n });\n}\n\nexport function runStrategyIfNotNull(\n oldCollection: OldRxCollection,\n version: number,\n docOrNull: any | null\n): Promise {\n if (docOrNull === null) {\n return PROMISE_RESOLVE_NULL;\n } else {\n const ret = oldCollection.dataMigrator.migrationStrategies[version](docOrNull, oldCollection);\n const retPromise = toPromise(ret);\n return retPromise;\n }\n}\n\nexport function getBatchOfOldCollection(\n oldCollection: OldRxCollection,\n batchSize: number\n): Promise {\n const storage = oldCollection.database.storage;\n const storageInstance = oldCollection.storageInstance;\n const preparedQuery = storage.statics.prepareQuery(\n storageInstance.schema,\n {\n selector: {},\n sort: [{ [oldCollection.schema.primaryPath]: 'asc' } as any],\n limit: batchSize,\n skip: 0\n }\n );\n\n return storageInstance\n .query(preparedQuery)\n .then(result => result.documents\n .map(doc => {\n doc = flatClone(doc);\n return doc;\n })\n );\n}\n\n/**\n * runs the doc-data through all following migrationStrategies\n * so it will match the newest schema.\n * @throws Error if final doc does not match final schema or migrationStrategy crashes\n * @return final object or null if migrationStrategy deleted it\n */\nexport function migrateDocumentData(\n oldCollection: OldRxCollection,\n docData: any\n): Promise {\n /**\n * We cannot deep-clone Blob or Buffer\n * so we just flat clone it here\n * and attach it to the deep cloned document data.\n */\n const attachmentsBefore = flatClone(docData._attachments);\n const mutateableDocData = clone(docData);\n mutateableDocData._attachments = attachmentsBefore;\n\n let nextVersion = oldCollection.version + 1;\n\n // run the document through migrationStrategies\n let currentPromise = Promise.resolve(mutateableDocData);\n while (nextVersion <= oldCollection.newestCollection.schema.version) {\n const version = nextVersion;\n currentPromise = currentPromise.then(docOrNull => runStrategyIfNotNull(\n oldCollection,\n version,\n docOrNull\n ));\n nextVersion++;\n }\n\n return currentPromise.then(doc => {\n if (doc === null) {\n return PROMISE_RESOLVE_NULL;\n }\n\n /**\n * Add _meta field if missing.\n * We need this to migration documents from pre-12.0.0 state\n * to version 12.0.0. Therefore we need to add the _meta field if it is missing.\n * TODO remove this in the major version 13.0.0\n */\n if (!doc._meta) {\n doc._meta = getDefaultRxDocumentMeta();\n }\n return doc;\n });\n}\n\n\nexport function isDocumentDataWithoutRevisionEqual(doc1: T, doc2: T): boolean {\n const doc1NoRev = Object.assign({}, doc1, {\n _attachments: undefined,\n _rev: undefined\n });\n const doc2NoRev = Object.assign({}, doc2, {\n _attachments: undefined,\n _rev: undefined\n });\n return deepEqual(doc1NoRev, doc2NoRev);\n}\n\n/**\n * transform documents data and save them to the new collection\n * @return status-action with status and migrated document\n */\nexport async function _migrateDocuments(\n oldCollection: OldRxCollection,\n documentsData: any[]\n): Promise<{ type: string; doc: any; }[]> {\n\n // run hooks that might mutate documentsData\n await Promise.all(\n documentsData.map(docData => runAsyncPluginHooks(\n 'preMigrateDocument',\n {\n docData,\n oldCollection\n }\n ))\n );\n // run the migration strategies on each document\n const migratedDocuments: (any | null)[] = await Promise.all(\n documentsData.map(docData => migrateDocumentData(oldCollection, docData))\n );\n\n\n const bulkWriteToStorageInput: RxDocumentData[] = [];\n const actions: any[] = [];\n\n documentsData.forEach((docData, idx) => {\n const migratedDocData: any | null = migratedDocuments[idx];\n const action = {\n res: null as any,\n type: '',\n migrated: migratedDocData,\n doc: docData,\n oldCollection,\n newestCollection: oldCollection.newestCollection\n };\n actions.push(action);\n\n /**\n * Determiniticly handle the revision\n * so migrating the same data on multiple instances\n * will result in the same output.\n */\n if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) {\n /**\n * Data not changed by migration strategies, keep the same revision.\n * This ensures that other replicated instances that did not migrate already\n * will still have the same document.\n */\n migratedDocData._rev = docData._rev;\n } else if (migratedDocData !== null) {\n /**\n * data changed, increase revision height\n * so replicating instances use our new document data\n */\n const newHeight = getHeightOfRevision(docData._rev) + 1;\n const newRevision = newHeight + '-' + createRevision(\n oldCollection.newestCollection.database.hashFunction,\n migratedDocData\n );\n migratedDocData._rev = newRevision;\n }\n\n\n if (migratedDocData) {\n /**\n * save to newest collection\n * notice that this data also contains the attachments data\n */\n const attachmentsBefore = migratedDocData._attachments;\n const saveData: WithAttachmentsData = migratedDocData;\n saveData._attachments = attachmentsBefore;\n saveData._meta.lwt = now();\n bulkWriteToStorageInput.push(saveData);\n action.res = saveData;\n action.type = 'success';\n } else {\n /**\n * Migration strategy returned null\n * which means we should not migrate this document,\n * just drop it.\n */\n action.type = 'deleted';\n }\n });\n\n /**\n * Write the documents to the newest collection.\n * We need to add as revision\n * because we provide the _rev by our own\n * to have deterministic revisions in case the migration\n * runs on multiple nodes which must lead to the equal storage state.\n */\n if (bulkWriteToStorageInput.length) {\n /**\n * To ensure that we really keep that revision, we\n * hackly insert this document via the RxStorageInstance.originalStorageInstance\n * so that getWrappedStorageInstance() does not overwrite its own revision.\n */\n const originalStorageInstance: RxStorageInstance = (oldCollection.newestCollection.storageInstance as any).originalStorageInstance;\n await originalStorageInstance.bulkWrite(\n bulkWriteToStorageInput.map(document => ({ document })),\n 'data-migrator-import'\n );\n }\n\n // run hooks\n await Promise.all(\n actions.map(action => runAsyncPluginHooks(\n 'postMigrateDocument',\n action\n ))\n );\n\n // remove the documents from the old collection storage instance\n const bulkDeleteInputData = documentsData.map(docData => {\n const writeDeleted = flatClone(docData);\n writeDeleted._deleted = true;\n writeDeleted._attachments = {};\n return {\n previous: docData,\n document: writeDeleted\n };\n });\n\n if (bulkDeleteInputData.length) {\n await oldCollection.storageInstance.bulkWrite(\n bulkDeleteInputData,\n 'data-migrator-delete'\n );\n }\n\n return actions;\n}\n\n\n/**\n * deletes this.storageInstance and removes it from the database.collectionsCollection\n */\nexport function deleteOldCollection(\n oldCollection: OldRxCollection\n): Promise {\n return oldCollection.storageInstance.remove()\n .then(\n () => oldCollection.database.removeCollectionDoc(\n oldCollection.dataMigrator.name,\n oldCollection.schema\n )\n );\n}\n\n/**\n * runs the migration on all documents and deletes the storage instance afterwards\n */\nexport function migrateOldCollection(\n oldCollection: OldRxCollection,\n batchSize = 10\n): Observable {\n if (oldCollection._migrate) {\n // already running\n throw newRxError('DM3');\n }\n oldCollection._migrate = true;\n\n const observer = new Subject();\n\n /**\n * TODO this is a side-effect which might throw\n * @see DataMigrator.migrate()\n */\n (() => {\n let error: any;\n const allBatchesDone = () => {\n // remove this oldCollection\n return deleteOldCollection(oldCollection)\n .then(() => observer.complete());\n };\n const handleOneBatch = () => {\n return getBatchOfOldCollection(oldCollection, batchSize)\n .then(batch => {\n if (batch.length === 0) {\n allBatchesDone();\n return false;\n } else {\n return _migrateDocuments(oldCollection, batch)\n .then((actions: any[]) => actions.forEach(action => observer.next(action)))\n .catch(e => error = e)\n .then(() => true);\n }\n })\n .then(next => {\n if (!next) {\n return;\n }\n if (error) {\n observer.error(error);\n } else {\n handleOneBatch();\n }\n });\n };\n handleOneBatch();\n })();\n\n return observer.asObservable();\n}\n\nexport function migratePromise(\n oldCollection: OldRxCollection,\n batchSize?: number\n): Promise {\n if (!oldCollection._migratePromise) {\n oldCollection._migratePromise = new Promise((res, rej) => {\n const state$ = migrateOldCollection(oldCollection, batchSize);\n (state$ as any).subscribe(null, rej, res);\n });\n }\n return oldCollection._migratePromise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AASA;AAIA;AACA;AAYA;AAGA;AAGA;AAqBA;AAIA;AACA;AAGA;AAIA;AAjEA;AACA;AACA;AACA;AAC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a,OAAO,CAAC,UAAAZ,MAAM;cAAA,OAAI0K,QAAQ,CAACrF,IAAI,CAACrF,MAAM,CAAC;YAAA,EAAC;UAAA,EAAC,SACrE,CAAC,UAAAoH,CAAC;YAAA,OAAID,KAAK,GAAGC,CAAC;UAAA,EAAC,CACrB9B,IAAI,CAAC;YAAA,OAAM,IAAI;UAAA,EAAC;QACzB;MACJ,CAAC,CAAC,CACDA,IAAI,CAAC,UAAAD,IAAI,EAAI;QACV,IAAI,CAACA,IAAI,EAAE;UACP;QACJ;QACA,IAAI8B,KAAK,EAAE;UACPuD,QAAQ,CAACvD,KAAK,CAACA,KAAK,CAAC;QACzB,CAAC,MAAM;UACHyD,cAAc,EAAE;QACpB;MACJ,CAAC,CAAC;IACV,CAAC;IACDA,cAAc,EAAE;EACpB,CAAC,GAAG;EAEJ,OAAOF,QAAQ,CAACtF,YAAY,EAAE;AAClC;AAEO,SAASuC,cAAc,CAC1BrI,aAA8B,EAC9B8E,SAAkB,EACN;EACZ,IAAI,CAAC9E,aAAa,CAACsI,eAAe,EAAE;IAChCtI,aAAa,CAACsI,eAAe,GAAG,IAAIpI,OAAO,CAAC,UAACuB,GAAG,EAAEiH,GAAG,EAAK;MACtD,IAAMC,MAAM,GAAGpB,oBAAoB,CAACvH,aAAa,EAAE8E,SAAS,CAAC;MAC5D6D,MAAM,CAASlB,SAAS,CAAC,IAAI,EAAEiB,GAAG,EAAEjH,GAAG,CAAC;IAC7C,CAAC,CAAC;EACN;EACA,OAAOzB,aAAa,CAACsI,eAAe;AACxC"} \ No newline at end of file +{"version":3,"file":"data-migrator.js","names":["DataMigrator","newestCollection","migrationStrategies","_migrated","nonMigratedOldCollections","allOldCollections","currentSchema","schema","database","name","migrate","batchSize","newRxError","state","done","total","handled","success","deleted","percent","stateSubject","Subject","allSubject","getMigrationStateByDatabase","allList","getValue","slice","push","asObservable","next","_getOldCollections","then","ret","getAllDocuments","storageInstance","storage","getAllQueryPrepared","statics","prepareQuery","normalizeMangoQuery","query","queryResult","allDocs","documents","countAll","Promise","all","map","oldCol","jsonSchema","length","totalCount","reduce","cur","prev","collection","flatClone","currentCol","shift","currentPromise","PROMISE_RESOLVE_VOID","migrationState$","migrateOldCollection","res","sub","subscribe","subState","type","Math","round","error","e","unsubscribe","forEach","c","close","complete","pipe","withCollection","migratePromise","_migratePromise","mustMigrate","must","PROMISE_RESOLVE_FALSE","rej","state$","err","createOldCollection","version","schemaObj","dataMigrator","storageInstanceCreationParams","databaseInstanceToken","token","databaseName","collectionName","options","instanceCreationOptions","multiInstance","runPluginHooks","createStorageInstance","createRxSchema","getWrappedStorageInstance","getOldCollectionDocs","collectionDocKeys","getPreviousVersions","internalStore","findDocumentsById","key","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","docsObj","Object","values","oldColDocs","colDoc","data","filter","runStrategyIfNotNull","oldCollection","docOrNull","PROMISE_RESOLVE_NULL","retPromise","toPromise","getBatchOfOldCollection","preparedQuery","selector","sort","primaryPath","limit","skip","result","doc","migrateDocumentData","docData","attachmentsBefore","_attachments","mutateableDocData","clone","nextVersion","resolve","_meta","getDefaultRxDocumentMeta","isDocumentDataWithoutRevisionEqual","doc1","doc2","doc1NoRev","assign","undefined","_rev","doc2NoRev","deepEqual","_migrateDocuments","documentsData","runAsyncPluginHooks","migratedDocuments","bulkWriteToStorageInput","actions","idx","migratedDocData","action","migrated","newHeight","getHeightOfRevision","newRevision","createRevision","saveData","lwt","now","originalStorageInstance","bulkWrite","document","bulkDeleteInputData","writeDeleted","_deleted","previous","deleteOldCollection","remove","removeCollectionDoc","_migrate","observer","allBatchesDone","handleOneBatch","batch"],"sources":["../../../../src/plugins/migration/data-migrator.ts"],"sourcesContent":["/**\n * The DataMigrator handles the documents from collections with older schemas\n * and transforms/saves them into the newest collection\n */\n/**\n * TODO this should be completely rewritten because:\n * - This could have been done in much less code which would be easier to uderstand\n *\n */\nimport {\n Subject,\n Observable\n} from 'rxjs';\nimport deepEqual from 'fast-deep-equal';\nimport {\n clone,\n toPromise,\n flatClone,\n getHeightOfRevision,\n createRevision,\n PROMISE_RESOLVE_VOID,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_NULL,\n getDefaultRxDocumentMeta,\n now\n} from '../../plugins/utils';\nimport {\n createRxSchema\n} from '../../rx-schema';\nimport {\n newRxError\n} from '../../rx-error';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from '../../hooks';\nimport type {\n RxCollection,\n RxDatabase,\n MigrationState,\n NumberFunctionMap,\n OldRxCollection,\n WithAttachmentsData,\n RxJsonSchema,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n InternalStoreCollectionDocType,\n RxStorageInstance\n} from '../../types';\nimport {\n RxSchema,\n getPreviousVersions\n} from '../../rx-schema';\nimport {\n getMigrationStateByDatabase,\n MigrationStateWithCollection\n} from './migration-state';\nimport { map } from 'rxjs/operators';\nimport {\n getWrappedStorageInstance\n} from '../../rx-storage-helper';\nimport {\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION\n} from '../../rx-database-internal-store';\nimport { normalizeMangoQuery } from '../../rx-query-helper';\n\nexport class DataMigrator {\n\n constructor(\n public newestCollection: RxCollection,\n public migrationStrategies: NumberFunctionMap\n ) {\n this.currentSchema = newestCollection.schema;\n this.database = newestCollection.database;\n this.name = newestCollection.name;\n }\n\n public currentSchema: RxSchema;\n public database: RxDatabase;\n public name: string;\n\n\n private _migrated: boolean = false;\n private _migratePromise?: Promise;\n private nonMigratedOldCollections: OldRxCollection[] = [];\n private allOldCollections: OldRxCollection[] = [];\n migrate(batchSize: number = 10): Observable {\n if (this._migrated) {\n throw newRxError('DM1');\n }\n this._migrated = true;\n\n const state = {\n done: false, // true if finished\n total: 0, // will be the doc-count\n handled: 0, // amount of handled docs\n success: 0, // handled docs which succeeded\n deleted: 0, // handled docs which got deleted\n percent: 0 // percentage\n };\n\n const stateSubject: Subject = new Subject();\n\n /**\n * Add to output of RxDatabase.migrationStates\n */\n const allSubject = getMigrationStateByDatabase(this.newestCollection.database);\n const allList = allSubject.getValue().slice(0);\n allList.push(stateSubject.asObservable());\n allSubject.next(allList);\n\n /**\n * TODO this is a side-effect which might throw\n * We did this because it is not possible to create new Observer(async(...))\n * @link https://github.com/ReactiveX/rxjs/issues/4074\n * In the future the whole migration plugin should be rewritten without rxjs\n * so we do not have this problem.\n */\n (() => {\n return _getOldCollections(this)\n .then(ret => {\n this.nonMigratedOldCollections = ret;\n this.allOldCollections = this.nonMigratedOldCollections.slice(0);\n\n const getAllDocuments = async (\n storageInstance: RxStorageInstance,\n schema: RxJsonSchema\n ): Promise[]> => {\n const storage = this.database.storage;\n const getAllQueryPrepared = storage.statics.prepareQuery(\n storageInstance.schema,\n normalizeMangoQuery(\n schema,\n {}\n )\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n };\n\n const countAll: Promise = Promise.all(\n this.nonMigratedOldCollections\n .map(oldCol => getAllDocuments(\n oldCol.storageInstance,\n oldCol.schema.jsonSchema\n ).then(allDocs => allDocs.length))\n );\n return countAll;\n })\n .then(countAll => {\n const totalCount: number = countAll\n .reduce((cur, prev) => prev = cur + prev, 0);\n state.total = totalCount;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n let currentCol = this.nonMigratedOldCollections.shift();\n let currentPromise = PROMISE_RESOLVE_VOID;\n while (currentCol) {\n const migrationState$ = migrateOldCollection(\n currentCol,\n batchSize\n );\n currentPromise = currentPromise.then(() => {\n return new Promise(res => {\n const sub = migrationState$.subscribe({\n next: (subState: any) => {\n state.handled++;\n (state as any)[subState.type] = (state as any)[subState.type] + 1;\n state.percent = Math.round(state.handled / state.total * 100);\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n },\n error: (e: any) => {\n sub.unsubscribe();\n // TODO we should not have to catch here.\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n stateSubject.error(e);\n },\n complete: () => {\n if (currentCol) {\n // TODO we should not have to catch here.\n currentCol.storageInstance.close().catch(() => { });\n }\n sub.unsubscribe();\n res();\n }\n });\n });\n });\n currentCol = this.nonMigratedOldCollections.shift();\n }\n return currentPromise;\n })\n .then(() => {\n state.done = true;\n state.percent = 100;\n stateSubject.next({\n collection: this.newestCollection,\n state: flatClone(state)\n });\n stateSubject.complete();\n });\n })();\n\n\n return stateSubject.pipe(\n map(withCollection => withCollection.state)\n );\n }\n\n migratePromise(batchSize: number): Promise {\n if (!this._migratePromise) {\n this._migratePromise = mustMigrate(this)\n .then(must => {\n if (!must) {\n return PROMISE_RESOLVE_FALSE;\n } else {\n return new Promise((res, rej) => {\n const state$ = this.migrate(batchSize);\n (state$ as any).subscribe(null, rej, res);\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n })\n .catch(err => {\n this.allOldCollections.forEach(c => c.storageInstance.close().catch(() => { }));\n throw err;\n });\n }\n });\n }\n return this._migratePromise;\n }\n}\n\nexport async function createOldCollection(\n version: number,\n schemaObj: RxJsonSchema,\n dataMigrator: DataMigrator\n): Promise {\n const database = dataMigrator.newestCollection.database;\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: dataMigrator.newestCollection.name,\n schema: schemaObj,\n options: dataMigrator.newestCollection.instanceCreationOptions,\n multiInstance: database.multiInstance\n };\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n const storageInstance = await database.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n const ret: OldRxCollection = {\n version,\n dataMigrator,\n newestCollection: dataMigrator.newestCollection,\n database,\n schema: createRxSchema(schemaObj, false),\n storageInstance\n };\n\n ret.storageInstance = getWrappedStorageInstance(\n ret.database,\n storageInstance,\n schemaObj\n );\n\n return ret;\n}\n\n\nexport function getOldCollectionDocs(\n dataMigrator: DataMigrator\n): Promise[]> {\n\n const collectionDocKeys = getPreviousVersions(dataMigrator.currentSchema.jsonSchema)\n .map(version => dataMigrator.name + '-' + version);\n\n return dataMigrator.database.internalStore.findDocumentsById(\n collectionDocKeys.map(key => getPrimaryKeyOfInternalDocument(\n key,\n INTERNAL_CONTEXT_COLLECTION\n )),\n false\n ).then(docsObj => Object.values(docsObj));\n}\n\n/**\n * get an array with OldCollection-instances from all existing old storage-instances\n */\nexport async function _getOldCollections(\n dataMigrator: DataMigrator\n): Promise {\n const oldColDocs = await getOldCollectionDocs(dataMigrator);\n\n return Promise.all(\n oldColDocs\n .map(colDoc => {\n if (!colDoc) {\n return null as any;\n }\n return createOldCollection(\n colDoc.data.schema.version,\n colDoc.data.schema,\n dataMigrator\n );\n })\n .filter(colDoc => colDoc !== null)\n );\n}\n\n\n/**\n * returns true if a migration is needed\n */\nexport function mustMigrate(dataMigrator: DataMigrator): Promise {\n if (dataMigrator.currentSchema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return getOldCollectionDocs(dataMigrator)\n .then(oldColDocs => {\n if (oldColDocs.length === 0) {\n return false;\n } else {\n return true;\n }\n });\n}\n\nexport function runStrategyIfNotNull(\n oldCollection: OldRxCollection,\n version: number,\n docOrNull: any | null\n): Promise {\n if (docOrNull === null) {\n return PROMISE_RESOLVE_NULL;\n } else {\n const ret = oldCollection.dataMigrator.migrationStrategies[version](docOrNull, oldCollection);\n const retPromise = toPromise(ret);\n return retPromise;\n }\n}\n\nexport function getBatchOfOldCollection(\n oldCollection: OldRxCollection,\n batchSize: number\n): Promise {\n const storage = oldCollection.database.storage;\n const storageInstance = oldCollection.storageInstance;\n const preparedQuery = storage.statics.prepareQuery(\n storageInstance.schema,\n {\n selector: {},\n sort: [{ [oldCollection.schema.primaryPath]: 'asc' } as any],\n limit: batchSize,\n skip: 0\n }\n );\n\n return storageInstance\n .query(preparedQuery)\n .then(result => result.documents\n .map(doc => {\n doc = flatClone(doc);\n return doc;\n })\n );\n}\n\n/**\n * runs the doc-data through all following migrationStrategies\n * so it will match the newest schema.\n * @throws Error if final doc does not match final schema or migrationStrategy crashes\n * @return final object or null if migrationStrategy deleted it\n */\nexport function migrateDocumentData(\n oldCollection: OldRxCollection,\n docData: any\n): Promise {\n /**\n * We cannot deep-clone Blob or Buffer\n * so we just flat clone it here\n * and attach it to the deep cloned document data.\n */\n const attachmentsBefore = flatClone(docData._attachments);\n const mutateableDocData = clone(docData);\n mutateableDocData._attachments = attachmentsBefore;\n\n let nextVersion = oldCollection.version + 1;\n\n // run the document through migrationStrategies\n let currentPromise = Promise.resolve(mutateableDocData);\n while (nextVersion <= oldCollection.newestCollection.schema.version) {\n const version = nextVersion;\n currentPromise = currentPromise.then(docOrNull => runStrategyIfNotNull(\n oldCollection,\n version,\n docOrNull\n ));\n nextVersion++;\n }\n\n return currentPromise.then(doc => {\n if (doc === null) {\n return PROMISE_RESOLVE_NULL;\n }\n\n /**\n * Add _meta field if missing.\n * We need this to migration documents from pre-12.0.0 state\n * to version 12.0.0. Therefore we need to add the _meta field if it is missing.\n * TODO remove this in the major version 13.0.0\n */\n if (!doc._meta) {\n doc._meta = getDefaultRxDocumentMeta();\n }\n return doc;\n });\n}\n\n\nexport function isDocumentDataWithoutRevisionEqual(doc1: T, doc2: T): boolean {\n const doc1NoRev = Object.assign({}, doc1, {\n _attachments: undefined,\n _rev: undefined\n });\n const doc2NoRev = Object.assign({}, doc2, {\n _attachments: undefined,\n _rev: undefined\n });\n return deepEqual(doc1NoRev, doc2NoRev);\n}\n\n/**\n * transform documents data and save them to the new collection\n * @return status-action with status and migrated document\n */\nexport async function _migrateDocuments(\n oldCollection: OldRxCollection,\n documentsData: any[]\n): Promise<{ type: string; doc: any; }[]> {\n\n // run hooks that might mutate documentsData\n await Promise.all(\n documentsData.map(docData => runAsyncPluginHooks(\n 'preMigrateDocument',\n {\n docData,\n oldCollection\n }\n ))\n );\n // run the migration strategies on each document\n const migratedDocuments: (any | null)[] = await Promise.all(\n documentsData.map(docData => migrateDocumentData(oldCollection, docData))\n );\n\n\n const bulkWriteToStorageInput: RxDocumentData[] = [];\n const actions: any[] = [];\n\n documentsData.forEach((docData, idx) => {\n const migratedDocData: any | null = migratedDocuments[idx];\n const action = {\n res: null as any,\n type: '',\n migrated: migratedDocData,\n doc: docData,\n oldCollection,\n newestCollection: oldCollection.newestCollection\n };\n actions.push(action);\n\n /**\n * Determiniticly handle the revision\n * so migrating the same data on multiple instances\n * will result in the same output.\n */\n if (isDocumentDataWithoutRevisionEqual(docData, migratedDocData)) {\n /**\n * Data not changed by migration strategies, keep the same revision.\n * This ensures that other replicated instances that did not migrate already\n * will still have the same document.\n */\n migratedDocData._rev = docData._rev;\n } else if (migratedDocData !== null) {\n /**\n * data changed, increase revision height\n * so replicating instances use our new document data\n */\n const newHeight = getHeightOfRevision(docData._rev) + 1;\n const newRevision = newHeight + '-' + createRevision(\n oldCollection.newestCollection.database.token\n );\n migratedDocData._rev = newRevision;\n }\n\n\n if (migratedDocData) {\n /**\n * save to newest collection\n * notice that this data also contains the attachments data\n */\n const attachmentsBefore = migratedDocData._attachments;\n const saveData: WithAttachmentsData = migratedDocData;\n saveData._attachments = attachmentsBefore;\n saveData._meta.lwt = now();\n bulkWriteToStorageInput.push(saveData);\n action.res = saveData;\n action.type = 'success';\n } else {\n /**\n * Migration strategy returned null\n * which means we should not migrate this document,\n * just drop it.\n */\n action.type = 'deleted';\n }\n });\n\n /**\n * Write the documents to the newest collection.\n * We need to add as revision\n * because we provide the _rev by our own\n * to have deterministic revisions in case the migration\n * runs on multiple nodes which must lead to the equal storage state.\n */\n if (bulkWriteToStorageInput.length) {\n /**\n * To ensure that we really keep that revision, we\n * hackly insert this document via the RxStorageInstance.originalStorageInstance\n * so that getWrappedStorageInstance() does not overwrite its own revision.\n */\n const originalStorageInstance: RxStorageInstance = (oldCollection.newestCollection.storageInstance as any).originalStorageInstance;\n await originalStorageInstance.bulkWrite(\n bulkWriteToStorageInput.map(document => ({ document })),\n 'data-migrator-import'\n );\n }\n\n // run hooks\n await Promise.all(\n actions.map(action => runAsyncPluginHooks(\n 'postMigrateDocument',\n action\n ))\n );\n\n // remove the documents from the old collection storage instance\n const bulkDeleteInputData = documentsData.map(docData => {\n const writeDeleted = flatClone(docData);\n writeDeleted._deleted = true;\n writeDeleted._attachments = {};\n return {\n previous: docData,\n document: writeDeleted\n };\n });\n\n if (bulkDeleteInputData.length) {\n await oldCollection.storageInstance.bulkWrite(\n bulkDeleteInputData,\n 'data-migrator-delete'\n );\n }\n\n return actions;\n}\n\n\n/**\n * deletes this.storageInstance and removes it from the database.collectionsCollection\n */\nexport function deleteOldCollection(\n oldCollection: OldRxCollection\n): Promise {\n return oldCollection.storageInstance.remove()\n .then(\n () => oldCollection.database.removeCollectionDoc(\n oldCollection.dataMigrator.name,\n oldCollection.schema\n )\n );\n}\n\n/**\n * runs the migration on all documents and deletes the storage instance afterwards\n */\nexport function migrateOldCollection(\n oldCollection: OldRxCollection,\n batchSize = 10\n): Observable {\n if (oldCollection._migrate) {\n // already running\n throw newRxError('DM3');\n }\n oldCollection._migrate = true;\n\n const observer = new Subject();\n\n /**\n * TODO this is a side-effect which might throw\n * @see DataMigrator.migrate()\n */\n (() => {\n let error: any;\n const allBatchesDone = () => {\n // remove this oldCollection\n return deleteOldCollection(oldCollection)\n .then(() => observer.complete());\n };\n const handleOneBatch = () => {\n return getBatchOfOldCollection(oldCollection, batchSize)\n .then(batch => {\n if (batch.length === 0) {\n allBatchesDone();\n return false;\n } else {\n return _migrateDocuments(oldCollection, batch)\n .then((actions: any[]) => actions.forEach(action => observer.next(action)))\n .catch(e => error = e)\n .then(() => true);\n }\n })\n .then(next => {\n if (!next) {\n return;\n }\n if (error) {\n observer.error(error);\n } else {\n handleOneBatch();\n }\n });\n };\n handleOneBatch();\n })();\n\n return observer.asObservable();\n}\n\nexport function migratePromise(\n oldCollection: OldRxCollection,\n batchSize?: number\n): Promise {\n if (!oldCollection._migratePromise) {\n oldCollection._migratePromise = new Promise((res, rej) => {\n const state$ = migrateOldCollection(oldCollection, batchSize);\n (state$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vC,eAAe;AACxC"} \ No newline at end of file diff --git a/dist/lib/plugins/migration/index.js b/dist/lib/plugins/migration/index.js index 203617e3b78..9fe645ad792 100644 --- a/dist/lib/plugins/migration/index.js +++ b/dist/lib/plugins/migration/index.js @@ -55,7 +55,7 @@ Object.defineProperty(exports, "migratePromise", { }); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _dataMigrator = require("./data-migrator"); var _migrationState = require("./migration-state"); var DATA_MIGRATOR_BY_COLLECTION = new WeakMap(); @@ -73,7 +73,7 @@ var RxDBMigrationPlugin = { proto.migrationStates = function () { return (0, _migrationState.getMigrationStateByDatabase)(this).pipe((0, _operators.switchMap)(function (list) { return (0, _rxjs.combineLatest)(list); - }), (0, _operators.shareReplay)(_util.RXJS_SHARE_REPLAY_DEFAULTS)); + }), (0, _operators.shareReplay)(_utils.RXJS_SHARE_REPLAY_DEFAULTS)); }; }, RxCollection: function RxCollection(proto) { @@ -85,7 +85,7 @@ var RxDBMigrationPlugin = { }; proto.migrationNeeded = function () { if (this.schema.version === 0) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } return (0, _dataMigrator.mustMigrate)(this.getDataMigrator()); }; diff --git a/dist/lib/plugins/migration/index.js.map b/dist/lib/plugins/migration/index.js.map index 63b9009b232..2e9452947d8 100644 --- a/dist/lib/plugins/migration/index.js.map +++ b/dist/lib/plugins/migration/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","hooks","preDestroyRxDatabase","after","onDatabaseDestroy","prototypes","RxDatabase","proto","migrationStates","getMigrationStateByDatabase","pipe","switchMap","list","combineLatest","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","RxCollection","getDataMigrator","has","set","DataMigrator","asRxCollection","migrationStrategies","get","migrationNeeded","schema","version","PROMISE_RESOLVE_FALSE","mustMigrate"],"sources":["../../../../src/plugins/migration/index.ts"],"sourcesContent":["import {\n combineLatest,\n Observable\n} from 'rxjs';\nimport {\n shareReplay,\n switchMap\n} from 'rxjs/operators';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase,\n AllMigrationStates\n} from '../../types';\nimport { PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS } from '../../util';\nimport {\n mustMigrate,\n DataMigrator\n} from './data-migrator';\nimport {\n getMigrationStateByDatabase,\n onDatabaseDestroy\n} from './migration-state';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration',\n rxdb: true,\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n switchMap(list => combineLatest(list)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getDataMigrator = function (this: RxCollection): DataMigrator {\n if (!DATA_MIGRATOR_BY_COLLECTION.has(this)) {\n DATA_MIGRATOR_BY_COLLECTION.set(\n this,\n new DataMigrator(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n\n }\n return DATA_MIGRATOR_BY_COLLECTION.get(this) as any;\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getDataMigrator());\n };\n }\n }\n};\n\n\n// used in tests\nexport {\n _getOldCollections,\n getBatchOfOldCollection,\n migrateDocumentData,\n _migrateDocuments,\n deleteOldCollection,\n migrateOldCollection,\n migratePromise,\n DataMigrator\n} from './data-migrator';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAIA;AAUA;AACA;AAIA;AAKO,IAAMA,2BAAgE,GAAG,IAAIC,OAAO,EAAE;AAAC;AAEvF,IAAMC,mBAA6B,GAAG;EACzCC,IAAI,EAAE,WAAW;EACjBC,IAAI,EAAE,IAAI;EACVC,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEC;IACX;EACJ,CAAC;EACDC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACC,eAAe,GAAG,YAA4D;QAChF,OAAO,IAAAC,2CAA2B,EAAC,IAAI,CAAC,CAACC,IAAI,CACzC,IAAAC,oBAAS,EAAC,UAAAC,IAAI;UAAA,OAAI,IAAAC,mBAAa,EAACD,IAAI,CAAC;QAAA,EAAC,EACtC,IAAAE,sBAAW,EAACC,gCAA0B,CAAC,CAC1C;MACL,CAAC;IACL,CAAC;IACDC,YAAY,EAAE,sBAACT,KAAU,EAAK;MAC1BA,KAAK,CAACU,eAAe,GAAG,YAA4C;QAChE,IAAI,CAACrB,2BAA2B,CAACsB,GAAG,CAAC,IAAI,CAAC,EAAE;UACxCtB,2BAA2B,CAACuB,GAAG,CAC3B,IAAI,EACJ,IAAIC,0BAAY,CACZ,IAAI,CAACC,cAAc,EACnB,IAAI,CAACC,mBAAmB,CAC3B,CACJ;QAEL;QACA,OAAO1B,2BAA2B,CAAC2B,GAAG,CAAC,IAAI,CAAC;MAChD,CAAC;MACDhB,KAAK,CAACiB,eAAe,GAAG,YAA8B;QAClD,IAAI,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAOC,2BAAqB;QAChC;QACA,OAAO,IAAAC,yBAAW,EAAC,IAAI,CAACX,eAAe,EAAE,CAAC;MAC9C,CAAC;IACL;EACJ;AACJ,CAAC;;AAGD;AAAA"} \ No newline at end of file +{"version":3,"file":"index.js","names":["DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","hooks","preDestroyRxDatabase","after","onDatabaseDestroy","prototypes","RxDatabase","proto","migrationStates","getMigrationStateByDatabase","pipe","switchMap","list","combineLatest","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","RxCollection","getDataMigrator","has","set","DataMigrator","asRxCollection","migrationStrategies","get","migrationNeeded","schema","version","PROMISE_RESOLVE_FALSE","mustMigrate"],"sources":["../../../../src/plugins/migration/index.ts"],"sourcesContent":["import {\n combineLatest,\n Observable\n} from 'rxjs';\nimport {\n shareReplay,\n switchMap\n} from 'rxjs/operators';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase,\n AllMigrationStates\n} from '../../types';\nimport { PROMISE_RESOLVE_FALSE, RXJS_SHARE_REPLAY_DEFAULTS } from '../../plugins/utils';\nimport {\n mustMigrate,\n DataMigrator\n} from './data-migrator';\nimport {\n getMigrationStateByDatabase,\n onDatabaseDestroy\n} from './migration-state';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration',\n rxdb: true,\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n switchMap(list => combineLatest(list)),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getDataMigrator = function (this: RxCollection): DataMigrator {\n if (!DATA_MIGRATOR_BY_COLLECTION.has(this)) {\n DATA_MIGRATOR_BY_COLLECTION.set(\n this,\n new DataMigrator(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n\n }\n return DATA_MIGRATOR_BY_COLLECTION.get(this) as any;\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getDataMigrator());\n };\n }\n }\n};\n\n\n// used in tests\nexport {\n _getOldCollections,\n getBatchOfOldCollection,\n migrateDocumentData,\n _migrateDocuments,\n deleteOldCollection,\n migrateOldCollection,\n migratePromise,\n DataMigrator\n} from './data-migrator';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAIA;AAUA;AACA;AAIA;AAKO,IAAMA,2BAAgE,GAAG,IAAIC,OAAO,EAAE;AAAC;AAEvF,IAAMC,mBAA6B,GAAG;EACzCC,IAAI,EAAE,WAAW;EACjBC,IAAI,EAAE,IAAI;EACVC,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEC;IACX;EACJ,CAAC;EACDC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACC,eAAe,GAAG,YAA4D;QAChF,OAAO,IAAAC,2CAA2B,EAAC,IAAI,CAAC,CAACC,IAAI,CACzC,IAAAC,oBAAS,EAAC,UAAAC,IAAI;UAAA,OAAI,IAAAC,mBAAa,EAACD,IAAI,CAAC;QAAA,EAAC,EACtC,IAAAE,sBAAW,EAACC,iCAA0B,CAAC,CAC1C;MACL,CAAC;IACL,CAAC;IACDC,YAAY,EAAE,sBAACT,KAAU,EAAK;MAC1BA,KAAK,CAACU,eAAe,GAAG,YAA4C;QAChE,IAAI,CAACrB,2BAA2B,CAACsB,GAAG,CAAC,IAAI,CAAC,EAAE;UACxCtB,2BAA2B,CAACuB,GAAG,CAC3B,IAAI,EACJ,IAAIC,0BAAY,CACZ,IAAI,CAACC,cAAc,EACnB,IAAI,CAACC,mBAAmB,CAC3B,CACJ;QAEL;QACA,OAAO1B,2BAA2B,CAAC2B,GAAG,CAAC,IAAI,CAAC;MAChD,CAAC;MACDhB,KAAK,CAACiB,eAAe,GAAG,YAA8B;QAClD,IAAI,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAOC,4BAAqB;QAChC;QACA,OAAO,IAAAC,yBAAW,EAAC,IAAI,CAACX,eAAe,EAAE,CAAC;MAC9C,CAAC;IACL;EACJ;AACJ,CAAC;;AAGD;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/migration/migration-state.js b/dist/lib/plugins/migration/migration-state.js index 784ad56a12b..ea7a3db93ed 100644 --- a/dist/lib/plugins/migration/migration-state.js +++ b/dist/lib/plugins/migration/migration-state.js @@ -7,7 +7,7 @@ exports.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = void 0; exports.getMigrationStateByDatabase = getMigrationStateByDatabase; exports.onDatabaseDestroy = onDatabaseDestroy; var _rxjs = require("rxjs"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap(); exports.DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE; function getMigrationStateByDatabase(database) { @@ -15,7 +15,7 @@ function getMigrationStateByDatabase(database) { DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(database, new _rxjs.BehaviorSubject([])); } var subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database); - return (0, _util.ensureNotFalsy)(subject); + return (0, _utils.ensureNotFalsy)(subject); } /** diff --git a/dist/lib/plugins/migration/migration-state.js.map b/dist/lib/plugins/migration/migration-state.js.map index 03704cf8970..f2af94410c5 100644 --- a/dist/lib/plugins/migration/migration-state.js.map +++ b/dist/lib/plugins/migration/migration-state.js.map @@ -1 +1 @@ -{"version":3,"file":"migration-state.js","names":["DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE","WeakMap","getMigrationStateByDatabase","database","has","set","BehaviorSubject","subject","get","ensureNotFalsy","onDatabaseDestroy","complete"],"sources":["../../../../src/plugins/migration/migration-state.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Observable\n} from 'rxjs';\nimport type {\n MigrationState,\n RxCollection,\n RxDatabase\n} from '../../types';\nimport { ensureNotFalsy } from '../../util';\n\nexport type MigrationStateWithCollection = {\n collection: RxCollection;\n state: MigrationState;\n};\n\nexport const DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap[]>>();\n\nexport function getMigrationStateByDatabase(database: RxDatabase): BehaviorSubject[]> {\n if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) {\n DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(\n database,\n new BehaviorSubject[]>([])\n );\n }\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n return ensureNotFalsy(subject);\n}\n\n/**\n * Complete on database destroy\n * so people do not have to unsubscribe\n */\nexport function onDatabaseDestroy(database: RxDatabase) {\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n if (subject) {\n subject.complete();\n }\n}\n"],"mappings":";;;;;;;;AAAA;AASA;AAOO,IAAMA,wCAAwC,GAAG,IAAIC,OAAO,EAA2E;AAAC;AAExI,SAASC,2BAA2B,CAACC,QAAoB,EAA+D;EAC3H,IAAI,CAACH,wCAAwC,CAACI,GAAG,CAACD,QAAQ,CAAC,EAAE;IACzDH,wCAAwC,CAACK,GAAG,CACxCF,QAAQ,EACR,IAAIG,qBAAe,CAA6C,EAAE,CAAC,CACtE;EACL;EACA,IAAMC,OAAO,GAAGP,wCAAwC,CAACQ,GAAG,CAACL,QAAQ,CAAC;EACtE,OAAO,IAAAM,oBAAc,EAACF,OAAO,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACO,SAASG,iBAAiB,CAACP,QAAoB,EAAE;EACpD,IAAMI,OAAO,GAAGP,wCAAwC,CAACQ,GAAG,CAACL,QAAQ,CAAC;EACtE,IAAII,OAAO,EAAE;IACTA,OAAO,CAACI,QAAQ,EAAE;EACtB;AACJ"} \ No newline at end of file +{"version":3,"file":"migration-state.js","names":["DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE","WeakMap","getMigrationStateByDatabase","database","has","set","BehaviorSubject","subject","get","ensureNotFalsy","onDatabaseDestroy","complete"],"sources":["../../../../src/plugins/migration/migration-state.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Observable\n} from 'rxjs';\nimport type {\n MigrationState,\n RxCollection,\n RxDatabase\n} from '../../types';\nimport { ensureNotFalsy } from '../../plugins/utils';\n\nexport type MigrationStateWithCollection = {\n collection: RxCollection;\n state: MigrationState;\n};\n\nexport const DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE = new WeakMap[]>>();\n\nexport function getMigrationStateByDatabase(database: RxDatabase): BehaviorSubject[]> {\n if (!DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.has(database)) {\n DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.set(\n database,\n new BehaviorSubject[]>([])\n );\n }\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n return ensureNotFalsy(subject);\n}\n\n/**\n * Complete on database destroy\n * so people do not have to unsubscribe\n */\nexport function onDatabaseDestroy(database: RxDatabase) {\n const subject = DATA_MIGRATION_STATE_SUBJECT_BY_DATABASE.get(database);\n if (subject) {\n subject.complete();\n }\n}\n"],"mappings":";;;;;;;;AAAA;AASA;AAOO,IAAMA,wCAAwC,GAAG,IAAIC,OAAO,EAA2E;AAAC;AAExI,SAASC,2BAA2B,CAACC,QAAoB,EAA+D;EAC3H,IAAI,CAACH,wCAAwC,CAACI,GAAG,CAACD,QAAQ,CAAC,EAAE;IACzDH,wCAAwC,CAACK,GAAG,CACxCF,QAAQ,EACR,IAAIG,qBAAe,CAA6C,EAAE,CAAC,CACtE;EACL;EACA,IAAMC,OAAO,GAAGP,wCAAwC,CAACQ,GAAG,CAACL,QAAQ,CAAC;EACtE,OAAO,IAAAM,qBAAc,EAACF,OAAO,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACO,SAASG,iBAAiB,CAACP,QAAoB,EAAE;EACpD,IAAMI,OAAO,GAAGP,wCAAwC,CAACQ,GAAG,CAACL,QAAQ,CAAC;EACtE,IAAII,OAAO,EAAE;IACTA,OAAO,CAACI,QAAQ,EAAE;EACtB;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/adapter-check.js b/dist/lib/plugins/pouchdb/adapter-check.js deleted file mode 100644 index 497abde34aa..00000000000 --- a/dist/lib/plugins/pouchdb/adapter-check.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.POUCHDB_LOCATION = void 0; -exports.checkAdapter = checkAdapter; -var _pouchDb = require("./pouch-db"); -var _util = require("../../util"); -/** - * this plugin adds the checkAdapter-function to rxdb - * you can use it to check if the given adapter is working in the current environment - */ - -/** - * The same pouchdb-location is used on each run - * To ensure when this is run multiple times, - * there will not be many created databases - */ -var POUCHDB_LOCATION = 'rxdb-adapter-check'; -exports.POUCHDB_LOCATION = POUCHDB_LOCATION; -function checkAdapter(adapter) { - // id of the document which is stored and removed to ensure everything works - var _id = POUCHDB_LOCATION + '-' + (0, _util.randomCouchString)(12); - var pouch; - try { - pouch = new _pouchDb.PouchDB(POUCHDB_LOCATION, (0, _util.adapterObject)(adapter), { - auto_compaction: true, - revs_limit: 1 - }); - } catch (err) { - return _util.PROMISE_RESOLVE_FALSE; - } - var recoveredDoc; - return pouch.info() // ensure that we wait until db is usable - // ensure write works - .then(function () { - return pouch.put({ - _id: _id, - value: { - ok: true, - time: (0, _util.now)() - } - }); - }) - // ensure read works - .then(function () { - return pouch.get(_id); - }).then(function (doc) { - return recoveredDoc = doc; - }) - // ensure remove works - .then(function () { - return pouch.remove(recoveredDoc); - }).then(function () { - return true; - }).then(function () { - if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok) return true;else return false; - })["catch"](function () { - return false; - }); - - /** - * NOTICE: - * Do not remove the pouchdb-instance after the test - * The problem is that when this function is call in parallel, - * for example when you restore the tabs from a browser-session and open - * the same website multiple times at the same time, - * calling destroy would possibly crash the other call - */ -} -//# sourceMappingURL=adapter-check.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/adapter-check.js.map b/dist/lib/plugins/pouchdb/adapter-check.js.map deleted file mode 100644 index 0d7dd06259b..00000000000 --- a/dist/lib/plugins/pouchdb/adapter-check.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"adapter-check.js","names":["POUCHDB_LOCATION","checkAdapter","adapter","_id","randomCouchString","pouch","PouchDB","adapterObject","auto_compaction","revs_limit","err","PROMISE_RESOLVE_FALSE","recoveredDoc","info","then","put","value","ok","time","now","get","doc","remove"],"sources":["../../../../src/plugins/pouchdb/adapter-check.ts"],"sourcesContent":["/**\n * this plugin adds the checkAdapter-function to rxdb\n * you can use it to check if the given adapter is working in the current environment\n */\nimport {\n PouchDB\n} from './pouch-db';\nimport {\n adapterObject,\n now,\n PROMISE_RESOLVE_FALSE,\n randomCouchString\n} from '../../util';\nimport type {\n PouchDBInstance\n} from '../../types';\n\n/**\n * The same pouchdb-location is used on each run\n * To ensure when this is run multiple times,\n * there will not be many created databases\n */\nexport const POUCHDB_LOCATION = 'rxdb-adapter-check';\n\nexport function checkAdapter(adapter: any): Promise {\n // id of the document which is stored and removed to ensure everything works\n const _id = POUCHDB_LOCATION + '-' + randomCouchString(12);\n\n let pouch: PouchDBInstance;\n try {\n pouch = new (PouchDB as any)(\n POUCHDB_LOCATION,\n adapterObject(adapter), {\n auto_compaction: true,\n revs_limit: 1\n }\n );\n } catch (err) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let recoveredDoc: any;\n return pouch.info() // ensure that we wait until db is usable\n // ensure write works\n .then(() => pouch.put({\n _id,\n value: {\n ok: true,\n time: now()\n }\n }))\n // ensure read works\n .then(() => pouch.get(_id))\n .then(doc => recoveredDoc = doc)\n // ensure remove works\n .then(() => pouch.remove(recoveredDoc))\n .then(() => true)\n .then(() => {\n if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok)\n return true;\n else\n return false;\n })\n .catch(() => false);\n\n /**\n * NOTICE:\n * Do not remove the pouchdb-instance after the test\n * The problem is that when this function is call in parallel,\n * for example when you restore the tabs from a browser-session and open\n * the same website multiple times at the same time,\n * calling destroy would possibly crash the other call\n */\n}\n"],"mappings":";;;;;;;AAIA;AAGA;AAPA;AACA;AACA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACO,IAAMA,gBAAgB,GAAG,oBAAoB;AAAC;AAE9C,SAASC,YAAY,CAACC,OAAY,EAAgB;EACrD;EACA,IAAMC,GAAG,GAAGH,gBAAgB,GAAG,GAAG,GAAG,IAAAI,uBAAiB,EAAC,EAAE,CAAC;EAE1D,IAAIC,KAAsB;EAC1B,IAAI;IACAA,KAAK,GAAG,IAAKC,gBAAO,CAChBN,gBAAgB,EAChB,IAAAO,mBAAa,EAACL,OAAO,CAAC,EAAE;MACpBM,eAAe,EAAE,IAAI;MACrBC,UAAU,EAAE;IAChB,CAAC,CACJ;EACL,CAAC,CAAC,OAAOC,GAAG,EAAE;IACV,OAAOC,2BAAqB;EAChC;EAEA,IAAIC,YAAiB;EACrB,OAAOP,KAAK,CAACQ,IAAI,EAAE,CAAC;EAChB;EAAA,CACCC,IAAI,CAAC;IAAA,OAAMT,KAAK,CAACU,GAAG,CAAC;MAClBZ,GAAG,EAAHA,GAAG;MACHa,KAAK,EAAE;QACHC,EAAE,EAAE,IAAI;QACRC,IAAI,EAAE,IAAAC,SAAG;MACb;IACJ,CAAC,CAAC;EAAA;EACF;EAAA,CACCL,IAAI,CAAC;IAAA,OAAMT,KAAK,CAACe,GAAG,CAACjB,GAAG,CAAC;EAAA,EAAC,CAC1BW,IAAI,CAAC,UAAAO,GAAG;IAAA,OAAIT,YAAY,GAAGS,GAAG;EAAA;EAC/B;EAAA,CACCP,IAAI,CAAC;IAAA,OAAMT,KAAK,CAACiB,MAAM,CAACV,YAAY,CAAC;EAAA,EAAC,CACtCE,IAAI,CAAC;IAAA,OAAM,IAAI;EAAA,EAAC,CAChBA,IAAI,CAAC,YAAM;IACR,IAAIF,YAAY,IAAIA,YAAY,CAACI,KAAK,IAAIJ,YAAY,CAACI,KAAK,CAACC,EAAE,EAC3D,OAAO,IAAI,CAAC,KAEZ,OAAO,KAAK;EACpB,CAAC,CAAC,SACI,CAAC;IAAA,OAAM,KAAK;EAAA,EAAC;;EAEvB;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/custom-events-plugin.js b/dist/lib/plugins/pouchdb/custom-events-plugin.js deleted file mode 100644 index 0551d556ce4..00000000000 --- a/dist/lib/plugins/pouchdb/custom-events-plugin.js +++ /dev/null @@ -1,629 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.EVENT_EMITTER_BY_POUCH_INSTANCE = void 0; -exports.addCustomEventsPluginToPouch = addCustomEventsPluginToPouch; -exports.changeEventToNormal = changeEventToNormal; -exports.eventEmitDataToStorageEvents = void 0; -exports.getCustomEventEmitterByPouch = getCustomEventEmitterByPouch; -var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); -var _rxjs = require("rxjs"); -var _util = require("../../util"); -var _rxError = require("../../rx-error"); -var _pouchdbHelper = require("./pouchdb-helper"); -/* - * Instead of listening to pouch.changes, - * we overwrite pouchdbs bulkDocs() - * and create our own event stream, this will work more reliable - * and has less strange behaviors. - * Also we can better define what data we need for our events. - * @link http://jsbin.com/pagebi/1/edit?js,output - * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273 - * @link https://hasura.io/blog/couchdb-style-conflict-resolution-rxdb-hasura/ - */ -var eventEmitDataToStorageEvents = function eventEmitDataToStorageEvents(pouchDBInstance, primaryPath, emitData) { - try { - var ret = []; - var _temp7 = function () { - if (!emitData.writeOptions.custom && emitData.writeOptions.hasOwnProperty('new_edits') && emitData.writeOptions.new_edits === false) { - return Promise.resolve(Promise.all(emitData.writeDocs.map(function (writeDoc) { - try { - var id = writeDoc._id; - writeDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(primaryPath, writeDoc); - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeDoc._attachments)).then(function (_writeAttachmentsToAt) { - writeDoc._attachments = _writeAttachmentsToAt; - var previousDoc = emitData.previousDocs.get(id); - if (previousDoc) { - previousDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(primaryPath, previousDoc); - } - if (previousDoc) { - var parsedRevPrevious = (0, _util.parseRevision)(previousDoc._rev); - var parsedRevNew = (0, _util.parseRevision)(writeDoc._rev); - if (parsedRevPrevious.height > parsedRevNew.height || - /** - * If the revision height is equal, - * we determine the higher hash as winner. - */ - - parsedRevPrevious.height === parsedRevNew.height && parsedRevPrevious.hash > parsedRevNew.hash) { - /** - * The newly added document was not the latest revision - * so we drop the write. - * With plain PouchDB it makes sense to store conflicting branches of the document - * but RxDB assumes that the conflict is resolved directly. - */ - return; - } - } - if (!previousDoc && writeDoc._deleted) { - // deleted document was added as revision - return; - } - if (previousDoc && previousDoc._deleted && writeDoc._deleted) { - // delete document was deleted again - return; - } - var event; - if ((!previousDoc || previousDoc._deleted) && !writeDoc._deleted) { - // was insert - event = { - operation: 'INSERT', - doc: writeDoc, - id: id, - previous: null - }; - } else if (writeDoc._deleted && previousDoc && !previousDoc._deleted) { - // was delete - previousDoc._rev = writeDoc._rev; - event = { - operation: 'DELETE', - doc: writeDoc, - id: id, - previous: previousDoc - }; - } else if (previousDoc) { - // was update - event = { - operation: 'UPDATE', - doc: writeDoc, - id: id, - previous: previousDoc - }; - } else { - throw (0, _rxError.newRxError)('SNH', { - args: { - writeDoc: writeDoc - } - }); - } - var changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event, emitData.startTime, emitData.endTime); - ret.push(changeEvent); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); // eslint-disable-next-line brace-style - } else { - var _temp8 = function () { - if (!emitData.writeOptions.custom || emitData.writeOptions.custom && !emitData.writeOptions.custom.writeRowById) { - var writeDocsById = new Map(); - emitData.writeDocs.forEach(function (writeDoc) { - return writeDocsById.set(writeDoc._id, writeDoc); - }); - return Promise.resolve(Promise.all(emitData.writeResult.map(function (resultRow) { - try { - var id = resultRow.id; - if (id.startsWith(_pouchdbHelper.POUCHDB_DESIGN_PREFIX) || id.startsWith(_pouchdbHelper.POUCHDB_LOCAL_PREFIX)) { - return Promise.resolve(); - } - var writeDoc = (0, _util.getFromMapOrThrow)(writeDocsById, resultRow.id); - writeDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(primaryPath, writeDoc); - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeDoc._attachments)).then(function (_writeAttachmentsToAt2) { - writeDoc._attachments = _writeAttachmentsToAt2; - writeDoc = (0, _util.flatClone)(writeDoc); - writeDoc._rev = resultRow.rev; - var event = (0, _pouchdbHelper.pouchChangeRowToChangeEvent)(primaryPath, writeDoc); - var changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event); - ret.push(changeEvent); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } else { - var writeMap = emitData.writeOptions.custom.writeRowById; - return Promise.resolve(Promise.all(emitData.writeResult.map(function (resultRow) { - try { - if (resultRow.error) { - return Promise.resolve(); - } - var id = resultRow.id; - var writeRow = (0, _util.getFromMapOrThrow)(writeMap, id); - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeRow.document._attachments)).then(function (attachments) { - function _temp11() { - if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) {} else { - var changeEvent = changeEventToNormal(pouchDBInstance, (0, _util.ensureNotFalsy)(emitData.writeOptions.custom).primaryPath, event, emitData.startTime, emitData.endTime); - ret.push(changeEvent); - } - } - var newDoc = Object.assign({}, writeRow.document, { - _attachments: attachments, - _rev: resultRow.rev - }); - var event; - var _temp10 = function () { - if (!writeRow.previous || writeRow.previous._deleted) { - // was insert - event = { - operation: 'INSERT', - doc: newDoc, - id: id, - previous: null - }; - } else { - var _temp12 = function () { - if (writeRow.document._deleted) { - // was delete - // we need to add the new revision to the previous doc - // so that the eventkey is calculated correctly. - // Is this a hack? idk. - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeRow.previous._attachments)).then(function (attachmentsInner) { - var previousDoc = Object.assign({}, writeRow.previous, { - _attachments: attachmentsInner - }); - event = { - operation: 'DELETE', - doc: writeRow.document, - id: resultRow.id, - previous: previousDoc - }; - }); - } else { - // was update - event = { - operation: 'UPDATE', - doc: newDoc, - id: resultRow.id, - previous: writeRow.previous - }; - } - }(); - if (_temp12 && _temp12.then) return _temp12.then(function () {}); - } - }(); - return _temp10 && _temp10.then ? _temp10.then(_temp11) : _temp11(_temp10); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } - }(); - if (_temp8 && _temp8.then) return _temp8.then(function () {}); - } - }(); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () { - return ret; - }) : ret); - } catch (e) { - return Promise.reject(e); - } -}; -exports.eventEmitDataToStorageEvents = eventEmitDataToStorageEvents; -// ensure only added once -var addedToPouch = false; -var EVENT_EMITTER_BY_POUCH_INSTANCE = new Map(); -exports.EVENT_EMITTER_BY_POUCH_INSTANCE = EVENT_EMITTER_BY_POUCH_INSTANCE; -function getCustomEventEmitterByPouch(pouch) { - var key = [pouch.__opts.name, pouch.adapter].join('|'); - var emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key); - if (!emitter) { - emitter = { - subject: new _rxjs.Subject() - }; - EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter); - } - return emitter; -} - -/** - * Counter, used to debug stuff. - */ -var i = 0; - -/** - * Because we cannot force pouchdb to await bulkDocs runs - * inside of a transaction, like done with the other RxStorage implementations, - * we have to ensure the calls to bulkDocs() do not run in parallel. - * - * TODO this is somehow a hack. Instead of doing that, inspect how - * PouchDB runs bulkDocs internally and adapt that transaction handling. - */ -var BULK_DOC_RUN_QUEUE = new WeakMap(); - -/** - * PouchDB is like a minefield, - * where stuff randomly does not work dependent on some conditions. - * So instead of doing plain writes, - * we hack into the bulkDocs() function - * and adjust the behavior accordingly. - */ -function addCustomEventsPluginToPouch() { - if (addedToPouch) { - return; - } - addedToPouch = true; - var oldBulkDocs = _pouchdbCore["default"].prototype.bulkDocs; - - /** - * Ensure we do not run bulkDocs() in parallel on the same PouchDB instance. - */ - var newBulkDocs = function newBulkDocs(body, options, callback) { - var _this = this; - /** - * Normalize inputs - * because there are many ways to call pouchdb.bulkDocs() - */ - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } - - /** - * PouchDB internal requests - * must still be handled normally - * to decrease the likelyness of bugs. - */ - var internalPouches = ['_replicator', '_users', 'pouch__all_dbs__']; - if (internalPouches.includes(this.name) || this.name.includes('-mrview-')) { - return oldBulkDocs.call(this, body, options, function (err, result) { - if (err) { - if (callback) { - callback(err, null); - } - } else { - if (callback) { - callback(null, result); - } - } - }); - } - var queue = BULK_DOC_RUN_QUEUE.get(this); - if (!queue) { - queue = _util.PROMISE_RESOLVE_VOID; - } - queue = queue.then(function () { - try { - return Promise.resolve(newBulkDocsInner.bind(_this)(body, options, callback)); - } catch (e) { - return Promise.reject(e); - } - }); - BULK_DOC_RUN_QUEUE.set(this, queue); - return queue; - }; - var newBulkDocsInner = function newBulkDocsInner(body, options, callback) { - try { - var _temp3 = function _temp3() { - /** - * Custom handling if the call came from RxDB (options.custom is set). - */ - var usePouchResult = []; - var hasNonErrorWrite = false; - if (options.custom && options.hasOwnProperty('new_edits') && options.new_edits === false) { - /** - * Reset the write docs array, - * because we only write non-conflicting documents. - */ - docs = []; - var writeRowById = options.custom.writeRowById; - var insertDocsById = options.custom.insertDocsById; - Array.from(writeRowById.entries()).forEach(function (_ref) { - var id = _ref[0], - writeRow = _ref[1]; - var previousRev = writeRow.previous ? writeRow.previous._rev : null; - var newRev = (0, _util.parseRevision)(writeRow.document._rev); - var docInDb = previousDocsInDb.get(id); - var docInDbRev = docInDb ? docInDb._rev : null; - if (docInDbRev !== previousRev) { - // we have a conflict - usePouchResult.push({ - error: true, - id: id, - status: 409 - }); - } else { - var useRevisions = { - start: newRev.height, - ids: docInDb ? docInDb._revisions.ids.slice(0) : [] - }; - useRevisions.ids.unshift(newRev.hash); - var useNewRev = useRevisions.start + '-' + newRev.hash; - hasNonErrorWrite = true; - var writeToPouchDocData = Object.assign({}, insertDocsById.get(id), { - _revisions: useRevisions, - _rev: useNewRev - }); - docs.push(writeToPouchDocData); - usePouchResult.push({ - ok: true, - id: id, - rev: writeRow.document._rev - }); - } - }); - - /** - * Optimization shortcut, - * if all document writes were conflict errors, - * we can skip directly. - */ - if (!hasNonErrorWrite) { - return usePouchResult; - } - } - - /** - * pouchdb calls this function again with transformed input. - * This would lead to duplicate events. So we marks the deeper calls via the options - * parameter and do not emit events if it is set. - */ - var deeperOptions = (0, _util.flatClone)(options); - deeperOptions.isDeeper = true; - var callReturn; - var callPromise = new Promise(function (res, rej) { - /** - * The emitted EventBulk from the write to the pouchdb, needs to contain a checkpoint field. - * Because PouchDB works on sequence number to sort changes, - * we have to fetch the latest sequence number out of the events because it - * is not possible to that that from pouch.bulkDocs(). - */ - var docIds = new Set(docs.map(function (d) { - return d._id; - })); - var heighestSequence = 0; - var changesSub; - var heighestSequencePromise = new Promise(function (res2) { - changesSub = _this2.changes({ - since: 'now', - live: true, - include_docs: true - }).on('change', function (change) { - var docId = change.id; - if (docIds.has(docId)) { - docIds["delete"](docId); - if (heighestSequence < change.seq) { - heighestSequence = change.seq; - } - if (docIds.size === 0) { - changesSub.cancel(); - res2(heighestSequence); - } - } - }); - }); - - /** - * We cannot send the custom here, - * because when a migration between different major RxDB versions is done, - * multiple versions of the RxDB PouchDB RxStorage might have added their - * custom method via PouchDBCore.plugin() - */ - var useOptsForOldBulkDocs = (0, _util.flatClone)(deeperOptions); - delete useOptsForOldBulkDocs.custom; - callReturn = oldBulkDocs.call(_this2, docs, useOptsForOldBulkDocs, function (err, result) { - if (err) { - if (callback) { - callback(err); - } else { - rej(err); - } - } else { - return function () { - try { - var _temp5 = function _temp5() { - result.forEach(function (row) { - usePouchResult.push(row); - }); - - /** - * For calls that came from RxDB, - * we have to ensure that the events are emitted - * before the actual call resolves. - */ - var eventsPromise = _util.PROMISE_RESOLVE_VOID; - if (!options.isDeeper) { - var endTime = (0, _util.now)(); - var emitData = { - emitId: runId, - writeDocs: docs, - writeOptions: options, - writeResult: usePouchResult, - previousDocs: previousDocsInDb, - startTime: startTime, - endTime: endTime - }; - eventsPromise = eventEmitDataToStorageEvents(_this2, '_id', emitData).then(function (events) { - var eventBulk = { - id: (0, _util.randomCouchString)(10), - events: events, - checkpoint: { - sequence: heighestSequenceInner - }, - context: options.custom ? options.custom.context : 'pouchdb-internal' - }; - var emitter = getCustomEventEmitterByPouch(_this2); - emitter.subject.next(eventBulk); - }); - } - if (callback) { - callback(null, usePouchResult); - } else { - return eventsPromise.then(function () { - res(usePouchResult); - return usePouchResult; - }); - } - }; - var hasError = result.find(function (row) { - return row.error; - }); - var heighestSequenceInner = -1; - var _temp4 = function () { - if (!hasError) { - return Promise.resolve(heighestSequencePromise).then(function (_heighestSequenceProm) { - heighestSequenceInner = _heighestSequenceProm; - }); - } else { - changesSub.cancel(); - } - }(); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }(); - } - }); - }); - return options.custom ? callPromise : callReturn; - }; - var _this2 = this; - var startTime = (0, _util.now)(); - var runId = i++; - - /** - * Normalize inputs - * because there are many ways to call pouchdb.bulkDocs() - */ - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } - var docs; - if (Array.isArray(body)) { - docs = body; - } else if (body === undefined) { - docs = []; - } else { - docs = body.docs; - if (body.hasOwnProperty('new_edits')) { - options.new_edits = body.new_edits; - } - } - - // throw if no docs given, because RxDB should never make such a call. - if (docs.length === 0) { - throw (0, _rxError.newRxError)('SNH', { - args: { - body: body, - options: options - } - }); - } - - /** - * If new_edits=false we have to first find the current state - * of the document and can later check if the state was changed - * because a new revision was written and we have to emit an event. - */ - var previousDocsInDb = options.custom ? options.custom.previousDocsInDb : new Map(); - var _temp2 = function () { - if (options.hasOwnProperty('new_edits') && options.new_edits === false) { - return Promise.resolve(_this2.bulkGet({ - docs: docs.map(function (doc) { - return { - id: doc._id - }; - }), - revs: true, - latest: true - })).then(function (viaBulkGet) { - /** - * bulkGet() does not return deleted documents, - * so we must refetch them via allDocs() afterwards. - */ - var mustRefetchBecauseDeleted = []; - viaBulkGet.results.forEach(function (resultRow) { - var firstDoc = resultRow.docs[0]; - if (firstDoc.ok) { - previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok); - } else { - if (firstDoc.error && firstDoc.error.reason === 'deleted') { - mustRefetchBecauseDeleted.push(resultRow.id); - } - } - }); - var _temp = function () { - if (mustRefetchBecauseDeleted.length > 0) { - return Promise.resolve(_this2.allDocs({ - keys: mustRefetchBecauseDeleted, - include_docs: true, - conflicts: true - })).then(function (deletedDocsViaAllDocs) { - var idsWithRevs = []; - deletedDocsViaAllDocs.rows.forEach(function (row) { - idsWithRevs.push({ - id: row.id, - rev: row.value.rev - }); - }); - return Promise.resolve(_this2.bulkGet({ - docs: idsWithRevs, - revs: true, - latest: true - })).then(function (deletedDocsViaBulkGetWithRev) { - deletedDocsViaBulkGetWithRev.results.forEach(function (resultRow) { - var firstDoc = resultRow.docs[0]; - if (firstDoc.ok) { - previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok); - } else { - throw (0, _rxError.newRxError)('SNH', { - args: { - deletedDocsViaBulkGetWithRev: deletedDocsViaBulkGetWithRev, - resultRow: resultRow - } - }); - } - }); - }); - }); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } - }; - _pouchdbCore["default"].plugin({ - bulkDocs: newBulkDocs - }); -} -function changeEventToNormal(pouchDBInstance, primaryPath, change, startTime, endTime) { - var doc = change.operation === 'DELETE' ? change.previous : change.doc; - var primary = doc[primaryPath]; - var storageChangeEvent = { - eventId: (0, _pouchdbHelper.getEventKey)(pouchDBInstance, primary, change), - documentId: primary, - documentData: change.doc, - previousDocumentData: change.previous, - operation: change.operation, - startTime: startTime, - endTime: endTime - }; - return storageChangeEvent; -} -//# sourceMappingURL=custom-events-plugin.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/custom-events-plugin.js.map b/dist/lib/plugins/pouchdb/custom-events-plugin.js.map deleted file mode 100644 index 9502f7ab66c..00000000000 --- a/dist/lib/plugins/pouchdb/custom-events-plugin.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"custom-events-plugin.js","names":["eventEmitDataToStorageEvents","pouchDBInstance","primaryPath","emitData","ret","writeOptions","custom","hasOwnProperty","new_edits","Promise","all","writeDocs","map","writeDoc","id","_id","pouchDocumentDataToRxDocumentData","writeAttachmentsToAttachments","_attachments","previousDoc","previousDocs","get","parsedRevPrevious","parseRevision","_rev","parsedRevNew","height","hash","_deleted","event","operation","doc","previous","newRxError","args","changeEvent","changeEventToNormal","startTime","endTime","push","writeRowById","writeDocsById","Map","forEach","set","writeResult","resultRow","startsWith","POUCHDB_DESIGN_PREFIX","POUCHDB_LOCAL_PREFIX","getFromMapOrThrow","flatClone","rev","pouchChangeRowToChangeEvent","writeMap","error","writeRow","document","attachments","ensureNotFalsy","newDoc","Object","assign","attachmentsInner","addedToPouch","EVENT_EMITTER_BY_POUCH_INSTANCE","getCustomEventEmitterByPouch","pouch","key","__opts","name","adapter","join","emitter","subject","Subject","i","BULK_DOC_RUN_QUEUE","WeakMap","addCustomEventsPluginToPouch","oldBulkDocs","PouchDBCore","prototype","bulkDocs","newBulkDocs","body","options","callback","internalPouches","includes","call","err","result","queue","PROMISE_RESOLVE_VOID","then","newBulkDocsInner","bind","usePouchResult","hasNonErrorWrite","docs","insertDocsById","Array","from","entries","previousRev","newRev","docInDb","previousDocsInDb","docInDbRev","status","useRevisions","start","ids","_revisions","slice","unshift","useNewRev","writeToPouchDocData","ok","deeperOptions","isDeeper","callReturn","callPromise","res","rej","docIds","Set","d","heighestSequence","changesSub","heighestSequencePromise","res2","changes","since","live","include_docs","on","change","docId","has","seq","size","cancel","useOptsForOldBulkDocs","row","eventsPromise","now","emitId","runId","events","eventBulk","randomCouchString","checkpoint","sequence","heighestSequenceInner","context","next","hasError","find","isArray","undefined","length","bulkGet","revs","latest","viaBulkGet","mustRefetchBecauseDeleted","results","firstDoc","reason","allDocs","keys","conflicts","deletedDocsViaAllDocs","idsWithRevs","rows","value","deletedDocsViaBulkGetWithRev","plugin","primary","storageChangeEvent","eventId","getEventKey","documentId","documentData","previousDocumentData"],"sources":["../../../../src/plugins/pouchdb/custom-events-plugin.ts"],"sourcesContent":["/*\n * Instead of listening to pouch.changes,\n * we overwrite pouchdbs bulkDocs()\n * and create our own event stream, this will work more reliable\n * and has less strange behaviors.\n * Also we can better define what data we need for our events.\n * @link http://jsbin.com/pagebi/1/edit?js,output\n * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273\n * @link https://hasura.io/blog/couchdb-style-conflict-resolution-rxdb-hasura/\n */\n\nimport type {\n BulkWriteRow,\n EventBulk,\n PouchBulkDocOptions,\n PouchBulkDocResultRow,\n PouchChangesOnChangeEvent,\n PouchCheckpoint,\n PouchDBInstance,\n PouchWriteError,\n RxDocumentData,\n RxStorageChangeEvent\n} from '../../types';\nimport PouchDBCore from 'pouchdb-core';\nimport { Subject } from 'rxjs';\nimport {\n ensureNotFalsy,\n flatClone,\n getFromMapOrThrow,\n now,\n parseRevision,\n PROMISE_RESOLVE_VOID,\n randomCouchString\n} from '../../util';\nimport { newRxError } from '../../rx-error';\nimport {\n getEventKey,\n pouchChangeRowToChangeEvent,\n POUCHDB_DESIGN_PREFIX,\n POUCHDB_LOCAL_PREFIX,\n pouchDocumentDataToRxDocumentData,\n writeAttachmentsToAttachments\n} from './pouchdb-helper';\nimport type { ChangeEvent } from 'event-reduce-js';\n\n// ensure only added once\nlet addedToPouch = false;\n\ndeclare type EmitData = {\n emitId: number;\n writeOptions: PouchBulkDocOptions;\n writeDocs: any[];\n writeResult: (PouchBulkDocResultRow | PouchWriteError)[];\n // used on new_edits=false to check if the last revision has changed\n previousDocs: Map;\n startTime: number;\n endTime: number;\n};\n\n\ndeclare type Emitter = {\n subject: Subject>, PouchCheckpoint>>;\n};\nexport const EVENT_EMITTER_BY_POUCH_INSTANCE: Map> = new Map();\n\nexport function getCustomEventEmitterByPouch(\n pouch: PouchDBInstance\n): Emitter {\n const key = [\n pouch.__opts.name,\n pouch.adapter\n ].join('|');\n let emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key);\n if (!emitter) {\n emitter = {\n subject: new Subject()\n };\n EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter);\n }\n return emitter;\n}\n\n\n/**\n * Counter, used to debug stuff.\n */\nlet i = 0;\n\n\n/**\n * Because we cannot force pouchdb to await bulkDocs runs\n * inside of a transaction, like done with the other RxStorage implementations,\n * we have to ensure the calls to bulkDocs() do not run in parallel.\n *\n * TODO this is somehow a hack. Instead of doing that, inspect how\n * PouchDB runs bulkDocs internally and adapt that transaction handling.\n */\nconst BULK_DOC_RUN_QUEUE: WeakMap> = new WeakMap();\n\n/**\n * PouchDB is like a minefield,\n * where stuff randomly does not work dependent on some conditions.\n * So instead of doing plain writes,\n * we hack into the bulkDocs() function\n * and adjust the behavior accordingly.\n */\nexport function addCustomEventsPluginToPouch() {\n if (addedToPouch) {\n return;\n }\n addedToPouch = true;\n\n const oldBulkDocs: any = PouchDBCore.prototype.bulkDocs;\n\n /**\n * Ensure we do not run bulkDocs() in parallel on the same PouchDB instance.\n */\n const newBulkDocs = function (\n this: PouchDBInstance,\n body: any[] | { docs: any[]; new_edits?: boolean; },\n options: PouchBulkDocOptions,\n callback: Function\n ) {\n\n /**\n * Normalize inputs\n * because there are many ways to call pouchdb.bulkDocs()\n */\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (!options) {\n options = {};\n }\n\n\n /**\n * PouchDB internal requests\n * must still be handled normally\n * to decrease the likelyness of bugs.\n */\n const internalPouches = [\n '_replicator',\n '_users',\n 'pouch__all_dbs__'\n ];\n if (\n (\n internalPouches.includes(this.name) ||\n this.name.includes('-mrview-')\n )\n ) {\n return oldBulkDocs.call(\n this,\n body,\n options,\n (err: any, result: (PouchBulkDocResultRow | PouchWriteError)[]) => {\n if (err) {\n if (callback) {\n callback(err, null);\n }\n } else {\n if (callback) {\n callback(null, result);\n }\n }\n });\n }\n\n\n let queue = BULK_DOC_RUN_QUEUE.get(this);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue.then(async () => {\n const ret = await newBulkDocsInner.bind(this)(\n body,\n options,\n callback\n );\n return ret;\n });\n BULK_DOC_RUN_QUEUE.set(this, queue);\n return queue;\n };\n\n\n const newBulkDocsInner = async function (\n this: PouchDBInstance,\n body: any[] | { docs: any[]; new_edits?: boolean; },\n options: PouchBulkDocOptions,\n callback: Function\n ) {\n const startTime = now();\n const runId = i++;\n\n /**\n * Normalize inputs\n * because there are many ways to call pouchdb.bulkDocs()\n */\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (!options) {\n options = {};\n }\n\n let docs: any[];\n if (Array.isArray(body)) {\n docs = body;\n } else if (body === undefined) {\n docs = [];\n } else {\n docs = body.docs;\n if (body.hasOwnProperty('new_edits')) {\n options.new_edits = body.new_edits;\n }\n }\n\n // throw if no docs given, because RxDB should never make such a call.\n if (docs.length === 0) {\n throw newRxError('SNH', {\n args: {\n body,\n options\n }\n });\n }\n\n\n /**\n * If new_edits=false we have to first find the current state\n * of the document and can later check if the state was changed\n * because a new revision was written and we have to emit an event.\n */\n const previousDocsInDb: Map> = options.custom ? options.custom.previousDocsInDb : new Map();\n if (\n options.hasOwnProperty('new_edits') &&\n options.new_edits === false\n ) {\n const viaBulkGet = await this.bulkGet({\n docs: docs.map(doc => ({ id: doc._id })),\n revs: true,\n latest: true\n });\n\n /**\n * bulkGet() does not return deleted documents,\n * so we must refetch them via allDocs() afterwards.\n */\n const mustRefetchBecauseDeleted: string[] = [];\n\n viaBulkGet.results.forEach(resultRow => {\n const firstDoc = resultRow.docs[0];\n if (firstDoc.ok) {\n previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok);\n } else {\n if (firstDoc.error && firstDoc.error.reason === 'deleted') {\n mustRefetchBecauseDeleted.push(resultRow.id);\n }\n }\n });\n\n if (mustRefetchBecauseDeleted.length > 0) {\n const deletedDocsViaAllDocs = await this.allDocs({\n keys: mustRefetchBecauseDeleted,\n include_docs: true,\n conflicts: true,\n });\n\n const idsWithRevs: { id: string; rev: string; }[] = [];\n deletedDocsViaAllDocs.rows.forEach(row => {\n idsWithRevs.push({\n id: row.id,\n rev: row.value.rev\n });\n });\n\n const deletedDocsViaBulkGetWithRev = await this.bulkGet({\n docs: idsWithRevs,\n revs: true,\n latest: true\n });\n\n deletedDocsViaBulkGetWithRev.results.forEach(resultRow => {\n const firstDoc = resultRow.docs[0];\n if (firstDoc.ok) {\n previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok);\n } else {\n throw newRxError('SNH', {\n args: {\n deletedDocsViaBulkGetWithRev,\n resultRow\n }\n });\n }\n });\n\n }\n }\n\n /**\n * Custom handling if the call came from RxDB (options.custom is set).\n */\n const usePouchResult: (PouchBulkDocResultRow | PouchWriteError)[] = [];\n let hasNonErrorWrite = false;\n if (\n options.custom &&\n options.hasOwnProperty('new_edits') &&\n options.new_edits === false\n ) {\n /**\n * Reset the write docs array,\n * because we only write non-conflicting documents.\n */\n docs = [];\n const writeRowById: Map> = options.custom.writeRowById;\n const insertDocsById: Map = options.custom.insertDocsById;\n\n Array.from(writeRowById.entries()).forEach(([id, writeRow]) => {\n const previousRev = writeRow.previous ? writeRow.previous._rev : null;\n const newRev = parseRevision(writeRow.document._rev);\n const docInDb = previousDocsInDb.get(id);\n const docInDbRev: string | null = docInDb ? docInDb._rev : null;\n\n if (\n docInDbRev !== previousRev\n ) {\n // we have a conflict\n usePouchResult.push({\n error: true,\n id,\n status: 409\n });\n } else {\n const useRevisions = {\n start: newRev.height,\n ids: docInDb ? docInDb._revisions.ids.slice(0) : []\n };\n useRevisions.ids.unshift(newRev.hash);\n const useNewRev = useRevisions.start + '-' + newRev.hash;\n\n hasNonErrorWrite = true;\n const writeToPouchDocData = Object.assign(\n {},\n insertDocsById.get(id),\n {\n _revisions: useRevisions,\n _rev: useNewRev\n }\n );\n docs.push(writeToPouchDocData);\n usePouchResult.push({\n ok: true,\n id,\n rev: writeRow.document._rev\n });\n }\n });\n\n /**\n * Optimization shortcut,\n * if all document writes were conflict errors,\n * we can skip directly.\n */\n if (!hasNonErrorWrite) {\n return usePouchResult;\n }\n }\n\n /**\n * pouchdb calls this function again with transformed input.\n * This would lead to duplicate events. So we marks the deeper calls via the options\n * parameter and do not emit events if it is set.\n */\n const deeperOptions = flatClone(options);\n deeperOptions.isDeeper = true;\n let callReturn: any;\n const callPromise = new Promise((res, rej) => {\n\n /**\n * The emitted EventBulk from the write to the pouchdb, needs to contain a checkpoint field.\n * Because PouchDB works on sequence number to sort changes,\n * we have to fetch the latest sequence number out of the events because it\n * is not possible to that that from pouch.bulkDocs().\n */\n const docIds: Set = new Set(docs.map(d => d._id));\n let heighestSequence = 0;\n let changesSub: PouchChangesOnChangeEvent;\n const heighestSequencePromise = new Promise(res2 => {\n changesSub = this.changes({\n since: 'now',\n live: true,\n include_docs: true\n }).on('change', (change: any) => {\n const docId: string = change.id;\n if (docIds.has(docId)) {\n docIds.delete(docId);\n if (heighestSequence < change.seq) {\n heighestSequence = change.seq;\n }\n\n if (docIds.size === 0) {\n (changesSub as any).cancel();\n res2(heighestSequence);\n }\n }\n }) as any;\n });\n\n\n /**\n * We cannot send the custom here,\n * because when a migration between different major RxDB versions is done,\n * multiple versions of the RxDB PouchDB RxStorage might have added their\n * custom method via PouchDBCore.plugin()\n */\n const useOptsForOldBulkDocs = flatClone(deeperOptions);\n delete useOptsForOldBulkDocs.custom;\n\n callReturn = oldBulkDocs.call(\n this,\n docs,\n useOptsForOldBulkDocs,\n (err: any, result: (PouchBulkDocResultRow | PouchWriteError)[]) => {\n if (err) {\n if (callback) {\n callback(err);\n } else {\n rej(err);\n }\n } else {\n return (async () => {\n const hasError = result.find(row => (row as PouchWriteError).error);\n let heighestSequenceInner = -1;\n if (!hasError) {\n heighestSequenceInner = await heighestSequencePromise;\n } else {\n changesSub.cancel();\n }\n\n result.forEach(row => {\n usePouchResult.push(row);\n });\n\n /**\n * For calls that came from RxDB,\n * we have to ensure that the events are emitted\n * before the actual call resolves.\n */\n let eventsPromise = PROMISE_RESOLVE_VOID;\n if (!options.isDeeper) {\n const endTime = now();\n const emitData = {\n emitId: runId,\n writeDocs: docs,\n writeOptions: options,\n writeResult: usePouchResult,\n previousDocs: previousDocsInDb,\n startTime,\n endTime\n };\n eventsPromise = eventEmitDataToStorageEvents(\n this,\n '_id',\n emitData\n ).then(events => {\n const eventBulk: EventBulk = {\n id: randomCouchString(10),\n events,\n checkpoint: {\n sequence: heighestSequenceInner\n },\n context: options.custom ? options.custom.context : 'pouchdb-internal'\n };\n\n const emitter = getCustomEventEmitterByPouch(this);\n emitter.subject.next(eventBulk);\n });\n }\n\n if (callback) {\n callback(null, usePouchResult);\n } else {\n return eventsPromise.then(() => {\n res(usePouchResult);\n return usePouchResult;\n });\n }\n })();\n }\n });\n });\n\n if (options.custom) {\n return callPromise;\n }\n\n\n\n return callReturn;\n };\n\n PouchDBCore.plugin({\n bulkDocs: newBulkDocs\n } as any);\n\n}\n\nexport async function eventEmitDataToStorageEvents(\n pouchDBInstance: PouchDBInstance,\n primaryPath: string,\n emitData: EmitData\n): Promise>[]> {\n const ret: RxStorageChangeEvent>[] = [];\n if (\n !emitData.writeOptions.custom &&\n emitData.writeOptions.hasOwnProperty('new_edits') &&\n emitData.writeOptions.new_edits === false\n ) {\n await Promise.all(\n emitData.writeDocs.map(async (writeDoc) => {\n const id = writeDoc._id;\n writeDoc = pouchDocumentDataToRxDocumentData(\n primaryPath,\n writeDoc\n );\n writeDoc._attachments = await writeAttachmentsToAttachments(writeDoc._attachments);\n let previousDoc = emitData.previousDocs.get(id);\n if (previousDoc) {\n previousDoc = pouchDocumentDataToRxDocumentData(\n primaryPath,\n previousDoc\n );\n }\n if (previousDoc) {\n const parsedRevPrevious = parseRevision(previousDoc._rev);\n const parsedRevNew = parseRevision(writeDoc._rev);\n if (\n (\n parsedRevPrevious.height > parsedRevNew.height ||\n /**\n * If the revision height is equal,\n * we determine the higher hash as winner.\n */\n (\n parsedRevPrevious.height === parsedRevNew.height &&\n parsedRevPrevious.hash > parsedRevNew.hash\n )\n )\n ) {\n /**\n * The newly added document was not the latest revision\n * so we drop the write.\n * With plain PouchDB it makes sense to store conflicting branches of the document\n * but RxDB assumes that the conflict is resolved directly.\n */\n return;\n }\n }\n\n if (!previousDoc && writeDoc._deleted) {\n // deleted document was added as revision\n return;\n }\n\n if (previousDoc && previousDoc._deleted && writeDoc._deleted) {\n // delete document was deleted again\n return;\n }\n\n let event: ChangeEvent>;\n if ((!previousDoc || previousDoc._deleted) && !writeDoc._deleted) {\n // was insert\n event = {\n operation: 'INSERT',\n doc: writeDoc,\n id: id,\n previous: null\n };\n } else if (writeDoc._deleted && previousDoc && !previousDoc._deleted) {\n // was delete\n previousDoc._rev = writeDoc._rev;\n event = {\n operation: 'DELETE',\n doc: writeDoc,\n id: id,\n previous: previousDoc\n };\n } else if (\n previousDoc\n ) {\n // was update\n event = {\n operation: 'UPDATE',\n doc: writeDoc,\n id: id,\n previous: previousDoc\n };\n } else {\n throw newRxError('SNH', { args: { writeDoc } });\n }\n\n const changeEvent = changeEventToNormal(\n pouchDBInstance,\n primaryPath,\n event,\n emitData.startTime,\n emitData.endTime\n );\n\n ret.push(changeEvent);\n })\n );\n // eslint-disable-next-line brace-style\n }\n\n /**\n * There is no write map given for internal pouchdb document writes\n * like it is done with replication.\n */\n else if (\n !emitData.writeOptions.custom ||\n (emitData.writeOptions.custom && !emitData.writeOptions.custom.writeRowById)\n ) {\n const writeDocsById: Map = new Map();\n emitData.writeDocs.forEach(writeDoc => writeDocsById.set(writeDoc._id, writeDoc));\n await Promise.all(\n emitData.writeResult.map(async (resultRow) => {\n const id = resultRow.id;\n if (\n id.startsWith(POUCHDB_DESIGN_PREFIX) ||\n id.startsWith(POUCHDB_LOCAL_PREFIX)\n ) {\n return;\n }\n let writeDoc = getFromMapOrThrow(writeDocsById, resultRow.id);\n writeDoc = pouchDocumentDataToRxDocumentData(\n primaryPath,\n writeDoc\n );\n\n writeDoc._attachments = await writeAttachmentsToAttachments(writeDoc._attachments);\n writeDoc = flatClone(writeDoc);\n writeDoc._rev = (resultRow as any).rev;\n const event = pouchChangeRowToChangeEvent(\n primaryPath as any,\n writeDoc\n );\n const changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event);\n ret.push(changeEvent);\n })\n );\n } else {\n const writeMap: Map> = emitData.writeOptions.custom.writeRowById;\n await Promise.all(\n emitData.writeResult.map(async (resultRow) => {\n if ((resultRow as PouchWriteError).error) {\n return;\n }\n const id = resultRow.id;\n const writeRow = getFromMapOrThrow(writeMap, id);\n const attachments = await writeAttachmentsToAttachments(writeRow.document._attachments);\n const newDoc: RxDocumentData = Object.assign(\n {},\n writeRow.document,\n {\n _attachments: attachments,\n _rev: (resultRow as PouchBulkDocResultRow).rev\n }\n );\n\n let event: ChangeEvent>;\n if (!writeRow.previous || writeRow.previous._deleted) {\n // was insert\n event = {\n operation: 'INSERT',\n doc: newDoc,\n id: id,\n previous: null\n };\n } else if (writeRow.document._deleted) {\n // was delete\n\n // we need to add the new revision to the previous doc\n // so that the eventkey is calculated correctly.\n // Is this a hack? idk.\n const attachmentsInner = await writeAttachmentsToAttachments(writeRow.previous._attachments);\n const previousDoc = Object.assign(\n {},\n writeRow.previous,\n {\n _attachments: attachmentsInner\n }\n );\n\n event = {\n operation: 'DELETE',\n doc: writeRow.document,\n id: resultRow.id,\n previous: previousDoc\n } as any;\n } else {\n // was update\n event = {\n operation: 'UPDATE',\n doc: newDoc,\n id: resultRow.id,\n previous: writeRow.previous\n };\n }\n\n if (\n writeRow.document._deleted &&\n (\n !writeRow.previous ||\n writeRow.previous._deleted\n )\n ) {\n /**\n * A deleted document was newly added to the storage engine,\n * do not emit an event.\n */\n } else {\n const changeEvent = changeEventToNormal(\n pouchDBInstance,\n ensureNotFalsy(emitData.writeOptions.custom).primaryPath,\n event,\n emitData.startTime,\n emitData.endTime\n );\n ret.push(changeEvent);\n }\n })\n );\n }\n\n return ret;\n}\n\nexport function changeEventToNormal(\n pouchDBInstance: PouchDBInstance,\n primaryPath: string,\n change: ChangeEvent>,\n startTime?: number,\n endTime?: number\n): RxStorageChangeEvent> {\n const doc: RxDocumentData = change.operation === 'DELETE' ? change.previous as any : change.doc as any;\n const primary: string = (doc as any)[primaryPath];\n const storageChangeEvent: RxStorageChangeEvent> = {\n eventId: getEventKey(pouchDBInstance, primary, change),\n documentId: primary,\n documentData: change.doc as any,\n previousDocumentData: change.previous as any,\n operation: change.operation,\n startTime,\n endTime\n };\n return storageChangeEvent;\n}\n"],"mappings":";;;;;;;;;;;AAuBA;AACA;AACA;AASA;AACA;AAnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AATA,IA+fsBA,4BAA4B,YAA5BA,4BAA4B,CAC9CC,eAAgC,EAChCC,WAAmB,EACnBC,QAAkB;EAAA,IACwC;IAC1D,IAAMC,GAAsD,GAAG,EAAE;IAAC;MAAA,IAE9D,CAACD,QAAQ,CAACE,YAAY,CAACC,MAAM,IAC7BH,QAAQ,CAACE,YAAY,CAACE,cAAc,CAAC,WAAW,CAAC,IACjDJ,QAAQ,CAACE,YAAY,CAACG,SAAS,KAAK,KAAK;QAAA,uBAEnCC,OAAO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AAC,CAAC;kBAAC;gBAAA;cAAA;YAAA;YAAA;UAAA;QAAA;MAAA;MAAA;IA6Mf,CAAC;MAAA;IAAA;EAAA;EAEDmC,uBAAW,CAACkG,MAAM,CAAC;IACfhG,QAAQ,EAAEC;EACd,CAAC,CAAQ;AAEb;AAyOO,SAAShD,mBAAmB,CAC/BnC,eAAgC,EAChCC,WAAmB,EACnBwI,MAA8C,EAC9CrG,SAAkB,EAClBC,OAAgB,EAC+B;EAC/C,IAAMP,GAA8B,GAAG2G,MAAM,CAAC5G,SAAS,KAAK,QAAQ,GAAG4G,MAAM,CAAC1G,QAAQ,GAAU0G,MAAM,CAAC3G,GAAU;EACjH,IAAMqJ,OAAe,GAAIrJ,GAAG,CAAS7B,WAAW,CAAC;EACjD,IAAMmL,kBAAmE,GAAG;IACxEC,OAAO,EAAE,IAAAC,0BAAW,EAACtL,eAAe,EAAEmL,OAAO,EAAE1C,MAAM,CAAC;IACtD8C,UAAU,EAAEJ,OAAO;IACnBK,YAAY,EAAE/C,MAAM,CAAC3G,GAAU;IAC/B2J,oBAAoB,EAAEhD,MAAM,CAAC1G,QAAe;IAC5CF,SAAS,EAAE4G,MAAM,CAAC5G,SAAS;IAC3BO,SAAS,EAATA,SAAS;IACTC,OAAO,EAAPA;EACJ,CAAC;EACD,OAAO+I,kBAAkB;AAC7B"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/index.js b/dist/lib/plugins/pouchdb/index.js deleted file mode 100644 index 38cc55e63aa..00000000000 --- a/dist/lib/plugins/pouchdb/index.js +++ /dev/null @@ -1,83 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _pouchDb = require("./pouch-db"); -Object.keys(_pouchDb).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _pouchDb[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _pouchDb[key]; - } - }); -}); -var _rxStoragePouchdb = require("./rx-storage-pouchdb"); -Object.keys(_rxStoragePouchdb).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _rxStoragePouchdb[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _rxStoragePouchdb[key]; - } - }); -}); -var _adapterCheck = require("./adapter-check"); -Object.keys(_adapterCheck).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _adapterCheck[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _adapterCheck[key]; - } - }); -}); -var _customEventsPlugin = require("./custom-events-plugin"); -Object.keys(_customEventsPlugin).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _customEventsPlugin[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _customEventsPlugin[key]; - } - }); -}); -var _pouchdbHelper = require("./pouchdb-helper"); -Object.keys(_pouchdbHelper).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _pouchdbHelper[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _pouchdbHelper[key]; - } - }); -}); -var _pouchStatics = require("./pouch-statics"); -Object.keys(_pouchStatics).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _pouchStatics[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _pouchStatics[key]; - } - }); -}); -var _rxStorageInstancePouch = require("./rx-storage-instance-pouch"); -Object.keys(_rxStorageInstancePouch).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _rxStorageInstancePouch[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _rxStorageInstancePouch[key]; - } - }); -}); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/index.js.map b/dist/lib/plugins/pouchdb/index.js.map deleted file mode 100644 index 5be9205dd9a..00000000000 --- a/dist/lib/plugins/pouchdb/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/pouchdb/index.ts"],"sourcesContent":["export * from './pouch-db';\nexport * from './rx-storage-pouchdb';\nexport * from './adapter-check';\nexport * from './custom-events-plugin';\nexport * from './pouchdb-helper';\nexport * from './pouch-statics';\nexport * from './rx-storage-instance-pouch';\n\nexport type {\n PouchDBInstance,\n PouchReplicationOptions,\n PouchSettings,\n PouchSyncHandler,\n PouchSyncHandlerEvents,\n PouchdbQuery,\n} from '../../types/pouch';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouch-db.js b/dist/lib/plugins/pouchdb/pouch-db.js deleted file mode 100644 index e65b79ff58d..00000000000 --- a/dist/lib/plugins/pouchdb/pouch-db.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.PouchDB = void 0; -exports.addPouchPlugin = addPouchPlugin; -exports.isInstanceOf = isInstanceOf; -exports.isLevelDown = isLevelDown; -var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); -var _rxError = require("../../rx-error"); -/** - * this handles the pouchdb-instance - * to easy add modules and manipulate things - * Adapters can be found here: - * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules - */ - -/* -// comment in to debug -const pouchdbDebug = require('pouchdb-debug'); -PouchDB.plugin(pouchdbDebug); -PouchDB.debug.enable('*'); -*/ - -/** - * check if the given module is a leveldown-adapter - * throws if not - */ -function isLevelDown(adapter) { - if (!adapter || typeof adapter.super_ !== 'function') { - throw (0, _rxError.newRxError)('UT4', { - adapter: adapter - }); - } -} -function isInstanceOf(obj) { - return obj instanceof _pouchdbCore["default"]; -} - -/** - * Adding a PouchDB plugin multiple times, - * can sometimes error. So we have to check if the plugin - * was added before. - */ -var ADDED_POUCH_PLUGINS = new Set(); - -/** - * Add a pouchdb plugin to the pouchdb library. - * @deprecated PouchDB RxStorage is deprecated, see - * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated - */ -function addPouchPlugin(plugin) { - if (plugin.rxdb) { - throw (0, _rxError.newRxTypeError)('PL2', { - plugin: plugin - }); - } - /** - * Pouchdb has confusing typings and modules. - * So we monkeypatch the plugin to use the default property - * when it was imported or packaged this way. - */ - if (typeof plugin === 'object' && plugin["default"]) { - plugin = plugin["default"]; - } - if (!ADDED_POUCH_PLUGINS.has(plugin)) { - ADDED_POUCH_PLUGINS.add(plugin); - _pouchdbCore["default"].plugin(plugin); - } -} -var PouchDB = _pouchdbCore["default"]; -exports.PouchDB = PouchDB; -//# sourceMappingURL=pouch-db.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouch-db.js.map b/dist/lib/plugins/pouchdb/pouch-db.js.map deleted file mode 100644 index 9fdcebf7da9..00000000000 --- a/dist/lib/plugins/pouchdb/pouch-db.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouch-db.js","names":["isLevelDown","adapter","super_","newRxError","isInstanceOf","obj","PouchDBCore","ADDED_POUCH_PLUGINS","Set","addPouchPlugin","plugin","rxdb","newRxTypeError","has","add","PouchDB"],"sources":["../../../../src/plugins/pouchdb/pouch-db.ts"],"sourcesContent":["/**\n * this handles the pouchdb-instance\n * to easy add modules and manipulate things\n * Adapters can be found here:\n * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules\n */\nimport PouchDBCore from 'pouchdb-core';\n\n/*\n// comment in to debug\nconst pouchdbDebug = require('pouchdb-debug');\nPouchDB.plugin(pouchdbDebug);\nPouchDB.debug.enable('*');\n*/\n\n\nimport {\n newRxError,\n newRxTypeError\n} from '../../rx-error';\n\n\n/**\n * check if the given module is a leveldown-adapter\n * throws if not\n */\nexport function isLevelDown(adapter: any) {\n if (!adapter || typeof adapter.super_ !== 'function') {\n throw newRxError('UT4', {\n adapter\n });\n }\n}\n\nexport function isInstanceOf(obj: any) {\n return obj instanceof PouchDBCore;\n}\n\n/**\n * Adding a PouchDB plugin multiple times,\n * can sometimes error. So we have to check if the plugin\n * was added before.\n */\nconst ADDED_POUCH_PLUGINS: Set = new Set();\n\n/**\n * Add a pouchdb plugin to the pouchdb library.\n * @deprecated PouchDB RxStorage is deprecated, see\n * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated\n */\nexport function addPouchPlugin(plugin: any) {\n if (plugin.rxdb) {\n throw newRxTypeError('PL2', {\n plugin\n });\n }\n /**\n * Pouchdb has confusing typings and modules.\n * So we monkeypatch the plugin to use the default property\n * when it was imported or packaged this way.\n */\n if (typeof plugin === 'object' && plugin.default) {\n plugin = plugin.default;\n }\n\n if (!ADDED_POUCH_PLUGINS.has(plugin)) {\n ADDED_POUCH_PLUGINS.add(plugin);\n PouchDBCore.plugin(plugin);\n }\n}\n\n\nexport const PouchDB: any = PouchDBCore as any;\n"],"mappings":";;;;;;;;;;AAMA;AAUA;AAhBA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;AACA;AACA;AACO,SAASA,WAAW,CAACC,OAAY,EAAE;EACtC,IAAI,CAACA,OAAO,IAAI,OAAOA,OAAO,CAACC,MAAM,KAAK,UAAU,EAAE;IAClD,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;MACpBF,OAAO,EAAPA;IACJ,CAAC,CAAC;EACN;AACJ;AAEO,SAASG,YAAY,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYC,uBAAW;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAMC,mBAA6B,GAAG,IAAIC,GAAG,EAAE;;AAE/C;AACA;AACA;AACA;AACA;AACO,SAASC,cAAc,CAACC,MAAW,EAAE;EACxC,IAAIA,MAAM,CAACC,IAAI,EAAE;IACb,MAAM,IAAAC,uBAAc,EAAC,KAAK,EAAE;MACxBF,MAAM,EAANA;IACJ,CAAC,CAAC;EACN;EACA;AACJ;AACA;AACA;AACA;EACI,IAAI,OAAOA,MAAM,KAAK,QAAQ,IAAIA,MAAM,WAAQ,EAAE;IAC9CA,MAAM,GAAGA,MAAM,WAAQ;EAC3B;EAEA,IAAI,CAACH,mBAAmB,CAACM,GAAG,CAACH,MAAM,CAAC,EAAE;IAClCH,mBAAmB,CAACO,GAAG,CAACJ,MAAM,CAAC;IAC/BJ,uBAAW,CAACI,MAAM,CAACA,MAAM,CAAC;EAC9B;AACJ;AAGO,IAAMK,OAAY,GAAGT,uBAAkB;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouch-statics.js b/dist/lib/plugins/pouchdb/pouch-statics.js deleted file mode 100644 index c183e53aa56..00000000000 --- a/dist/lib/plugins/pouchdb/pouch-statics.js +++ /dev/null @@ -1,217 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxStoragePouchStatics = void 0; -exports.preparePouchDbQuery = preparePouchDbQuery; -var _pouchdbSelectorCore = require("pouchdb-selector-core"); -var _rxError = require("../../rx-error"); -var _pouchdbHelper = require("./pouchdb-helper"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _overwritable = require("../../overwritable"); -var _util = require("../../util"); -var RxStoragePouchStatics = { - getSortComparator: function getSortComparator(schema, query) { - var _ref; - var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var sortOptions = query.sort ? query.sort : [(_ref = {}, _ref[primaryPath] = 'asc', _ref)]; - var selector = query.selector ? query.selector : {}; - var inMemoryFields = Object.keys(selector).filter(function (key) { - return !key.startsWith('$'); - }); - var fun = function fun(a, b) { - /** - * Sorting on two documents with the same primary is not allowed - * because it might end up in a non-deterministic result. - */ - if (a[primaryPath] === b[primaryPath]) { - throw (0, _rxError.newRxError)('SNH', { - args: { - a: a, - b: b - }, - primaryPath: primaryPath - }); - } - - // TODO use createFieldSorter - // TODO make a performance test - var rows = [a, b].map(function (doc) { - return { - doc: (0, _pouchdbHelper.pouchSwapPrimaryToId)(primaryPath, doc) - }; - }); - var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, { - selector: {}, - sort: sortOptions - }, inMemoryFields); - if (sortedRows.length !== 2) { - throw (0, _rxError.newRxError)('SNH', { - query: query, - primaryPath: primaryPath, - args: { - rows: rows, - sortedRows: sortedRows - } - }); - } - if (sortedRows[0].doc._id === rows[0].doc._id) { - return -1; - } else { - return 1; - } - }; - return fun; - }, - /** - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js - */ - getQueryMatcher: function getQueryMatcher(schema, query) { - var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var selector = query.selector ? query.selector : {}; - var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(selector); - var fun = function fun(doc) { - if (doc._deleted) { - return false; - } - var cloned = (0, _pouchdbHelper.pouchSwapPrimaryToId)(primaryPath, doc); - var row = { - doc: cloned - }; - var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { - selector: massagedSelector - }, Object.keys(selector)); - var ret = rowsMatched && rowsMatched.length === 1; - return ret; - }; - return fun; - }, - /** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ - prepareQuery: function prepareQuery(schema, mutateableQuery) { - return preparePouchDbQuery(schema, mutateableQuery); - }, - checkpointSchema: _pouchdbHelper.POUCHDB_CHECKPOINT_SCHEMA -}; - -/** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ -exports.RxStoragePouchStatics = RxStoragePouchStatics; -function preparePouchDbQuery(schema, mutateableQuery) { - var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var query = (0, _util.flatClone)(mutateableQuery); - if (query.selector) { - query.selector = (0, _util.flatClone)(query.selector); - } - - /** - * because sort won't work on unused keys we have to workaround - * so we add the key to the selector if necessary - * @link https://github.com/nolanlawson/pouchdb-find/issues/204 - */ - if (query.sort) { - query.sort.forEach(function (sortPart) { - var key = Object.keys(sortPart)[0]; - var comparisonOperators = ['$gt', '$gte', '$lt', '$lte', '$eq']; - var keyUsed = query.selector && query.selector[key] && Object.keys(query.selector[key]).some(function (op) { - return comparisonOperators.includes(op); - }); - if (!keyUsed) { - var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(schema, key); - if (!schemaObj) { - throw (0, _rxError.newRxError)('QU5', { - query: query, - key: key, - schema: schema - }); - } - if (!query.selector) { - query.selector = {}; - } - if (!query.selector[key]) { - query.selector[key] = {}; - } - switch (schemaObj.type) { - case 'number': - case 'integer': - // TODO change back to -Infinity when issue resolved - // @link https://github.com/pouchdb/pouchdb/issues/6454 - // -Infinity does not work since pouchdb 6.2.0 - query.selector[key].$gt = -9999999999999999999999999999; - break; - case 'string': - /** - * strings need an empty string, see - * @link https://github.com/pubkey/rxdb/issues/585 - */ - if (typeof query.selector[key] !== 'string') { - query.selector[key].$gt = ''; - } - break; - default: - query.selector[key].$gt = null; - break; - } - } - }); - } - - // regex does not work over the primary key - if (_overwritable.overwritable.isDevMode() && query.selector && query.selector[primaryKey] && query.selector[primaryKey].$regex) { - throw (0, _rxError.newRxError)('QU4', { - path: primaryKey, - query: mutateableQuery - }); - } - - // primary-swap sorting - if (query.sort) { - var sortArray = query.sort.map(function (part) { - var _newPart; - var key = Object.keys(part)[0]; - var direction = Object.values(part)[0]; - var useKey = key === primaryKey ? '_id' : key; - var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); - return newPart; - }); - query.sort = sortArray; - } - - // strip empty selectors - Object.entries((0, _util.ensureNotFalsy)(query.selector)).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { - delete (0, _util.ensureNotFalsy)(query.selector)[k]; - } - }); - - /** - * Set use_index - * @link https://pouchdb.com/guides/mango-queries.html#use_index - */ - if (mutateableQuery.index) { - var indexMaybeArray = mutateableQuery.index; - var indexArray = (0, _util.isMaybeReadonlyArray)(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; - indexArray = indexArray.map(function (str) { - if (str === primaryKey) { - return '_id'; - } else { - return str; - } - }); - var indexName = (0, _pouchdbHelper.getPouchIndexDesignDocNameByIndex)(indexArray); - delete query.index; - query.use_index = indexName; - } - query.selector = (0, _pouchdbHelper.primarySwapPouchDbQuerySelector)(query.selector, primaryKey); - return query; -} -//# sourceMappingURL=pouch-statics.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouch-statics.js.map b/dist/lib/plugins/pouchdb/pouch-statics.js.map deleted file mode 100644 index d3ed0c046d9..00000000000 --- a/dist/lib/plugins/pouchdb/pouch-statics.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouch-statics.js","names":["RxStoragePouchStatics","getSortComparator","schema","query","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","sortOptions","sort","selector","inMemoryFields","Object","keys","filter","key","startsWith","fun","a","b","newRxError","args","rows","map","doc","pouchSwapPrimaryToId","sortedRows","filterInMemoryFields","length","_id","getQueryMatcher","massagedSelector","massageSelector","_deleted","cloned","row","rowsMatched","ret","prepareQuery","mutateableQuery","preparePouchDbQuery","checkpointSchema","POUCHDB_CHECKPOINT_SCHEMA","flatClone","forEach","sortPart","comparisonOperators","keyUsed","some","op","includes","schemaObj","getSchemaByObjectPath","type","$gt","overwritable","isDevMode","$regex","path","sortArray","part","direction","values","useKey","newPart","entries","ensureNotFalsy","k","v","Array","isArray","index","indexMaybeArray","indexArray","isMaybeReadonlyArray","str","indexName","getPouchIndexDesignDocNameByIndex","use_index","primarySwapPouchDbQuerySelector"],"sources":["../../../../src/plugins/pouchdb/pouch-statics.ts"],"sourcesContent":["import {\n filterInMemoryFields,\n massageSelector\n} from 'pouchdb-selector-core';\nimport { newRxError } from '../../rx-error';\n\nimport {\n getPouchIndexDesignDocNameByIndex,\n POUCHDB_CHECKPOINT_SCHEMA,\n pouchSwapPrimaryToId,\n primarySwapPouchDbQuerySelector\n} from './pouchdb-helper';\nimport type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport {\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath\n} from '../../rx-schema-helper';\nimport type {\n MangoQuery,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n PreparedQuery,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageStatics,\n StringKeys\n} from '../../types';\nimport { overwritable } from '../../overwritable';\nimport { ensureNotFalsy, flatClone, isMaybeReadonlyArray } from '../../util';\n\nexport const RxStoragePouchStatics: RxStorageStatics = {\n getSortComparator(\n schema: RxJsonSchema>,\n query: MangoQuery\n ): DeterministicSortComparator {\n const primaryPath: StringKeys = getPrimaryFieldOfPrimaryKey(schema.primaryKey) as any;\n const sortOptions: MangoQuerySortPart[] = query.sort ? (query.sort as any) : [{\n [primaryPath]: 'asc'\n }];\n const selector = query.selector ? query.selector : {};\n const inMemoryFields = Object\n .keys(selector)\n .filter(key => !key.startsWith('$'));\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n /**\n * Sorting on two documents with the same primary is not allowed\n * because it might end up in a non-deterministic result.\n */\n if (a[primaryPath] === b[primaryPath]) {\n throw newRxError('SNH', { args: { a, b }, primaryPath: primaryPath as any });\n }\n\n // TODO use createFieldSorter\n // TODO make a performance test\n const rows = [a, b].map(doc => ({\n doc: pouchSwapPrimaryToId(primaryPath, doc)\n }));\n const sortedRows: { doc: any; }[] = filterInMemoryFields(\n rows,\n {\n selector: {},\n sort: sortOptions\n },\n inMemoryFields\n );\n if (sortedRows.length !== 2) {\n throw newRxError('SNH', {\n query,\n primaryPath: primaryPath as any,\n args: {\n rows,\n sortedRows\n }\n });\n }\n if (sortedRows[0].doc._id === rows[0].doc._id) {\n return -1;\n } else {\n return 1;\n }\n };\n return fun;\n },\n\n /**\n * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js\n */\n getQueryMatcher(\n schema: RxJsonSchema,\n query: MangoQuery\n ): QueryMatcher> {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const selector = query.selector ? query.selector : {};\n const massagedSelector = massageSelector(selector);\n const fun: QueryMatcher> = (doc: RxDocumentWriteData) => {\n if (doc._deleted) {\n return false;\n }\n const cloned = pouchSwapPrimaryToId(primaryPath, doc);\n const row = {\n doc: cloned\n };\n const rowsMatched = filterInMemoryFields(\n [row],\n { selector: massagedSelector },\n Object.keys(selector)\n );\n const ret = rowsMatched && rowsMatched.length === 1;\n return ret;\n };\n return fun;\n },\n\n\n /**\n * pouchdb has many bugs and strange behaviors\n * this functions takes a normal mango query\n * and transforms it to one that fits for pouchdb\n */\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: MangoQuery\n ): PreparedQuery {\n return preparePouchDbQuery(\n schema,\n mutateableQuery\n );\n },\n checkpointSchema: POUCHDB_CHECKPOINT_SCHEMA\n};\n\n/**\n * pouchdb has many bugs and strange behaviors\n * this functions takes a normal mango query\n * and transforms it to one that fits for pouchdb\n */\nexport function preparePouchDbQuery(\n schema: RxJsonSchema>,\n mutateableQuery: MangoQuery\n): PreparedQuery {\n const primaryKey = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const query = flatClone(mutateableQuery);\n if (query.selector) {\n query.selector = flatClone(query.selector);\n }\n\n /**\n * because sort won't work on unused keys we have to workaround\n * so we add the key to the selector if necessary\n * @link https://github.com/nolanlawson/pouchdb-find/issues/204\n */\n if (query.sort) {\n query.sort.forEach(sortPart => {\n const key = Object.keys(sortPart)[0];\n const comparisonOperators = ['$gt', '$gte', '$lt', '$lte', '$eq'];\n const keyUsed = query.selector && query.selector[key] && Object.keys(query.selector[key]).some(op => comparisonOperators.includes(op));\n\n if (!keyUsed) {\n const schemaObj = getSchemaByObjectPath(schema, key);\n if (!schemaObj) {\n throw newRxError('QU5', {\n query,\n key,\n schema\n });\n }\n if (!query.selector) {\n query.selector = {};\n }\n if (!query.selector[key]) {\n query.selector[key] = {};\n }\n switch (schemaObj.type) {\n case 'number':\n case 'integer':\n // TODO change back to -Infinity when issue resolved\n // @link https://github.com/pouchdb/pouchdb/issues/6454\n // -Infinity does not work since pouchdb 6.2.0\n query.selector[key].$gt = -9999999999999999999999999999;\n break;\n case 'string':\n /**\n * strings need an empty string, see\n * @link https://github.com/pubkey/rxdb/issues/585\n */\n if (typeof query.selector[key] !== 'string') {\n query.selector[key].$gt = '';\n }\n break;\n default:\n query.selector[key].$gt = null;\n break;\n }\n }\n });\n }\n\n // regex does not work over the primary key\n if (\n overwritable.isDevMode() &&\n query.selector &&\n query.selector[primaryKey as any] &&\n query.selector[primaryKey as any].$regex\n ) {\n throw newRxError('QU4', {\n path: primaryKey as any,\n query: mutateableQuery\n });\n }\n\n // primary-swap sorting\n if (query.sort) {\n const sortArray: MangoQuerySortPart[] = query.sort.map(part => {\n const key = Object.keys(part)[0];\n const direction: MangoQuerySortDirection = Object.values(part)[0];\n const useKey = key === primaryKey ? '_id' : key;\n const newPart = { [useKey]: direction };\n return newPart as any;\n });\n query.sort = sortArray;\n }\n\n // strip empty selectors\n Object.entries(ensureNotFalsy(query.selector)).forEach(([k, v]) => {\n if (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys((v as any)).length === 0\n ) {\n delete ensureNotFalsy(query.selector)[k];\n }\n });\n\n /**\n * Set use_index\n * @link https://pouchdb.com/guides/mango-queries.html#use_index\n */\n if (mutateableQuery.index) {\n const indexMaybeArray = mutateableQuery.index;\n let indexArray: string[] = isMaybeReadonlyArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray];\n indexArray = indexArray.map(str => {\n if (str === primaryKey) {\n return '_id';\n } else {\n return str;\n }\n });\n const indexName = getPouchIndexDesignDocNameByIndex(indexArray);\n delete query.index;\n (query as any).use_index = indexName;\n }\n\n query.selector = primarySwapPouchDbQuerySelector(query.selector, primaryKey);\n\n return query;\n}\n"],"mappings":";;;;;;;AAAA;AAIA;AAEA;AAUA;AAeA;AACA;AAEO,IAAMA,qBAAuC,GAAG;EACnDC,iBAAiB,6BACbC,MAA+C,EAC/CC,KAA4B,EACU;IAAA;IACtC,IAAMC,WAAkC,GAAG,IAAAC,2CAA2B,EAACH,MAAM,CAACI,UAAU,CAAQ;IAChG,IAAMC,WAAiC,GAAGJ,KAAK,CAACK,IAAI,GAAIL,KAAK,CAACK,IAAI,GAAW,kBACxEJ,WAAW,IAAG,KAAK,QACtB;IACF,IAAMK,QAAQ,GAAGN,KAAK,CAACM,QAAQ,GAAGN,KAAK,CAACM,QAAQ,GAAG,CAAC,CAAC;IACrD,IAAMC,cAAc,GAAGC,MAAM,CACxBC,IAAI,CAACH,QAAQ,CAAC,CACdI,MAAM,CAAC,UAAAC,GAAG;MAAA,OAAI,CAACA,GAAG,CAACC,UAAU,CAAC,GAAG,CAAC;IAAA,EAAC;IAExC,IAAMC,GAA2C,GAAG,SAA9CA,GAA2C,CAAIC,CAAY,EAAEC,CAAY,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,IAAVuB,CAAC;MAAEC,CAAC;IACzD,IACI,OAAOA,CAAC,KAAK,QAAQ,IACrBA,CAAC,KAAK,IAAI,IACV,CAACC,KAAK,CAACC,OAAO,CAACF,CAAC,CAAC,IACjBxD,MAAM,CAACC,IAAI,CAAEuD,CAAC,CAAS,CAACxC,MAAM,KAAK,CAAC,EACtC;MACE,OAAO,IAAAsC,oBAAc,EAAC9D,KAAK,CAACM,QAAQ,CAAC,CAACyD,CAAC,CAAC;IAC5C;EACJ,CAAC,CAAC;;EAEF;AACJ;AACA;AACA;EACI,IAAI5B,eAAe,CAACgC,KAAK,EAAE;IACvB,IAAMC,eAAe,GAAGjC,eAAe,CAACgC,KAAK;IAC7C,IAAIE,UAAoB,GAAG,IAAAC,0BAAoB,EAACF,eAAe,CAAC,GAAGA,eAAe,GAAG,CAACA,eAAe,CAAC;IACtGC,UAAU,GAAGA,UAAU,CAAClD,GAAG,CAAC,UAAAoD,GAAG,EAAI;MAC/B,IAAIA,GAAG,KAAKpE,UAAU,EAAE;QACpB,OAAO,KAAK;MAChB,CAAC,MAAM;QACH,OAAOoE,GAAG;MACd;IACJ,CAAC,CAAC;IACF,IAAMC,SAAS,GAAG,IAAAC,gDAAiC,EAACJ,UAAU,CAAC;IAC/D,OAAOrE,KAAK,CAACmE,KAAK;IACjBnE,KAAK,CAAS0E,SAAS,GAAGF,SAAS;EACxC;EAEAxE,KAAK,CAACM,QAAQ,GAAG,IAAAqE,8CAA+B,EAAC3E,KAAK,CAACM,QAAQ,EAAEH,UAAU,CAAC;EAE5E,OAAOH,KAAK;AAChB"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouchdb-helper.js b/dist/lib/plugins/pouchdb/pouchdb-helper.js deleted file mode 100644 index 6dc96a3f3f2..00000000000 --- a/dist/lib/plugins/pouchdb/pouchdb-helper.js +++ /dev/null @@ -1,387 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RX_STORAGE_NAME_POUCHDB = exports.RXDB_POUCH_DELETED_FLAG = exports.POUCHDB_META_FIELDNAME = exports.POUCHDB_LOCAL_PREFIX_LENGTH = exports.POUCHDB_LOCAL_PREFIX = exports.POUCHDB_DESIGN_PREFIX = exports.POUCHDB_CHECKPOINT_SCHEMA = exports.OPEN_POUCH_INSTANCES = exports.OPEN_POUCHDB_STORAGE_INSTANCES = void 0; -exports.getEventKey = getEventKey; -exports.getPouchIndexDesignDocNameByIndex = getPouchIndexDesignDocNameByIndex; -exports.hashAttachmentData = hashAttachmentData; -exports.openPouchId = openPouchId; -exports.pouchChangeRowToChangeEvent = pouchChangeRowToChangeEvent; -exports.pouchChangeRowToChangeStreamEvent = pouchChangeRowToChangeStreamEvent; -exports.pouchDocumentDataToRxDocumentData = pouchDocumentDataToRxDocumentData; -exports.pouchHash = pouchHash; -exports.pouchStripLocalFlagFromPrimary = pouchStripLocalFlagFromPrimary; -exports.pouchSwapIdToPrimary = pouchSwapIdToPrimary; -exports.pouchSwapIdToPrimaryString = pouchSwapIdToPrimaryString; -exports.pouchSwapPrimaryToId = pouchSwapPrimaryToId; -exports.primarySwapPouchDbQuerySelector = primarySwapPouchDbQuerySelector; -exports.rxDocumentDataToPouchDocumentData = rxDocumentDataToPouchDocumentData; -exports.writeAttachmentsToAttachments = void 0; -var _pouchdbMd = require("pouchdb-md5"); -var _util = require("../../util"); -var _rxError = require("../../rx-error"); -var _rxStorageHelper = require("../../rx-storage-helper"); -var writeAttachmentsToAttachments = function writeAttachmentsToAttachments(attachments) { - try { - if (!attachments) { - return Promise.resolve({}); - } - var ret = {}; - return Promise.resolve(Promise.all(Object.entries(attachments).map(function (_ref4) { - try { - var key = _ref4[0], - obj = _ref4[1]; - if (!obj.type) { - throw (0, _rxError.newRxError)('SNH', { - args: { - obj: obj - } - }); - } - /** - * Is write attachment, - * so we have to remove the data to have a - * non-write attachment. - */ - var _temp3 = function () { - if (obj.data) { - var _temp2 = function _temp2(dataAsBase64String) { - return Promise.resolve(hashAttachmentData(dataAsBase64String)).then(function (hash) { - var length = (0, _rxStorageHelper.getAttachmentSize)(dataAsBase64String); - ret[key] = { - digest: 'md5-' + hash, - length: length, - type: _asWrite.type - }; - }); - }; - var _asWrite = obj; - var data = _asWrite.data; - var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(data); - if (isBuffer) { - data = new Blob([data]); - } - var _temp = typeof data === 'string'; - return _temp ? _temp2(data) : Promise.resolve(_util.blobBufferUtil.toBase64String(data)).then(_temp2); - } else { - ret[key] = obj; - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.writeAttachmentsToAttachments = writeAttachmentsToAttachments; -var RX_STORAGE_NAME_POUCHDB = 'pouchdb'; - -/** - * Used to check in tests if all instances have been cleaned up. - */ -exports.RX_STORAGE_NAME_POUCHDB = RX_STORAGE_NAME_POUCHDB; -var OPEN_POUCHDB_STORAGE_INSTANCES = new Set(); - -/** - * All open PouchDB instances are stored here - * so that we can find them again when needed in the internals. - */ -exports.OPEN_POUCHDB_STORAGE_INSTANCES = OPEN_POUCHDB_STORAGE_INSTANCES; -var OPEN_POUCH_INSTANCES = new Map(); -exports.OPEN_POUCH_INSTANCES = OPEN_POUCH_INSTANCES; -function openPouchId(databaseInstanceToken, databaseName, collectionName, schemaVersion) { - return [databaseInstanceToken, databaseName, collectionName, schemaVersion + ''].join('||'); -} - -/** - * prefix of local pouchdb documents - */ -var POUCHDB_LOCAL_PREFIX = '_local/'; -exports.POUCHDB_LOCAL_PREFIX = POUCHDB_LOCAL_PREFIX; -var POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX.length; - -/** - * Pouchdb stores indexes as design documents, - * we have to filter them out and not return the - * design documents to the outside. - */ -exports.POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX_LENGTH; -var POUCHDB_DESIGN_PREFIX = '_design/'; - -/** - * PouchDB does not allow to add custom properties - * that start with lodash like RxDB's _meta field. - * So we have to map this field into a non-lodashed field. - */ -exports.POUCHDB_DESIGN_PREFIX = POUCHDB_DESIGN_PREFIX; -var POUCHDB_META_FIELDNAME = 'rxdbMeta'; -exports.POUCHDB_META_FIELDNAME = POUCHDB_META_FIELDNAME; -function pouchSwapIdToPrimary(primaryKey, docData) { - if (primaryKey === '_id' || docData[primaryKey]) { - return docData; - } - docData = (0, _util.flatClone)(docData); - docData[primaryKey] = docData._id; - delete docData._id; - return docData; -} -function pouchSwapIdToPrimaryString(primaryKey, str) { - if (str === '_id') { - return primaryKey; - } else { - return str; - } -} -function pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc) { - var useDoc = pouchSwapIdToPrimary(primaryKey, pouchDoc); - - // always flat clone because we mutate the _attachments property. - useDoc = (0, _util.flatClone)(useDoc); - delete useDoc._revisions; - - // ensure deleted flag is set. - useDoc._deleted = !!useDoc._deleted; - useDoc._attachments = {}; - if (pouchDoc._attachments) { - Object.entries(pouchDoc._attachments).forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; - if (value.data) { - useDoc._attachments[key] = { - data: value.data, - type: value.type ? value.type : value.content_type - }; - } else { - useDoc._attachments[key] = { - digest: value.digest, - // TODO why do we need to access value.type? - type: value.type ? value.type : value.content_type, - length: value.length - }; - } - }); - } - useDoc._meta = useDoc[POUCHDB_META_FIELDNAME]; - delete useDoc[POUCHDB_META_FIELDNAME]; - return useDoc; -} -function rxDocumentDataToPouchDocumentData(primaryKey, doc) { - var pouchDoc = pouchSwapPrimaryToId(primaryKey, doc); - - // always flat clone because we mutate the _attachments property. - pouchDoc = (0, _util.flatClone)(pouchDoc); - pouchDoc._attachments = {}; - if (doc._attachments) { - Object.entries(doc._attachments).forEach(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; - var useValue = value; - if (useValue.data) { - pouchDoc._attachments[key] = { - data: useValue.data, - content_type: useValue.type - }; - } else { - pouchDoc._attachments[key] = { - digest: useValue.digest, - content_type: useValue.type, - length: useValue.length, - stub: true - }; - } - }); - } - pouchDoc[POUCHDB_META_FIELDNAME] = pouchDoc._meta; - delete pouchDoc._meta; - return pouchDoc; -} - -/** - * Swaps the primaryKey of the document - * to the _id property. - */ -function pouchSwapPrimaryToId(primaryKey, docData) { - // optimisation shortcut - if (primaryKey === '_id') { - return docData; - } - var idValue = docData[primaryKey]; - var ret = (0, _util.flatClone)(docData); - delete ret[primaryKey]; - ret._id = idValue; - return ret; -} - -/** - * in: '_local/foobar' - * out: 'foobar' - */ -function pouchStripLocalFlagFromPrimary(str) { - return str.substring(POUCHDB_LOCAL_PREFIX.length); -} -function getEventKey(pouchDBInstance, primary, change) { - var useRev = change.doc ? change.doc._rev : change.previous._rev; - var eventKey = pouchDBInstance.name + '|' + primary + '|' + change.operation + '|' + useRev; - return eventKey; -} -function pouchChangeRowToChangeEvent(primaryKey, pouchDoc) { - if (!pouchDoc) { - throw (0, _rxError.newRxError)('SNH', { - args: { - pouchDoc: pouchDoc - } - }); - } - var id = pouchDoc._id; - var doc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); - var revHeight = doc._rev ? (0, _util.getHeightOfRevision)(doc._rev) : 1; - if (pouchDoc._deleted) { - return { - operation: 'DELETE', - id: id, - doc: null, - previous: doc - }; - } else if (revHeight === 1) { - return { - operation: 'INSERT', - id: id, - doc: doc, - previous: null - }; - } else { - return { - operation: 'UPDATE', - id: id, - doc: doc, - previous: 'UNKNOWN' - }; - } -} -function pouchChangeRowToChangeStreamEvent(primaryKey, pouchRow) { - var doc = pouchRow.doc; - if (!doc) { - throw (0, _rxError.newRxError)('SNH', { - args: { - pouchRow: pouchRow - } - }); - } - var revHeight = (0, _util.getHeightOfRevision)(doc._rev); - if (pouchRow.deleted) { - var previousDoc = (0, _util.flatClone)(pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc)); - var ev = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'DELETE', - doc: null, - previous: previousDoc - }; - return ev; - } else if (revHeight === 1) { - var _ev = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'INSERT', - doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), - previous: null - }; - return _ev; - } else { - var _ev2 = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'UPDATE', - doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), - previous: 'UNKNOWN' - }; - return _ev2; - } -} - -/** - * Runs a primary swap with transform all custom primaryKey occurrences - * into '_id' - * @recursive - */ -function primarySwapPouchDbQuerySelector(selector, primaryKey) { - if (primaryKey === '_id') { - return selector; - } - if (Array.isArray(selector)) { - return selector.map(function (item) { - return primarySwapPouchDbQuerySelector(item, primaryKey); - }); - } else if (typeof selector === 'object') { - var ret = {}; - Object.entries(selector).forEach(function (_ref3) { - var k = _ref3[0], - v = _ref3[1]; - if (k === primaryKey) { - ret._id = v; - } else { - if (k.startsWith('$')) { - ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); - } else { - ret[k] = v; - } - } - }); - return ret; - } else { - return selector; - } -} -function pouchHash(data) { - return new Promise(function (res) { - (0, _pouchdbMd.binaryMd5)(data, function (digest) { - res(digest); - }); - }); -} - -/** - * Runs the same hashing as PouchDB would do. - * Used to pre-calculated the hashes which is required to emit the correct events. - */ -function hashAttachmentData(attachmentBase64String) { - var binary; - try { - binary = atob(attachmentBase64String); - } catch (err) { - console.log('hashAttachmentData() could not run b64DecodeUnicode() on ' + attachmentBase64String); - throw err; - } - return pouchHash(binary); -} -function getPouchIndexDesignDocNameByIndex(index) { - var indexName = 'idx-rxdb-index-' + index.join(','); - return indexName; -} - -/** - * PouchDB has not way to read deleted local documents - * out of the database. - * So instead of deleting them, we set a custom deleted flag. - */ -var RXDB_POUCH_DELETED_FLAG = 'rxdb-pouch-deleted'; -exports.RXDB_POUCH_DELETED_FLAG = RXDB_POUCH_DELETED_FLAG; -var POUCHDB_CHECKPOINT_SCHEMA = { - type: 'object', - properties: { - sequence: { - type: 'number' - } - }, - required: ['sequence'], - additionalProperties: false -}; -exports.POUCHDB_CHECKPOINT_SCHEMA = POUCHDB_CHECKPOINT_SCHEMA; -//# sourceMappingURL=pouchdb-helper.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/pouchdb-helper.js.map b/dist/lib/plugins/pouchdb/pouchdb-helper.js.map deleted file mode 100644 index 1ff817cd691..00000000000 --- a/dist/lib/plugins/pouchdb/pouchdb-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-helper.js","names":["writeAttachmentsToAttachments","attachments","ret","Promise","all","Object","entries","map","key","obj","type","newRxError","args","data","dataAsBase64String","hashAttachmentData","hash","length","getAttachmentSize","digest","asWrite","isBuffer","Buffer","Blob","blobBufferUtil","toBase64String","RX_STORAGE_NAME_POUCHDB","OPEN_POUCHDB_STORAGE_INSTANCES","Set","OPEN_POUCH_INSTANCES","Map","openPouchId","databaseInstanceToken","databaseName","collectionName","schemaVersion","join","POUCHDB_LOCAL_PREFIX","POUCHDB_LOCAL_PREFIX_LENGTH","POUCHDB_DESIGN_PREFIX","POUCHDB_META_FIELDNAME","pouchSwapIdToPrimary","primaryKey","docData","flatClone","_id","pouchSwapIdToPrimaryString","str","pouchDocumentDataToRxDocumentData","pouchDoc","useDoc","_revisions","_deleted","_attachments","forEach","value","content_type","_meta","rxDocumentDataToPouchDocumentData","doc","pouchSwapPrimaryToId","useValue","stub","idValue","pouchStripLocalFlagFromPrimary","substring","getEventKey","pouchDBInstance","primary","change","useRev","_rev","previous","eventKey","name","operation","pouchChangeRowToChangeEvent","id","revHeight","getHeightOfRevision","pouchChangeRowToChangeStreamEvent","pouchRow","deleted","previousDoc","ev","sequence","seq","primarySwapPouchDbQuerySelector","selector","Array","isArray","item","k","v","startsWith","pouchHash","res","binaryMd5","attachmentBase64String","binary","atob","err","console","log","getPouchIndexDesignDocNameByIndex","index","indexName","RXDB_POUCH_DELETED_FLAG","POUCHDB_CHECKPOINT_SCHEMA","properties","required","additionalProperties"],"sources":["../../../../src/plugins/pouchdb/pouchdb-helper.ts"],"sourcesContent":["import type {\n ChangeStreamEvent,\n DeepReadonly,\n JsonSchema,\n MaybeReadonly,\n PouchChangeRow,\n PouchCheckpoint,\n PouchDBInstance,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxDocumentData,\n RxDocumentWriteData,\n RxLocalDocumentData,\n StringKeys,\n WithAttachments\n} from '../../types';\nimport type { RxStorageInstancePouch } from './rx-storage-instance-pouch';\nimport { binaryMd5 } from 'pouchdb-md5';\nimport {\n blobBufferUtil,\n flatClone,\n getHeightOfRevision\n} from '../../util';\nimport { newRxError } from '../../rx-error';\nimport type { ChangeEvent } from 'event-reduce-js';\nimport { getAttachmentSize } from '../../rx-storage-helper';\n\nexport type PouchStorageInternals = {\n pouchInstanceId: string;\n pouch: PouchDBInstance;\n};\n\n\nexport const RX_STORAGE_NAME_POUCHDB = 'pouchdb';\n\n/**\n * Used to check in tests if all instances have been cleaned up.\n */\nexport const OPEN_POUCHDB_STORAGE_INSTANCES: Set> = new Set();\n\n/**\n * All open PouchDB instances are stored here\n * so that we can find them again when needed in the internals.\n */\nexport const OPEN_POUCH_INSTANCES: Map = new Map();\nexport function openPouchId(\n databaseInstanceToken: string,\n databaseName: string,\n collectionName: string,\n schemaVersion: number\n): string {\n return [\n databaseInstanceToken,\n databaseName,\n collectionName,\n schemaVersion + ''\n ].join('||');\n}\n\n\n/**\n * prefix of local pouchdb documents\n */\nexport const POUCHDB_LOCAL_PREFIX: '_local/' = '_local/';\nexport const POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX.length;\n\n/**\n * Pouchdb stores indexes as design documents,\n * we have to filter them out and not return the\n * design documents to the outside.\n */\nexport const POUCHDB_DESIGN_PREFIX: '_design/' = '_design/';\n\n\n/**\n * PouchDB does not allow to add custom properties\n * that start with lodash like RxDB's _meta field.\n * So we have to map this field into a non-lodashed field.\n */\nexport const POUCHDB_META_FIELDNAME = 'rxdbMeta';\n\nexport function pouchSwapIdToPrimary(\n primaryKey: StringKeys>,\n docData: any\n): any {\n\n if (primaryKey === '_id' || docData[primaryKey]) {\n return docData;\n }\n\n docData = flatClone(docData);\n docData[primaryKey] = docData._id;\n delete docData._id;\n\n return docData;\n}\n\nexport function pouchSwapIdToPrimaryString(\n primaryKey: StringKeys>,\n str: keyof T\n): StringKeys> {\n if (str === '_id') {\n return primaryKey;\n } else {\n return str as any;\n }\n}\n\nexport function pouchDocumentDataToRxDocumentData(\n primaryKey: StringKeys>,\n pouchDoc: WithAttachments\n): RxDocumentData {\n let useDoc: RxDocumentData = pouchSwapIdToPrimary(primaryKey, pouchDoc);\n\n // always flat clone because we mutate the _attachments property.\n useDoc = flatClone(useDoc);\n delete (useDoc as any)._revisions;\n\n // ensure deleted flag is set.\n useDoc._deleted = !!useDoc._deleted;\n\n useDoc._attachments = {};\n if (pouchDoc._attachments) {\n Object.entries(pouchDoc._attachments).forEach(([key, value]) => {\n if ((value as any).data) {\n useDoc._attachments[key] = {\n data: (value as any).data,\n type: (value as any).type ? (value as any).type : (value as any).content_type\n } as any;\n } else {\n useDoc._attachments[key] = {\n digest: value.digest,\n // TODO why do we need to access value.type?\n type: (value as any).type ? (value as any).type : value.content_type,\n length: value.length\n };\n }\n });\n }\n\n useDoc._meta = (useDoc as any)[POUCHDB_META_FIELDNAME];\n delete (useDoc as any)[POUCHDB_META_FIELDNAME];\n\n return useDoc;\n}\n\nexport function rxDocumentDataToPouchDocumentData(\n primaryKey: StringKeys>,\n doc: RxDocumentData | RxDocumentWriteData\n): WithAttachments {\n let pouchDoc: WithAttachments = pouchSwapPrimaryToId(primaryKey, doc);\n\n // always flat clone because we mutate the _attachments property.\n pouchDoc = flatClone(pouchDoc);\n\n pouchDoc._attachments = {};\n if (doc._attachments) {\n Object.entries(doc._attachments).forEach(([key, value]) => {\n const useValue: RxAttachmentWriteData & RxAttachmentData = value as any;\n if (useValue.data) {\n (pouchDoc as any)._attachments[key] = {\n data: useValue.data,\n content_type: useValue.type\n };\n } else {\n (pouchDoc as any)._attachments[key] = {\n digest: useValue.digest,\n content_type: useValue.type,\n length: useValue.length,\n stub: true\n };\n }\n });\n }\n\n (pouchDoc as any)[POUCHDB_META_FIELDNAME] = (pouchDoc as any)._meta;\n delete (pouchDoc as any)._meta;\n\n return pouchDoc as any;\n}\n\n\n/**\n * Swaps the primaryKey of the document\n * to the _id property.\n */\nexport function pouchSwapPrimaryToId(\n primaryKey: StringKeys>,\n docData: any\n): RxDocType & { _id: string; } {\n // optimisation shortcut\n if (primaryKey === '_id') {\n return docData;\n }\n\n const idValue = docData[primaryKey];\n const ret = flatClone(docData);\n delete ret[primaryKey];\n ret._id = idValue;\n return ret;\n}\n\n/**\n * in: '_local/foobar'\n * out: 'foobar'\n */\nexport function pouchStripLocalFlagFromPrimary(str: string): string {\n return str.substring(POUCHDB_LOCAL_PREFIX.length);\n}\n\nexport function getEventKey(\n pouchDBInstance: PouchDBInstance,\n primary: string,\n change: ChangeEvent>\n): string {\n const useRev = change.doc ? change.doc._rev : change.previous._rev;\n const eventKey = pouchDBInstance.name + '|' + primary + '|' + change.operation + '|' + useRev;\n return eventKey;\n}\n\nexport function pouchChangeRowToChangeEvent(\n primaryKey: StringKeys,\n pouchDoc: any\n): ChangeEvent> {\n if (!pouchDoc) {\n throw newRxError('SNH', { args: { pouchDoc } });\n }\n const id = pouchDoc._id;\n\n const doc = pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchDoc as any\n );\n const revHeight = doc._rev ? getHeightOfRevision(doc._rev) : 1;\n\n if (pouchDoc._deleted) {\n return {\n operation: 'DELETE',\n id,\n doc: null,\n previous: doc\n };\n } else if (revHeight === 1) {\n return {\n operation: 'INSERT',\n id,\n doc,\n previous: null\n };\n } else {\n return {\n operation: 'UPDATE',\n id,\n doc: doc,\n previous: 'UNKNOWN'\n };\n }\n}\n\nexport function pouchChangeRowToChangeStreamEvent(\n primaryKey: StringKeys,\n pouchRow: PouchChangeRow\n): ChangeStreamEvent {\n const doc = pouchRow.doc;\n if (!doc) {\n throw newRxError('SNH', { args: { pouchRow } });\n }\n const revHeight = getHeightOfRevision(doc._rev);\n\n if (pouchRow.deleted) {\n const previousDoc = flatClone(\n pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchRow.doc as any\n )\n );\n const ev: ChangeStreamEvent = {\n sequence: pouchRow.seq,\n id: pouchRow.id,\n operation: 'DELETE',\n doc: null,\n previous: previousDoc\n };\n return ev;\n } else if (revHeight === 1) {\n const ev: ChangeStreamEvent = {\n sequence: pouchRow.seq,\n id: pouchRow.id,\n operation: 'INSERT',\n doc: pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchRow.doc as any\n ),\n previous: null\n };\n return ev;\n } else {\n const ev: ChangeStreamEvent = {\n sequence: pouchRow.seq,\n id: pouchRow.id,\n operation: 'UPDATE',\n doc: pouchDocumentDataToRxDocumentData(\n primaryKey,\n pouchRow.doc as any\n ),\n previous: 'UNKNOWN'\n };\n return ev;\n }\n}\n\n\n/**\n * Runs a primary swap with transform all custom primaryKey occurrences\n * into '_id'\n * @recursive\n */\nexport function primarySwapPouchDbQuerySelector(\n selector: any,\n primaryKey: StringKeys>\n): any {\n if (primaryKey === '_id') {\n return selector;\n }\n if (Array.isArray(selector)) {\n return selector.map(item => primarySwapPouchDbQuerySelector(item, primaryKey));\n } else if (typeof selector === 'object') {\n const ret: any = {};\n Object.entries(selector).forEach(([k, v]) => {\n if (k === primaryKey) {\n ret._id = v;\n } else {\n if (k.startsWith('$')) {\n ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey);\n } else {\n ret[k] = v;\n }\n }\n });\n return ret;\n } else {\n return selector;\n }\n}\n\nexport function pouchHash(data: Buffer | Blob | string): Promise {\n return new Promise(res => {\n binaryMd5(data, (digest: string) => {\n res(digest);\n });\n });\n}\n\n\n/**\n * Runs the same hashing as PouchDB would do.\n * Used to pre-calculated the hashes which is required to emit the correct events.\n */\nexport function hashAttachmentData(\n attachmentBase64String: string\n): Promise {\n let binary;\n try {\n binary = atob(attachmentBase64String);\n } catch (err) {\n console.log('hashAttachmentData() could not run b64DecodeUnicode() on ' + attachmentBase64String);\n throw err;\n }\n return pouchHash(binary);\n}\n\nexport async function writeAttachmentsToAttachments(\n attachments: { [attachmentId: string]: RxAttachmentData | RxAttachmentWriteData; }\n): Promise<{ [attachmentId: string]: RxAttachmentData; }> {\n if (!attachments) {\n return {};\n }\n const ret: { [attachmentId: string]: RxAttachmentData; } = {};\n await Promise.all(\n Object.entries(attachments)\n .map(async ([key, obj]) => {\n if (!obj.type) {\n throw newRxError('SNH', { args: { obj } });\n }\n /**\n * Is write attachment,\n * so we have to remove the data to have a\n * non-write attachment.\n */\n if ((obj as RxAttachmentWriteData).data) {\n const asWrite = (obj as RxAttachmentWriteData);\n let data: any = asWrite.data;\n const isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(data);\n if (isBuffer) {\n data = new Blob([data]);\n }\n const dataAsBase64String = typeof data === 'string' ? data : await blobBufferUtil.toBase64String(data);\n const hash = await hashAttachmentData(dataAsBase64String);\n const length = getAttachmentSize(dataAsBase64String);\n ret[key] = {\n digest: 'md5-' + hash,\n length,\n type: asWrite.type\n };\n } else {\n ret[key] = obj as RxAttachmentData;\n }\n })\n );\n return ret;\n}\n\nexport function getPouchIndexDesignDocNameByIndex(\n index: MaybeReadonly\n): string {\n const indexName = 'idx-rxdb-index-' + index.join(',');\n return indexName;\n}\n\n/**\n * PouchDB has not way to read deleted local documents\n * out of the database.\n * So instead of deleting them, we set a custom deleted flag.\n */\nexport const RXDB_POUCH_DELETED_FLAG = 'rxdb-pouch-deleted' as const;\n\n\nexport type RxLocalDocumentDataWithCustomDeletedField = RxLocalDocumentData & {\n [k in typeof RXDB_POUCH_DELETED_FLAG]?: boolean;\n};\n\n\nexport const POUCHDB_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n sequence: {\n type: 'number'\n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,GAAG;EACd,CAAC,MAAM;IACH,OAAOsF,QAAQ;EACnB;AACJ;AAEO,SAASO,SAAS,CAAClF,IAA4B,EAAmB;EACrE,OAAO,IAAIV,OAAO,CAAC,UAAA6F,GAAG,EAAI;IACtB,IAAAC,oBAAS,EAACpF,IAAI,EAAE,UAACM,MAAc,EAAK;MAChC6E,GAAG,CAAC7E,MAAM,CAAC;IACf,CAAC,CAAC;EACN,CAAC,CAAC;AACN;;AAGA;AACA;AACA;AACA;AACO,SAASJ,kBAAkB,CAC9BmF,sBAA8B,EACf;EACf,IAAIC,MAAM;EACV,IAAI;IACAA,MAAM,GAAGC,IAAI,CAACF,sBAAsB,CAAC;EACzC,CAAC,CAAC,OAAOG,GAAG,EAAE;IACVC,OAAO,CAACC,GAAG,CAAC,2DAA2D,GAAGL,sBAAsB,CAAC;IACjG,MAAMG,GAAG;EACb;EACA,OAAON,SAAS,CAACI,MAAM,CAAC;AAC5B;AA2CO,SAASK,iCAAiC,CAC7CC,KAA8B,EACxB;EACN,IAAMC,SAAS,GAAG,iBAAiB,GAAGD,KAAK,CAACrE,IAAI,CAAC,GAAG,CAAC;EACrD,OAAOsE,SAAS;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACO,IAAMC,uBAAuB,GAAG,oBAA6B;AAAC;AAQ9D,IAAMC,yBAAoE,GAAG;EAChFlG,IAAI,EAAE,QAAQ;EACdmG,UAAU,EAAE;IACRxB,QAAQ,EAAE;MACN3E,IAAI,EAAE;IACV;EACJ,CAAC;EACDoG,QAAQ,EAAE,CACN,UAAU,CACb;EACDC,oBAAoB,EAAE;AAC1B,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/rx-storage-instance-pouch.js b/dist/lib/plugins/pouchdb/rx-storage-instance-pouch.js deleted file mode 100644 index a23e1b8aec6..00000000000 --- a/dist/lib/plugins/pouchdb/rx-storage-instance-pouch.js +++ /dev/null @@ -1,600 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxStorageInstancePouch = void 0; -var _obliviousSet = require("oblivious-set"); -var _rxjs = require("rxjs"); -var _rxError = require("../../rx-error"); -var _pouchdbHelper = require("./pouchdb-helper"); -var _util = require("../../util"); -var _customEventsPlugin = require("./custom-events-plugin"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -/** - * Because we internally use the findDocumentsById() - * method, it is defined here because RxStorage wrappers - * might swap out the function. - */ -var pouchFindDocumentsById = function pouchFindDocumentsById(instance, ids, deleted) { - try { - ensureNotClosed(instance); - var ret = {}; - - /** - * On deleted documents, PouchDB will only return the tombstone. - * So we have to get the properties directly for each document - * with the hack of getting the changes and then make one request per document - * with the latest revision. - * TODO create an issue at pouchdb on how to get the document data of deleted documents, - * when one past revision was written via new_edits=false - * @link https://stackoverflow.com/a/63516761/3443137 - */ - if (deleted) { - instance.nonParallelQueue = instance.nonParallelQueue.then(function () { - try { - return Promise.resolve(instance.internals.pouch.changes({ - live: false, - since: 0, - doc_ids: ids, - style: 'all_docs' - })).then(function (viaChanges) { - return Promise.resolve(Promise.all(viaChanges.results.map(function (result) { - try { - return Promise.resolve(instance.internals.pouch.get(result.id, { - rev: result.changes[0].rev, - deleted: 'ok', - style: 'all_docs' - })).then(function (firstDoc) { - var useFirstDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(instance.primaryPath, firstDoc); - ret[result.id] = useFirstDoc; - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(instance.nonParallelQueue).then(function () { - return ret; - }); - } else { - instance.nonParallelQueue = instance.nonParallelQueue.then(function () { - try { - return Promise.resolve(instance.internals.pouch.allDocs({ - include_docs: true, - keys: ids - })).then(function (pouchResult) { - pouchResult.rows.filter(function (row) { - return !!row.doc; - }).forEach(function (row) { - var docData = row.doc; - docData = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(instance.primaryPath, docData); - ret[row.id] = docData; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(instance.nonParallelQueue).then(function () { - return ret; - }); - } - } catch (e) { - return Promise.reject(e); - } -}; -var lastId = 0; -var RxStorageInstancePouch = /*#__PURE__*/function () { - /** - * Some PouchDB operations give wrong results when they run in parallel. - * So we have to ensure they are queued up. - */ - - function RxStorageInstancePouch(storage, databaseName, collectionName, schema, internals, options) { - var _this = this; - this.id = lastId++; - this.changes$ = new _rxjs.Subject(); - this.subs = []; - this.closed = false; - this.nonParallelQueue = _util.PROMISE_RESOLVE_VOID; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - _pouchdbHelper.OPEN_POUCHDB_STORAGE_INSTANCES.add(this); - this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); - /** - * Instead of listening to pouch.changes, - * we have overwritten pouchdbs bulkDocs() - * and create our own event stream, this will work more reliable - * and does not mix up with write events from other sources. - */ - var emitter = (0, _customEventsPlugin.getCustomEventEmitterByPouch)(this.internals.pouch); - - /** - * Contains all eventIds that of emitted events, - * used because multi-instance pouchdbs often will reemit the same - * event on the other browser tab so we have to de-duplicate them. - */ - var emittedEventBulkIds = new _obliviousSet.ObliviousSet(60 * 1000); - var eventSub = emitter.subject.subscribe(function (eventBulk) { - if (eventBulk.events.length === 0 || emittedEventBulkIds.has(eventBulk.id)) { - return; - } - emittedEventBulkIds.add(eventBulk.id); - - // rewrite primaryPath of all events - eventBulk.events.forEach(function (event) { - if (event.documentData) { - event.documentData = (0, _pouchdbHelper.pouchSwapIdToPrimary)(_this.primaryPath, event.documentData); - } - if (event.previousDocumentData) { - event.previousDocumentData = (0, _pouchdbHelper.pouchSwapIdToPrimary)(_this.primaryPath, event.previousDocumentData); - } - }); - _this.changes$.next(eventBulk); - }); - this.subs.push(eventSub); - } - var _proto = RxStorageInstancePouch.prototype; - _proto.close = function close() { - ensureNotClosed(this); - this.closed = true; - this.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - _pouchdbHelper.OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); - _pouchdbHelper.OPEN_POUCH_INSTANCES["delete"](this.internals.pouchInstanceId); - - // TODO this did not work because a closed pouchdb cannot be recreated in the same process run - // await this.internals.pouch.close(); - return _util.PROMISE_RESOLVE_VOID; - }; - _proto.remove = function remove() { - try { - var _this2 = this; - ensureNotClosed(_this2); - _this2.closed = true; - _this2.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - _pouchdbHelper.OPEN_POUCHDB_STORAGE_INSTANCES["delete"](_this2); - _pouchdbHelper.OPEN_POUCH_INSTANCES["delete"](_this2.internals.pouchInstanceId); - return Promise.resolve(_this2.internals.pouch.destroy()).then(function () {}); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this3 = this; - ensureNotClosed(_this3); - if (documentWrites.length === 0) { - throw (0, _rxError.newRxError)('P2', { - args: { - documentWrites: documentWrites - } - }); - } - var writeRowById = new Map(); - var insertDocsById = new Map(); - var writeDocs = documentWrites.map(function (writeData) { - /** - * Ensure that _meta.lwt is set correctly - */ - if (writeData.document._meta.lwt < 1000 || writeData.previous && writeData.previous._meta.lwt >= writeData.document._meta.lwt) { - throw (0, _rxError.newRxError)('SNH', { - args: writeData - }); - } - - /** - * Ensure that a revision exists, - * having an empty revision here would not throw - * but just not resolve forever. - */ - if (!writeData.document._rev) { - throw (0, _rxError.newRxError)('SNH', { - args: writeData - }); - } - var primary = writeData.document[_this3.primaryPath]; - writeRowById.set(primary, writeData); - var storeDocumentData = (0, _pouchdbHelper.rxDocumentDataToPouchDocumentData)(_this3.primaryPath, writeData.document); - insertDocsById.set(primary, storeDocumentData); - return storeDocumentData; - }); - var previousDocsInDb = new Map(); - var ret = { - success: {}, - error: {} - }; - _this3.nonParallelQueue = _this3.nonParallelQueue.then(function () { - try { - return Promise.resolve(_this3.internals.pouch.bulkDocs(writeDocs, { - new_edits: false, - custom: { - primaryPath: _this3.primaryPath, - writeRowById: writeRowById, - insertDocsById: insertDocsById, - previousDocsInDb: previousDocsInDb, - context: context - } - })).then(function (pouchResult) { - return Promise.all(pouchResult.map(function (resultRow) { - try { - var writeRow = (0, _util.getFromMapOrThrow)(writeRowById, resultRow.id); - var _temp3 = function () { - if (resultRow.error) { - var previousDoc = (0, _util.getFromMapOrThrow)(previousDocsInDb, resultRow.id); - var err = { - isError: true, - status: 409, - documentId: resultRow.id, - writeRow: writeRow, - documentInDb: (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(_this3.primaryPath, previousDoc) - }; - ret.error[resultRow.id] = err; - } else { - var _temp2 = function _temp2() { - ret.success[resultRow.id] = _pushObj; - }; - var _pushObj = (0, _util.flatClone)(writeRow.document); - _pushObj = (0, _pouchdbHelper.pouchSwapIdToPrimary)(_this3.primaryPath, _pushObj); - _pushObj._rev = resultRow.rev; - - // replace the inserted attachments with their diggest - _pushObj._attachments = {}; - var _temp = function () { - if (!writeRow.document._attachments) { - writeRow.document._attachments = {}; - } else { - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeRow.document._attachments)).then(function (_writeAttachmentsToAt) { - _pushObj._attachments = _writeAttachmentsToAt; - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - })); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(_this3.nonParallelQueue).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - try { - var _this4 = this; - ensureNotClosed(_this4); - return Promise.resolve(_this4.internals.pouch.find(preparedQuery)).then(function (findResult) { - var ret = { - documents: findResult.docs.map(function (pouchDoc) { - var useDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(_this4.primaryPath, pouchDoc); - return useDoc; - }) - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.count = function count(preparedQuery) { - try { - var _this5 = this; - /** - * There is no count method in PouchDB, - * so we have to run a normal query and use the result length. - */ - return Promise.resolve(_this5.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(documentId, attachmentId) { - try { - var _this6 = this; - ensureNotClosed(_this6); - return Promise.resolve(_this6.internals.pouch.getAttachment(documentId, attachmentId)).then(function (attachmentData) { - /** - * In Node.js, PouchDB works with Buffers because it is old and Node.js did - * not support Blob at the time is was coded. - * So here we have to transform the Buffer to a Blob. - */ - var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(attachmentData); - if (isBuffer) { - attachmentData = new Blob([attachmentData]); - } - return Promise.resolve(_util.blobBufferUtil.toBase64String(attachmentData)); - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - return pouchFindDocumentsById(this, ids, deleted); - }; - _proto.changeStream = function changeStream() { - ensureNotClosed(this); - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(_minimumDeletedTime) { - ensureNotClosed(this); - /** - * PouchDB does not support purging documents. - * So instead we run a compaction that might at least help a bit - * in freeing up disc space. - * @link https://github.com/pouchdb/pouchdb/issues/802 - */ - return this.internals.pouch.compact().then(function () { - return true; - }); - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _temp5 = function _temp5() { - return Promise.resolve(pouchFindDocumentsById(_this7, changedDocuments.map(function (o) { - return o.id; - }), true)).then(function (documentsData) { - if (Object.keys(documentsData).length > 0 && checkpoint && checkpoint.sequence === lastSequence) { - /** - * When documents are returned, it makes no sense - * if the sequence is equal to the one given at the checkpoint. - */ - throw new Error('same sequence'); - } - var lastRow = (0, _util.lastOfArray)(changedDocuments); - var documents = changedDocuments.map(function (changeRow) { - return (0, _util.getFromObjectOrThrow)(documentsData, changeRow.id); - }); - return { - documents: documents, - checkpoint: lastRow ? { - sequence: lastRow.sequence - } : checkpoint ? checkpoint : { - sequence: -1 - } - }; - }); - }; - var _this7 = this; - ensureNotClosed(_this7); - if (!limit || typeof limit !== 'number') { - throw new Error('wrong limit'); - } - var pouchChangesOpts = { - live: false, - limit: limit, - include_docs: false, - since: checkpoint ? checkpoint.sequence : 0, - descending: false - }; - var lastSequence = 0; - var first = true; - var skippedDesignDocuments = 0; - var changedDocuments = []; - /** - * Because PouchDB also returns changes of _design documents, - * we have to fill up the results with more changes if this happens. - */ - var _temp4 = _for(function () { - return !!first || skippedDesignDocuments > 0; - }, void 0, function () { - first = false; - skippedDesignDocuments = 0; - return Promise.resolve(_this7.internals.pouch.changes(pouchChangesOpts)).then(function (pouchResults) { - var addChangedDocuments = pouchResults.results.filter(function (row) { - var isDesignDoc = row.id.startsWith(_pouchdbHelper.POUCHDB_DESIGN_PREFIX); - if (isDesignDoc) { - skippedDesignDocuments = skippedDesignDocuments + 1; - return false; - } else { - return true; - } - }).map(function (row) { - return { - id: row.id, - sequence: row.seq - }; - }); - changedDocuments = changedDocuments.concat(addChangedDocuments); - lastSequence = pouchResults.last_seq; - - // modify pouch options for next run of pouch.changes() - pouchChangesOpts.since = lastSequence; - pouchChangesOpts.limit = skippedDesignDocuments; - }); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new _rxjs.Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstancePouch; -}(); -exports.RxStorageInstancePouch = RxStorageInstancePouch; -function ensureNotClosed(instance) { - if (instance.closed) { - throw new Error('RxStorageInstancePouch is closed ' + instance.databaseName + '-' + instance.collectionName); - } -} -//# sourceMappingURL=rx-storage-instance-pouch.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/rx-storage-instance-pouch.js.map b/dist/lib/plugins/pouchdb/rx-storage-instance-pouch.js.map deleted file mode 100644 index f1b50fcbcbc..00000000000 --- a/dist/lib/plugins/pouchdb/rx-storage-instance-pouch.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-instance-pouch.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","pouchFindDocumentsById","instance","ids","deleted","ensureNotClosed","ret","nonParallelQueue","internals","pouch","changes","live","since","doc_ids","style","viaChanges","Promise","all","results","map","get","id","rev","firstDoc","useFirstDoc","pouchDocumentDataToRxDocumentData","primaryPath","allDocs","include_docs","keys","pouchResult","rows","filter","row","doc","forEach","docData","lastId","RxStorageInstancePouch","storage","databaseName","collectionName","schema","options","changes$","Subject","subs","closed","PROMISE_RESOLVE_VOID","OPEN_POUCHDB_STORAGE_INSTANCES","add","getPrimaryFieldOfPrimaryKey","primaryKey","emitter","getCustomEventEmitterByPouch","emittedEventBulkIds","ObliviousSet","eventSub","subject","subscribe","eventBulk","events","length","has","event","documentData","pouchSwapIdToPrimary","previousDocumentData","next","push","close","sub","unsubscribe","OPEN_POUCH_INSTANCES","pouchInstanceId","remove","destroy","bulkWrite","documentWrites","context","newRxError","args","writeRowById","Map","insertDocsById","writeDocs","writeData","document","_meta","lwt","previous","_rev","primary","set","storeDocumentData","rxDocumentDataToPouchDocumentData","previousDocsInDb","success","error","bulkDocs","new_edits","custom","resultRow","writeRow","getFromMapOrThrow","previousDoc","err","isError","status","documentId","documentInDb","pushObj","flatClone","_attachments","writeAttachmentsToAttachments","query","preparedQuery","find","findResult","documents","docs","pouchDoc","useDoc","count","mode","getAttachmentData","attachmentId","getAttachment","attachmentData","isBuffer","Buffer","Blob","blobBufferUtil","toBase64String","findDocumentsById","changeStream","asObservable","cleanup","_minimumDeletedTime","compact","getChangedDocumentsSince","limit","checkpoint","changedDocuments","documentsData","Object","sequence","lastSequence","Error","lastRow","lastOfArray","changeRow","getFromObjectOrThrow","pouchChangesOpts","descending","first","skippedDesignDocuments","pouchResults","addChangedDocuments","isDesignDoc","startsWith","POUCHDB_DESIGN_PREFIX","seq","concat","last_seq","conflictResultionTasks","resolveConflictResultionTask","_taskSolution"],"sources":["../../../../src/plugins/pouchdb/rx-storage-instance-pouch.ts"],"sourcesContent":["import { ObliviousSet } from 'oblivious-set';\nimport {\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport { newRxError } from '../../rx-error';\nimport type {\n BulkWriteRow,\n EventBulk,\n PouchBulkDocResultRow,\n PouchChangesOptionsNonLive,\n PouchCheckpoint,\n PouchSettings,\n PouchWriteError,\n PreparedQuery,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport {\n OPEN_POUCHDB_STORAGE_INSTANCES,\n OPEN_POUCH_INSTANCES,\n POUCHDB_DESIGN_PREFIX,\n pouchDocumentDataToRxDocumentData,\n PouchStorageInternals,\n pouchSwapIdToPrimary,\n rxDocumentDataToPouchDocumentData,\n writeAttachmentsToAttachments\n} from './pouchdb-helper';\nimport {\n blobBufferUtil,\n flatClone,\n getFromMapOrThrow,\n getFromObjectOrThrow,\n lastOfArray,\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport {\n getCustomEventEmitterByPouch\n} from './custom-events-plugin';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\n\n\nlet lastId = 0;\n\nexport class RxStorageInstancePouch implements RxStorageInstance<\nRxDocType,\nPouchStorageInternals,\nPouchSettings,\nPouchCheckpoint\n> {\n public readonly id: number = lastId++;\n\n private changes$: Subject>, PouchCheckpoint>> = new Subject();\n private subs: Subscription[] = [];\n public primaryPath: StringKeys>;\n\n public closed: boolean = false;\n\n\n /**\n * Some PouchDB operations give wrong results when they run in parallel.\n * So we have to ensure they are queued up.\n */\n public nonParallelQueue: Promise = PROMISE_RESOLVE_VOID;\n\n constructor(\n public readonly storage: RxStorage,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: Readonly,\n public readonly options: Readonly\n ) {\n OPEN_POUCHDB_STORAGE_INSTANCES.add(this);\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n /**\n * Instead of listening to pouch.changes,\n * we have overwritten pouchdbs bulkDocs()\n * and create our own event stream, this will work more reliable\n * and does not mix up with write events from other sources.\n */\n const emitter = getCustomEventEmitterByPouch(this.internals.pouch);\n\n /**\n * Contains all eventIds that of emitted events,\n * used because multi-instance pouchdbs often will reemit the same\n * event on the other browser tab so we have to de-duplicate them.\n */\n const emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n const eventSub = emitter.subject.subscribe((eventBulk) => {\n if (\n eventBulk.events.length === 0 ||\n emittedEventBulkIds.has(eventBulk.id)\n ) {\n return;\n }\n emittedEventBulkIds.add(eventBulk.id);\n\n // rewrite primaryPath of all events\n eventBulk.events.forEach(event => {\n if (event.documentData) {\n event.documentData = pouchSwapIdToPrimary(\n this.primaryPath,\n event.documentData as any\n );\n }\n if (event.previousDocumentData) {\n event.previousDocumentData = pouchSwapIdToPrimary(\n this.primaryPath,\n event.previousDocumentData as any\n );\n }\n });\n this.changes$.next(eventBulk);\n });\n this.subs.push(eventSub);\n }\n\n close() {\n ensureNotClosed(this);\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n OPEN_POUCHDB_STORAGE_INSTANCES.delete(this);\n OPEN_POUCH_INSTANCES.delete(this.internals.pouchInstanceId);\n\n // TODO this did not work because a closed pouchdb cannot be recreated in the same process run\n // await this.internals.pouch.close();\n return PROMISE_RESOLVE_VOID;\n }\n\n async remove() {\n ensureNotClosed(this);\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n\n OPEN_POUCHDB_STORAGE_INSTANCES.delete(this);\n OPEN_POUCH_INSTANCES.delete(this.internals.pouchInstanceId);\n\n await this.internals.pouch.destroy();\n }\n public async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise<\n RxStorageBulkWriteResponse\n > {\n ensureNotClosed(this);\n if (documentWrites.length === 0) {\n throw newRxError('P2', {\n args: {\n documentWrites\n }\n });\n }\n\n const writeRowById: Map> = new Map();\n const insertDocsById: Map = new Map();\n const writeDocs: (RxDocType & { _id: string; _rev: string; })[] = documentWrites.map(writeData => {\n\n /**\n * Ensure that _meta.lwt is set correctly\n */\n if (\n writeData.document._meta.lwt < 1000 ||\n (\n writeData.previous &&\n writeData.previous._meta.lwt >= writeData.document._meta.lwt\n )\n ) {\n throw newRxError('SNH', {\n args: writeData\n });\n }\n\n /**\n * Ensure that a revision exists,\n * having an empty revision here would not throw\n * but just not resolve forever.\n */\n if (!writeData.document._rev) {\n throw newRxError('SNH', {\n args: writeData\n });\n }\n\n const primary: string = (writeData.document as any)[this.primaryPath];\n writeRowById.set(primary, writeData);\n const storeDocumentData: any = rxDocumentDataToPouchDocumentData(\n this.primaryPath,\n writeData.document\n );\n insertDocsById.set(primary, storeDocumentData);\n return storeDocumentData;\n });\n\n const previousDocsInDb: Map> = new Map();\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n this.nonParallelQueue = this.nonParallelQueue.then(async () => {\n const pouchResult = await this.internals.pouch.bulkDocs(writeDocs, {\n new_edits: false,\n custom: {\n primaryPath: this.primaryPath,\n writeRowById,\n insertDocsById,\n previousDocsInDb,\n context\n }\n } as any);\n return Promise.all(\n pouchResult.map(async (resultRow) => {\n const writeRow = getFromMapOrThrow(writeRowById, resultRow.id);\n if ((resultRow as PouchWriteError).error) {\n const previousDoc = getFromMapOrThrow(previousDocsInDb, resultRow.id);\n const err: RxStorageBulkWriteError = {\n isError: true,\n status: 409,\n documentId: resultRow.id,\n writeRow,\n documentInDb: pouchDocumentDataToRxDocumentData(\n this.primaryPath,\n previousDoc\n )\n };\n ret.error[resultRow.id] = err;\n } else {\n let pushObj: RxDocumentData = flatClone(writeRow.document) as any;\n pushObj = pouchSwapIdToPrimary(this.primaryPath, pushObj);\n pushObj._rev = (resultRow as PouchBulkDocResultRow).rev;\n\n // replace the inserted attachments with their diggest\n pushObj._attachments = {};\n if (!writeRow.document._attachments) {\n writeRow.document._attachments = {};\n } else {\n pushObj._attachments = await writeAttachmentsToAttachments(writeRow.document._attachments);\n }\n ret.success[resultRow.id] = pushObj;\n }\n })\n );\n });\n await this.nonParallelQueue;\n return ret;\n }\n\n public async query(\n preparedQuery: PreparedQuery\n ): Promise> {\n ensureNotClosed(this);\n const findResult = await this.internals.pouch.find(preparedQuery);\n const ret: RxStorageQueryResult = {\n documents: findResult.docs.map(pouchDoc => {\n const useDoc = pouchDocumentDataToRxDocumentData(\n this.primaryPath,\n pouchDoc\n );\n return useDoc;\n })\n };\n return ret;\n }\n async count(\n preparedQuery: PreparedQuery\n ): Promise {\n /**\n * There is no count method in PouchDB,\n * so we have to run a normal query and use the result length.\n */\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n async getAttachmentData(\n documentId: string,\n attachmentId: string\n ): Promise {\n ensureNotClosed(this);\n let attachmentData = await this.internals.pouch.getAttachment(\n documentId,\n attachmentId\n );\n\n /**\n * In Node.js, PouchDB works with Buffers because it is old and Node.js did\n * not support Blob at the time is was coded.\n * So here we have to transform the Buffer to a Blob.\n */\n const isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(attachmentData);\n if (isBuffer) {\n attachmentData = new Blob([attachmentData]);\n }\n\n const ret = await blobBufferUtil.toBase64String(attachmentData);\n return ret;\n }\n\n findDocumentsById(\n ids: string[],\n deleted: boolean\n ): Promise> {\n return pouchFindDocumentsById(\n this,\n ids,\n deleted\n );\n }\n\n changeStream(): Observable>, PouchCheckpoint>> {\n ensureNotClosed(this);\n return this.changes$.asObservable();\n }\n\n cleanup(_minimumDeletedTime: number): Promise {\n ensureNotClosed(this);\n /**\n * PouchDB does not support purging documents.\n * So instead we run a compaction that might at least help a bit\n * in freeing up disc space.\n * @link https://github.com/pouchdb/pouchdb/issues/802\n */\n return this.internals.pouch\n .compact()\n .then(() => true);\n }\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: PouchCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: PouchCheckpoint;\n }> {\n ensureNotClosed(this);\n if (!limit || typeof limit !== 'number') {\n throw new Error('wrong limit');\n }\n\n const pouchChangesOpts: PouchChangesOptionsNonLive = {\n live: false,\n limit: limit,\n include_docs: false,\n since: checkpoint ? checkpoint.sequence : 0,\n descending: false\n };\n\n let lastSequence = 0;\n let first = true;\n let skippedDesignDocuments = 0;\n let changedDocuments: { id: string; sequence: number; }[] = [];\n /**\n * Because PouchDB also returns changes of _design documents,\n * we have to fill up the results with more changes if this happens.\n */\n while (first || skippedDesignDocuments > 0) {\n first = false;\n skippedDesignDocuments = 0;\n const pouchResults = await this.internals.pouch.changes(pouchChangesOpts);\n const addChangedDocuments = pouchResults.results\n .filter(row => {\n const isDesignDoc = row.id.startsWith(POUCHDB_DESIGN_PREFIX);\n if (isDesignDoc) {\n skippedDesignDocuments = skippedDesignDocuments + 1;\n return false;\n } else {\n return true;\n }\n })\n .map(row => ({\n id: row.id,\n sequence: row.seq\n }));\n changedDocuments = changedDocuments.concat(addChangedDocuments);\n lastSequence = pouchResults.last_seq;\n\n // modify pouch options for next run of pouch.changes()\n pouchChangesOpts.since = lastSequence;\n pouchChangesOpts.limit = skippedDesignDocuments;\n }\n\n const documentsData = await pouchFindDocumentsById(\n this,\n changedDocuments.map(o => o.id),\n true\n );\n\n if (\n Object.keys(documentsData).length > 0 &&\n checkpoint && checkpoint.sequence === lastSequence\n ) {\n /**\n * When documents are returned, it makes no sense\n * if the sequence is equal to the one given at the checkpoint.\n */\n throw new Error('same sequence');\n }\n\n const lastRow = lastOfArray(changedDocuments);\n const documents = changedDocuments.map(changeRow => getFromObjectOrThrow(documentsData, changeRow.id));\n\n return {\n documents,\n checkpoint: lastRow ? {\n sequence: lastRow.sequence\n } : checkpoint ? checkpoint : {\n sequence: -1\n }\n };\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n}\n\n\n\nfunction ensureNotClosed(\n instance: RxStorageInstancePouch\n) {\n if (instance.closed) {\n throw new Error('RxStorageInstancePouch is closed ' + instance.databaseName + '-' + instance.collectionName);\n }\n}\n\n\n/**\n * Because we internally use the findDocumentsById()\n * method, it is defined here because RxStorage wrappers\n * might swap out the function.\n */\nasync function pouchFindDocumentsById(\n instance: RxStorageInstancePouch,\n ids: string[],\n deleted: boolean\n): Promise> {\n ensureNotClosed(instance);\n const ret: RxDocumentDataById = {};\n\n /**\n * On deleted documents, PouchDB will only return the tombstone.\n * So we have to get the properties directly for each document\n * with the hack of getting the changes and then make one request per document\n * with the latest revision.\n * TODO create an issue at pouchdb on how to get the document data of deleted documents,\n * when one past revision was written via new_edits=false\n * @link https://stackoverflow.com/a/63516761/3443137\n */\n if (deleted) {\n instance.nonParallelQueue = instance.nonParallelQueue.then(async () => {\n const viaChanges = await instance.internals.pouch.changes({\n live: false,\n since: 0,\n doc_ids: ids,\n style: 'all_docs'\n });\n await Promise.all(\n viaChanges.results.map(async (result) => {\n const firstDoc = await instance.internals.pouch.get(\n result.id,\n {\n rev: result.changes[0].rev,\n deleted: 'ok',\n style: 'all_docs'\n }\n );\n const useFirstDoc = pouchDocumentDataToRxDocumentData(\n instance.primaryPath,\n firstDoc\n );\n ret[result.id] = useFirstDoc;\n })\n );\n });\n await instance.nonParallelQueue;\n return ret;\n } else {\n instance.nonParallelQueue = instance.nonParallelQueue.then(async () => {\n const pouchResult = await instance.internals.pouch.allDocs({\n include_docs: true,\n keys: ids\n });\n pouchResult.rows\n .filter(row => !!row.doc)\n .forEach(row => {\n let docData = row.doc;\n docData = pouchDocumentDataToRxDocumentData(\n instance.primaryPath,\n docData\n );\n ret[row.id] = docData;\n });\n });\n await instance.nonParallelQueue;\n return ret;\n }\n}\n"],"mappings":";;;;;;AAAA;AACA;AAKA;AAwBA;AAUA;AAQA;AAGA;AAZO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAI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AK,GAAGuI,YAAY;UACrCM,gBAAgB,CAACZ,KAAK,GAAGe,sBAAsB;QAAC;MACpD,CAAC;MAAA;IA8BL,CAAC;MAAA;IAAA;EAAA;EAAA,OAEDS,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAIxH,aAAO,EAAE;EACxB,CAAC;EAAA,OACKyH,4BAA4B,yCAACC,aAAyD,EAAiB;IAAA;EAAE,CAAC;EAAA;AAAA;AAAA;AAKpH,SAASlK,eAAe,CACpBH,QAAqC,EACvC;EACE,IAAIA,QAAQ,CAAC6C,MAAM,EAAE;IACjB,MAAM,IAAIqG,KAAK,CAAC,mCAAmC,GAAGlJ,QAAQ,CAACsC,YAAY,GAAG,GAAG,GAAGtC,QAAQ,CAACuC,cAAc,CAAC;EAChH;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js b/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js deleted file mode 100644 index 621f5ead645..00000000000 --- a/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js +++ /dev/null @@ -1,188 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxStoragePouch = void 0; -exports.checkPouchAdapter = checkPouchAdapter; -exports.createIndexesOnPouch = void 0; -exports.getPouchDBOfRxCollection = getPouchDBOfRxCollection; -exports.getPouchLocation = getPouchLocation; -exports.getRxStoragePouch = getRxStoragePouch; -var _util = require("../../util"); -var _pouchDb = require("./pouch-db"); -var _rxError = require("../../rx-error"); -var _rxStorageInstancePouch = require("./rx-storage-instance-pouch"); -var _pouchdbHelper = require("./pouchdb-helper"); -var _pouchdbFind = _interopRequireDefault(require("pouchdb-find")); -var _pouchStatics = require("./pouch-statics"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _customEventsPlugin = require("./custom-events-plugin"); -var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); -var _rxStorageHelper = require("../../rx-storage-helper"); -/** - * Creates the indexes of the schema inside of the pouchdb instance. - * Will skip indexes that already exist. - */ -var createIndexesOnPouch = function createIndexesOnPouch(pouch, schema) { - try { - if (!schema.indexes) { - return Promise.resolve(); - } - var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - return Promise.resolve(pouch.getIndexes()).then(function (before) { - var existingIndexes = new Set(before.indexes.map(function (idx) { - return idx.name; - })); - return Promise.resolve(Promise.all(schema.indexes.map(function (indexMaybeArray) { - var indexArray = (0, _util.isMaybeReadonlyArray)(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; - - /** - * replace primary key with _id - * because that is the enforced primary key on pouchdb. - */ - indexArray = indexArray.map(function (key) { - if (key === primaryKey) { - return '_id'; - } else { - return key; - } - }); - var indexName = (0, _pouchdbHelper.getPouchIndexDesignDocNameByIndex)(indexArray); - if (existingIndexes.has(indexName)) { - // index already exists - return; - } - - /** - * TODO we might have even better performance by doing a pouch.bulkDocs() - * on index creation - */ - return pouch.createIndex({ - name: indexName, - ddoc: indexName, - index: { - fields: indexArray - } - }); - }))).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * returns the pouchdb-database-name - */ -exports.createIndexesOnPouch = createIndexesOnPouch; -var RxStoragePouch = /*#__PURE__*/function () { - function RxStoragePouch(adapter) { - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.name = _pouchdbHelper.RX_STORAGE_NAME_POUCHDB; - this.statics = _pouchStatics.RxStoragePouchStatics; - this.adapter = adapter; - this.pouchSettings = pouchSettings; - checkPouchAdapter(adapter); - } - var _proto = RxStoragePouch.prototype; - _proto.createPouch = function createPouch(location, options) { - var pouchDbParameters = { - location: location, - adapter: (0, _util.adapterObject)(this.adapter), - settings: options - }; - var pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); - var pouch = new _pouchDb.PouchDB(pouchDbParameters.location, pouchDBOptions); - - /** - * In the past we found some errors where the PouchDB is not directly usable - * so we we had to call .info() first to ensure it can be used. - * I commented this out for now to get faster database/collection creation. - * We might have to add this again if something fails. - */ - // await pouch.info(); - - return Promise.resolve(pouch); - }; - _proto.createStorageInstance = function createStorageInstance(params) { - try { - var _this = this; - (0, _rxStorageHelper.ensureRxStorageInstanceParamsAreCorrect)(params); - var pouchLocation = getPouchLocation(params.databaseName, params.collectionName, params.schema.version); - return Promise.resolve(_this.createPouch(pouchLocation, params.options)).then(function (pouch) { - return Promise.resolve(createIndexesOnPouch(pouch, params.schema)).then(function () { - var pouchInstanceId = (0, _pouchdbHelper.openPouchId)(params.databaseInstanceToken, params.databaseName, params.collectionName, params.schema.version); - var instance = new _rxStorageInstancePouch.RxStorageInstancePouch(_this, params.databaseName, params.collectionName, params.schema, { - pouch: pouch, - pouchInstanceId: pouchInstanceId - }, params.options); - _pouchdbHelper.OPEN_POUCH_INSTANCES.set(pouchInstanceId, pouch); - (0, _rxStorageMultiinstance.addRxStorageMultiInstanceSupport)(_pouchdbHelper.RX_STORAGE_NAME_POUCHDB, params, instance); - return instance; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }; - return RxStoragePouch; -}(); -/** - * Checks if all is ok with the given adapter, - * else throws an error. - */ -exports.RxStoragePouch = RxStoragePouch; -function checkPouchAdapter(adapter) { - if (typeof adapter === 'string') { - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters[adapter]) { - throw (0, _rxError.newRxError)('DB9', { - adapter: adapter - }); - } - } else { - (0, _pouchDb.isLevelDown)(adapter); - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.leveldb) { - throw (0, _rxError.newRxError)('DB10', { - adapter: adapter - }); - } - } -} -function getPouchLocation(dbName, collectionName, schemaVersion) { - var prefix = dbName + '-rxdb-' + schemaVersion + '-'; - if (!collectionName.includes('/')) { - return prefix + collectionName; - } else { - // if collectionName is a path, we have to prefix the last part only - var split = collectionName.split('/'); - var last = split.pop(); - var ret = split.join('/'); - ret += '/' + prefix + last; - return ret; - } -} -function getPouchDBOfRxCollection(collection) { - var id = (0, _pouchdbHelper.openPouchId)(collection.database.token, collection.database.name, collection.name, collection.schema.version); - var pouch = (0, _util.getFromMapOrThrow)(_pouchdbHelper.OPEN_POUCH_INSTANCES, id); - return pouch; -} -var addedRxDBPouchPlugins = false; - -/** - * @deprecated PouchDB RxStorage is deprecated, see - * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated - */ -function getRxStoragePouch(adapter, pouchSettings) { - if (!addedRxDBPouchPlugins) { - addedRxDBPouchPlugins = true; - (0, _pouchDb.addPouchPlugin)(_pouchdbFind["default"]); - (0, _customEventsPlugin.addCustomEventsPluginToPouch)(); - } - if (!adapter) { - throw new Error('adapter missing'); - } - var storage = new RxStoragePouch(adapter, pouchSettings); - return storage; -} -//# sourceMappingURL=rx-storage-pouchdb.js.map \ No newline at end of file diff --git a/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js.map b/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js.map deleted file mode 100644 index 3ee90d18c19..00000000000 --- a/dist/lib/plugins/pouchdb/rx-storage-pouchdb.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"rx-storage-pouchdb.js","names":["createIndexesOnPouch","pouch","schema","indexes","primaryKey","getPrimaryFieldOfPrimaryKey","getIndexes","before","existingIndexes","Set","map","idx","name","Promise","all","indexMaybeArray","indexArray","isMaybeReadonlyArray","key","indexName","getPouchIndexDesignDocNameByIndex","has","createIndex","ddoc","index","fields","RxStoragePouch","adapter","pouchSettings","RX_STORAGE_NAME_POUCHDB","statics","RxStoragePouchStatics","checkPouchAdapter","createPouch","location","options","pouchDbParameters","adapterObject","settings","pouchDBOptions","Object","assign","PouchDB","resolve","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","pouchLocation","getPouchLocation","databaseName","collectionName","version","pouchInstanceId","openPouchId","databaseInstanceToken","instance","RxStorageInstancePouch","OPEN_POUCH_INSTANCES","set","addRxStorageMultiInstanceSupport","adapters","newRxError","isLevelDown","leveldb","dbName","schemaVersion","prefix","includes","split","last","pop","ret","join","getPouchDBOfRxCollection","collection","id","database","token","getFromMapOrThrow","addedRxDBPouchPlugins","getRxStoragePouch","addPouchPlugin","PouchDBFind","addCustomEventsPluginToPouch","Error","storage"],"sources":["../../../../src/plugins/pouchdb/rx-storage-pouchdb.ts"],"sourcesContent":["\nimport type {\n PouchDBInstance,\n PouchSettings,\n RxJsonSchema,\n RxStorageInstanceCreationParams,\n RxStorage,\n MaybeReadonly,\n RxCollection\n} from '../../types';\n\nimport {\n adapterObject,\n getFromMapOrThrow,\n isMaybeReadonlyArray\n} from '../../util';\nimport {\n addPouchPlugin,\n isLevelDown,\n PouchDB\n} from './pouch-db';\nimport { newRxError } from '../../rx-error';\n\nimport { RxStorageInstancePouch } from './rx-storage-instance-pouch';\nimport {\n getPouchIndexDesignDocNameByIndex,\n openPouchId,\n OPEN_POUCH_INSTANCES,\n PouchStorageInternals,\n RX_STORAGE_NAME_POUCHDB\n} from './pouchdb-helper';\nimport PouchDBFind from 'pouchdb-find';\nimport { RxStoragePouchStatics } from './pouch-statics';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { addCustomEventsPluginToPouch } from './custom-events-plugin';\nimport { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\n\n\n\nexport class RxStoragePouch implements RxStorage {\n public name: string = RX_STORAGE_NAME_POUCHDB;\n public statics = RxStoragePouchStatics;\n\n constructor(\n public adapter: any,\n public pouchSettings: PouchSettings = {}\n ) {\n checkPouchAdapter(adapter);\n }\n\n private createPouch(\n location: string,\n options: PouchSettings\n ): Promise {\n const pouchDbParameters = {\n location: location,\n adapter: adapterObject(this.adapter),\n settings: options\n };\n const pouchDBOptions = Object.assign(\n {},\n pouchDbParameters.adapter,\n this.pouchSettings,\n pouchDbParameters.settings\n );\n const pouch = new PouchDB(\n pouchDbParameters.location,\n pouchDBOptions\n ) as PouchDBInstance;\n\n /**\n * In the past we found some errors where the PouchDB is not directly usable\n * so we we had to call .info() first to ensure it can be used.\n * I commented this out for now to get faster database/collection creation.\n * We might have to add this again if something fails.\n */\n // await pouch.info();\n\n return Promise.resolve(pouch);\n }\n\n public async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n\n ensureRxStorageInstanceParamsAreCorrect(params);\n\n const pouchLocation = getPouchLocation(\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n const pouch = await this.createPouch(\n pouchLocation,\n params.options\n );\n await createIndexesOnPouch(pouch, params.schema);\n const pouchInstanceId = openPouchId(\n params.databaseInstanceToken,\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n const instance = new RxStorageInstancePouch(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n pouch,\n pouchInstanceId\n },\n params.options\n );\n OPEN_POUCH_INSTANCES.set(\n pouchInstanceId,\n pouch\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_POUCHDB,\n params,\n instance\n );\n\n return instance;\n }\n}\n\n/**\n * Checks if all is ok with the given adapter,\n * else throws an error.\n */\nexport function checkPouchAdapter(adapter: string | any) {\n if (typeof adapter === 'string') {\n if (!(PouchDB as any).adapters || !(PouchDB as any).adapters[adapter]) {\n throw newRxError('DB9', {\n adapter\n });\n }\n } else {\n isLevelDown(adapter);\n if (!(PouchDB as any).adapters || !(PouchDB as any).adapters.leveldb) {\n throw newRxError('DB10', {\n adapter\n });\n }\n }\n}\n\n/**\n * Creates the indexes of the schema inside of the pouchdb instance.\n * Will skip indexes that already exist.\n */\nexport async function createIndexesOnPouch(\n pouch: PouchDBInstance,\n schema: RxJsonSchema\n): Promise {\n if (!schema.indexes) {\n return;\n }\n const primaryKey = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const before = await pouch.getIndexes();\n const existingIndexes: Set = new Set(\n before.indexes.map(idx => idx.name)\n );\n\n await Promise.all(\n schema.indexes.map((indexMaybeArray) => {\n let indexArray: MaybeReadonly = isMaybeReadonlyArray(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray];\n\n /**\n * replace primary key with _id\n * because that is the enforced primary key on pouchdb.\n */\n indexArray = indexArray.map(key => {\n if (key === primaryKey) {\n return '_id';\n } else {\n return key;\n }\n });\n\n const indexName = getPouchIndexDesignDocNameByIndex(indexArray);\n if (existingIndexes.has(indexName)) {\n // index already exists\n return;\n }\n\n /**\n * TODO we might have even better performance by doing a pouch.bulkDocs()\n * on index creation\n */\n return pouch.createIndex({\n name: indexName,\n ddoc: indexName,\n index: {\n fields: indexArray\n }\n });\n })\n );\n}\n\n/**\n * returns the pouchdb-database-name\n */\nexport function getPouchLocation(\n dbName: string,\n collectionName: string,\n schemaVersion: number\n): string {\n const prefix = dbName + '-rxdb-' + schemaVersion + '-';\n if (!collectionName.includes('/')) {\n return prefix + collectionName;\n } else {\n // if collectionName is a path, we have to prefix the last part only\n const split = collectionName.split('/');\n const last = split.pop();\n\n let ret = split.join('/');\n ret += '/' + prefix + last;\n return ret;\n }\n}\n\n\nexport function getPouchDBOfRxCollection(\n collection: RxCollection\n): PouchDBInstance {\n const id = openPouchId(\n collection.database.token,\n collection.database.name,\n collection.name,\n collection.schema.version\n );\n const pouch = getFromMapOrThrow(OPEN_POUCH_INSTANCES, id);\n return pouch;\n}\n\n\nlet addedRxDBPouchPlugins = false;\n\n/**\n * @deprecated PouchDB RxStorage is deprecated, see\n * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated\n */\nexport function getRxStoragePouch(\n adapter: any,\n pouchSettings?: PouchSettings\n): RxStoragePouch {\n if (!addedRxDBPouchPlugins) {\n addedRxDBPouchPlugins = true;\n addPouchPlugin(PouchDBFind);\n addCustomEventsPluginToPouch();\n }\n\n if (!adapter) {\n throw new Error('adapter missing');\n }\n const storage = new RxStoragePouch(adapter, pouch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aAAa,CAAC;EAC1D,OAAOyD,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/query-builder/index.js b/dist/lib/plugins/query-builder/index.js index 27940443c65..cc22cf352bb 100644 --- a/dist/lib/plugins/query-builder/index.js +++ b/dist/lib/plugins/query-builder/index.js @@ -24,12 +24,12 @@ Object.keys(_nosqlQueryBuilder).forEach(function (key) { }); }); var _rxQuery = require("../../rx-query"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _hooks = require("../../hooks"); // if the query-builder plugin is used, we have to save its last path var RXQUERY_OTHER_FLAG = 'queryBuilderPath'; function runBuildingStep(rxQuery, functionName, value) { - var queryBuilder = (0, _nosqlQueryBuilder.createQueryBuilder)((0, _util.clone)(rxQuery.mangoQuery)); + var queryBuilder = (0, _nosqlQueryBuilder.createQueryBuilder)((0, _utils.clone)(rxQuery.mangoQuery)); if (rxQuery.other[RXQUERY_OTHER_FLAG]) { queryBuilder._path = rxQuery.other[RXQUERY_OTHER_FLAG]; } diff --git a/dist/lib/plugins/query-builder/index.js.map b/dist/lib/plugins/query-builder/index.js.map index 1ec37f92f0f..342a6071828 100644 --- a/dist/lib/plugins/query-builder/index.js.map +++ b/dist/lib/plugins/query-builder/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["RXQUERY_OTHER_FLAG","runBuildingStep","rxQuery","functionName","value","queryBuilder","createQueryBuilder","clone","mangoQuery","other","_path","queryBuilderJson","toJSON","runPluginHooks","op","queryObj","query","collection","newQuery","RxQueryBase","path","tunneled","tunnelQueryCache","applyBuildingStep","proto","RxDBQueryBuilderPlugin","name","rxdb","prototypes","RxQuery","forEach","attribute","OTHER_MANGO_ATTRIBUTES","OTHER_MANGO_OPERATORS","operator"],"sources":["../../../../src/plugins/query-builder/index.ts"],"sourcesContent":["import {\n createQueryBuilder,\n OTHER_MANGO_ATTRIBUTES,\n OTHER_MANGO_OPERATORS\n} from './mquery/nosql-query-builder';\nimport type { RxPlugin, RxQuery } from '../../types';\nimport { RxQueryBase, tunnelQueryCache } from '../../rx-query';\nimport { clone } from '../../util';\nimport { runPluginHooks } from '../../hooks';\n\n// if the query-builder plugin is used, we have to save its last path\nconst RXQUERY_OTHER_FLAG = 'queryBuilderPath';\n\nexport function runBuildingStep(\n rxQuery: RxQuery,\n functionName: string,\n value: any\n): RxQuery {\n const queryBuilder = createQueryBuilder(clone(rxQuery.mangoQuery));\n if (rxQuery.other[RXQUERY_OTHER_FLAG]) {\n queryBuilder._path = rxQuery.other[RXQUERY_OTHER_FLAG];\n }\n\n (queryBuilder as any)[functionName](value); // run\n\n const queryBuilderJson = queryBuilder.toJSON();\n\n\n runPluginHooks('preCreateRxQuery', {\n op: rxQuery.op,\n queryObj: queryBuilderJson.query,\n collection: rxQuery.collection\n });\n\n\n const newQuery = new RxQueryBase(\n rxQuery.op,\n queryBuilderJson.query,\n rxQuery.collection\n ) as RxQuery;\n\n\n\n if (queryBuilderJson.path) {\n newQuery.other[RXQUERY_OTHER_FLAG] = queryBuilderJson.path;\n }\n\n const tunneled = tunnelQueryCache(newQuery);\n return tunneled;\n}\n\nexport function applyBuildingStep(\n proto: any,\n functionName: string\n): void {\n proto[functionName] = function (this: RxQuery, value: any) {\n return runBuildingStep(this, functionName, value);\n };\n}\n\nexport * from './mquery/nosql-query-builder';\n\nexport const RxDBQueryBuilderPlugin: RxPlugin = {\n name: 'query-builder',\n rxdb: true,\n prototypes: {\n RxQuery(proto: any) {\n [\n 'where',\n 'equals',\n 'eq',\n 'or',\n 'nor',\n 'and',\n 'mod',\n 'exists',\n 'elemMatch',\n 'sort'\n ].forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_ATTRIBUTES.forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_OPERATORS.forEach(operator => {\n applyBuildingStep(proto, operator);\n });\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAAA;AA4DA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA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;EAC5CC,IAAI,EAAE,eAAe;EACrBC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,OAAO,mBAACL,KAAU,EAAE;MAChB,CACI,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,IAAI,EACJ,KAAK,EACL,KAAK,EACL,KAAK,EACL,QAAQ,EACR,WAAW,EACX,MAAM,CACT,CAACM,OAAO,CAAC,UAAAC,SAAS,EAAI;QACnBR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACFC,yCAAsB,CAACF,OAAO,CAAC,UAAAC,SAAS,EAAI;QACxCR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACFE,wCAAqB,CAACH,OAAO,CAAC,UAAAI,QAAQ,EAAI;QACtCX,iBAAiB,CAACC,KAAK,EAAEU,QAAQ,CAAC;MACtC,CAAC,CAAC;IACN;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["RXQUERY_OTHER_FLAG","runBuildingStep","rxQuery","functionName","value","queryBuilder","createQueryBuilder","clone","mangoQuery","other","_path","queryBuilderJson","toJSON","runPluginHooks","op","queryObj","query","collection","newQuery","RxQueryBase","path","tunneled","tunnelQueryCache","applyBuildingStep","proto","RxDBQueryBuilderPlugin","name","rxdb","prototypes","RxQuery","forEach","attribute","OTHER_MANGO_ATTRIBUTES","OTHER_MANGO_OPERATORS","operator"],"sources":["../../../../src/plugins/query-builder/index.ts"],"sourcesContent":["import {\n createQueryBuilder,\n OTHER_MANGO_ATTRIBUTES,\n OTHER_MANGO_OPERATORS\n} from './mquery/nosql-query-builder';\nimport type { RxPlugin, RxQuery } from '../../types';\nimport { RxQueryBase, tunnelQueryCache } from '../../rx-query';\nimport { clone } from '../../plugins/utils';\nimport { runPluginHooks } from '../../hooks';\n\n// if the query-builder plugin is used, we have to save its last path\nconst RXQUERY_OTHER_FLAG = 'queryBuilderPath';\n\nexport function runBuildingStep(\n rxQuery: RxQuery,\n functionName: string,\n value: any\n): RxQuery {\n const queryBuilder = createQueryBuilder(clone(rxQuery.mangoQuery));\n if (rxQuery.other[RXQUERY_OTHER_FLAG]) {\n queryBuilder._path = rxQuery.other[RXQUERY_OTHER_FLAG];\n }\n\n (queryBuilder as any)[functionName](value); // run\n\n const queryBuilderJson = queryBuilder.toJSON();\n\n\n runPluginHooks('preCreateRxQuery', {\n op: rxQuery.op,\n queryObj: queryBuilderJson.query,\n collection: rxQuery.collection\n });\n\n\n const newQuery = new RxQueryBase(\n rxQuery.op,\n queryBuilderJson.query,\n rxQuery.collection\n ) as RxQuery;\n\n\n\n if (queryBuilderJson.path) {\n newQuery.other[RXQUERY_OTHER_FLAG] = queryBuilderJson.path;\n }\n\n const tunneled = tunnelQueryCache(newQuery);\n return tunneled;\n}\n\nexport function applyBuildingStep(\n proto: any,\n functionName: string\n): void {\n proto[functionName] = function (this: RxQuery, value: any) {\n return runBuildingStep(this, functionName, value);\n };\n}\n\nexport * from './mquery/nosql-query-builder';\n\nexport const RxDBQueryBuilderPlugin: RxPlugin = {\n name: 'query-builder',\n rxdb: true,\n prototypes: {\n RxQuery(proto: any) {\n [\n 'where',\n 'equals',\n 'eq',\n 'or',\n 'nor',\n 'and',\n 'mod',\n 'exists',\n 'elemMatch',\n 'sort'\n ].forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_ATTRIBUTES.forEach(attribute => {\n applyBuildingStep(proto, attribute);\n });\n OTHER_MANGO_OPERATORS.forEach(operator => {\n applyBuildingStep(proto, operator);\n });\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAAA;AA4DA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAtDA;AACA;AACA;AAEA;AACA,IAAMA,kBAAkB,GAAG,kBAAkB;AAEtC,SAASC,eAAe,CAC3BC,OAA+C,EAC/CC,YAAoB,EACpBC,KAAU,EAC4B;EACtC,IAAMC,YAAY,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ACL,KAAK,EACL,KAAK,EACL,QAAQ,EACR,WAAW,EACX,MAAM,CACT,CAACM,OAAO,CAAC,UAAAC,SAAS,EAAI;QACnBR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACFC,yCAAsB,CAACF,OAAO,CAAC,UAAAC,SAAS,EAAI;QACxCR,iBAAiB,CAACC,KAAK,EAAEO,SAAS,CAAC;MACvC,CAAC,CAAC;MACFE,wCAAqB,CAACH,OAAO,CAAC,UAAAI,QAAQ,EAAI;QACtCX,iBAAiB,CAACC,KAAK,EAAEU,QAAQ,CAAC;MACtC,CAAC,CAAC;IACN;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/query-builder/mquery/nosql-query-builder.js.map b/dist/lib/plugins/query-builder/mquery/nosql-query-builder.js.map index 4b3179fd6bb..a5d268c0af3 100644 --- a/dist/lib/plugins/query-builder/mquery/nosql-query-builder.js.map +++ b/dist/lib/plugins/query-builder/mquery/nosql-query-builder.js.map @@ -1 +1 @@ -{"version":3,"file":"nosql-query-builder.js","names":["NoSqlQueryBuilderClass","mangoQuery","options","_conditions","_fields","queryBuilder","selector","find","limit","skip","sort","forEach","s","where","_path","_val","arguments","length","type","Array","isArray","merge","newRxTypeError","path","equals","val","_ensurePath","eq","or","array","$or","push","apply","nor","$nor","and","$and","mod","slice","conds","$mod","exists","$exists","elemMatch","_criteria","fn","criteria","isObject","$elemMatch","arg","len","i","_pushArr","split","field","ascend","substring","keys","Object","args","source","canMerge","_distinct","method","newRxError","toJSON","query","mQuerySortToRxDBSort","entries","map","k","v","direction","part","OTHER_MANGO_ATTRIBUTES","prototype","OTHER_MANGO_OPERATORS","$conditional","opts","value","$meta","String","toLowerCase","test","valueStr","toString","replace","parseInt","createQueryBuilder"],"sources":["../../../../../src/plugins/query-builder/mquery/nosql-query-builder.ts"],"sourcesContent":["/**\n * this is based on\n * @link https://github.com/aheckmann/mquery/blob/master/lib/mquery.js\n */\nimport {\n isObject,\n merge\n} from './mquery-utils';\nimport {\n newRxTypeError,\n newRxError\n} from '../../../rx-error';\nimport type {\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n MangoQuerySortDirection\n} from '../../../types';\n\n\ndeclare type MQueryOptions = {\n limit?: number;\n skip?: number;\n sort?: any;\n};\n\nexport class NoSqlQueryBuilderClass {\n\n public options: MQueryOptions = {};\n public _conditions: MangoQuerySelector = {};\n public _fields: any = {};\n public _path?: any;\n private _distinct: any;\n\n /**\n * MQuery constructor used for building queries.\n *\n * ####Example:\n * var query = new MQuery({ name: 'mquery' });\n * query.where('age').gte(21).exec(callback);\n *\n */\n constructor(\n mangoQuery?: MangoQuery\n ) {\n if (mangoQuery) {\n const queryBuilder: NoSqlQueryBuilder = this as any;\n\n if (mangoQuery.selector) {\n queryBuilder.find(mangoQuery.selector);\n }\n if (mangoQuery.limit) {\n queryBuilder.limit(mangoQuery.limit);\n }\n if (mangoQuery.skip) {\n queryBuilder.skip(mangoQuery.skip);\n }\n if (mangoQuery.sort) {\n mangoQuery.sort.forEach(s => queryBuilder.sort(s));\n }\n }\n }\n\n /**\n * Specifies a `path` for use with chaining.\n */\n where(_path: string, _val?: MangoQuerySelector): NoSqlQueryBuilder {\n if (!arguments.length) return this as any;\n const type = typeof arguments[0];\n if ('string' === type) {\n this._path = arguments[0];\n if (2 === arguments.length) {\n this._conditions[this._path] = arguments[1];\n }\n return this as any;\n }\n\n if ('object' === type && !Array.isArray(arguments[0])) {\n return this.merge(arguments[0]);\n }\n\n throw newRxTypeError('MQ1', {\n path: arguments[0]\n });\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * ####Example\n * User.where('age').equals(49);\n */\n equals(val: any): NoSqlQueryBuilder {\n this._ensurePath('equals');\n const path = this._path;\n this._conditions[path] = val;\n return this as any;\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * This is alias of `equals`\n */\n eq(val: any): NoSqlQueryBuilder {\n this._ensurePath('eq');\n const path = this._path;\n this._conditions[path] = val;\n return this as any;\n }\n\n /**\n * Specifies arguments for an `$or` condition.\n * ####Example\n * query.or([{ color: 'red' }, { status: 'emergency' }])\n */\n or(array: any[]): NoSqlQueryBuilder {\n const or = this._conditions.$or || (this._conditions.$or = []);\n if (!Array.isArray(array)) array = [array];\n or.push.apply(or, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$nor` condition.\n * ####Example\n * query.nor([{ color: 'green' }, { status: 'ok' }])\n */\n nor(array: any[]): NoSqlQueryBuilder {\n const nor = this._conditions.$nor || (this._conditions.$nor = []);\n if (!Array.isArray(array)) array = [array];\n nor.push.apply(nor, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$and` condition.\n * ####Example\n * query.and([{ color: 'green' }, { status: 'ok' }])\n * @see $and http://docs.mongodb.org/manual/reference/operator/and/\n */\n and(array: any[]): NoSqlQueryBuilder {\n const and = this._conditions.$and || (this._conditions.$and = []);\n if (!Array.isArray(array)) array = [array];\n and.push.apply(and, array);\n return this as any;\n }\n\n /**\n * Specifies a `$mod` condition\n */\n mod(_path: string, _val: number): NoSqlQueryBuilder {\n let val;\n let path;\n\n if (1 === arguments.length) {\n this._ensurePath('mod');\n val = arguments[0];\n path = this._path;\n } else if (2 === arguments.length && !Array.isArray(arguments[1])) {\n this._ensurePath('mod');\n val = (arguments as any).slice();\n path = this._path;\n } else if (3 === arguments.length) {\n val = (arguments as any).slice(1);\n path = arguments[0];\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$mod = val;\n return this as any;\n }\n\n /**\n * Specifies an `$exists` condition\n * ####Example\n * // { name: { $exists: true }}\n * Thing.where('name').exists()\n * Thing.where('name').exists(true)\n * Thing.find().exists('name')\n */\n exists(_path: string, _val: number): NoSqlQueryBuilder {\n let path;\n let val;\n if (0 === arguments.length) {\n this._ensurePath('exists');\n path = this._path;\n val = true;\n } else if (1 === arguments.length) {\n if ('boolean' === typeof arguments[0]) {\n this._ensurePath('exists');\n path = this._path;\n val = arguments[0];\n } else {\n path = arguments[0];\n val = true;\n }\n } else if (2 === arguments.length) {\n path = arguments[0];\n val = arguments[1];\n }\n\n const conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$exists = val;\n return this as any;\n }\n\n /**\n * Specifies an `$elemMatch` condition\n * ####Example\n * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})\n * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n * query.elemMatch('comment', function (elem) {\n * elem.where('author').equals('autobot');\n * elem.where('votes').gte(5);\n * })\n * query.where('comment').elemMatch(function (elem) {\n * elem.where({ author: 'autobot' });\n * elem.where('votes').gte(5);\n * })\n */\n elemMatch(_path: string, _criteria: any): NoSqlQueryBuilder {\n if (null === arguments[0])\n throw newRxTypeError('MQ2');\n\n let fn;\n let path;\n let criteria;\n\n if ('function' === typeof arguments[0]) {\n this._ensurePath('elemMatch');\n path = this._path;\n fn = arguments[0];\n } else if (isObject(arguments[0])) {\n this._ensurePath('elemMatch');\n path = this._path;\n criteria = arguments[0];\n } else if ('function' === typeof arguments[1]) {\n path = arguments[0];\n fn = arguments[1];\n } else if (arguments[1] && isObject(arguments[1])) {\n path = arguments[0];\n criteria = arguments[1];\n } else\n throw newRxTypeError('MQ2');\n\n if (fn) {\n criteria = new NoSqlQueryBuilderClass;\n fn(criteria);\n criteria = criteria._conditions;\n }\n\n const conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$elemMatch = criteria;\n return this as any;\n }\n\n /**\n * Sets the sort order\n * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.\n * If a string is passed, it must be a space delimited list of path names.\n * The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n * ####Example\n * query.sort({ field: 'asc', test: -1 });\n * query.sort('field -test');\n * query.sort([['field', 1], ['test', -1]]);\n */\n sort(arg: any): NoSqlQueryBuilder {\n if (!arg) return this as any;\n let len;\n const type = typeof arg;\n // .sort([['field', 1], ['test', -1]])\n if (Array.isArray(arg)) {\n len = arg.length;\n for (let i = 0; i < arg.length; ++i) {\n _pushArr(this.options, arg[i][0], arg[i][1]);\n }\n\n return this as any;\n }\n\n // .sort('field -test')\n if (1 === arguments.length && 'string' === type) {\n arg = arg.split(/\\s+/);\n len = arg.length;\n for (let i = 0; i < len; ++i) {\n let field = arg[i];\n if (!field) continue;\n const ascend = '-' === field[0] ? -1 : 1;\n if (ascend === -1) field = field.substring(1);\n push(this.options, field, ascend);\n }\n\n return this as any;\n }\n\n // .sort({ field: 1, test: -1 })\n if (isObject(arg)) {\n const keys = Object.keys(arg);\n keys.forEach(field => push(this.options, field, arg[field]));\n return this as any;\n }\n\n throw newRxTypeError('MQ3', {\n args: arguments\n });\n }\n\n /**\n * Merges another MQuery or conditions object into this one.\n *\n * When a MQuery is passed, conditions, field selection and options are merged.\n *\n */\n merge(source: any): NoSqlQueryBuilder {\n if (!source) {\n return this as any;\n }\n\n if (!canMerge(source)) {\n throw newRxTypeError('MQ4', {\n source\n });\n }\n\n if (source instanceof NoSqlQueryBuilderClass) {\n // if source has a feature, apply it to ourselves\n\n if (source._conditions)\n merge(this._conditions, source._conditions);\n\n if (source._fields) {\n if (!this._fields) this._fields = {};\n merge(this._fields, source._fields);\n }\n\n if (source.options) {\n if (!this.options) this.options = {};\n merge(this.options, source.options);\n }\n\n if (source._distinct)\n this._distinct = source._distinct;\n\n return this as any;\n }\n\n // plain object\n merge(this._conditions, source);\n\n return this as any;\n }\n\n /**\n * Finds documents.\n * ####Example\n * query.find()\n * query.find({ name: 'Burning Lights' })\n */\n find(criteria: any): NoSqlQueryBuilder {\n if (canMerge(criteria)) {\n this.merge(criteria);\n }\n\n return this as any;\n }\n\n /**\n * Make sure _path is set.\n *\n * @parmam {String} method\n */\n _ensurePath(method: any) {\n if (!this._path) {\n throw newRxError('MQ5', {\n method\n });\n }\n }\n\n toJSON(): {\n query: MangoQuery;\n path?: string;\n } {\n const query: MangoQuery = {\n selector: this._conditions,\n };\n\n if (this.options.skip) {\n query.skip = this.options.skip;\n }\n if (this.options.limit) {\n query.limit = this.options.limit;\n }\n if (this.options.sort) {\n query.sort = mQuerySortToRxDBSort(this.options.sort);\n }\n\n return {\n query,\n path: this._path\n };\n }\n}\n\nexport function mQuerySortToRxDBSort(\n sort: { [k: string]: 1 | -1; }\n): MangoQuerySortPart[] {\n return Object.entries(sort).map(([k, v]) => {\n const direction: MangoQuerySortDirection = v === 1 ? 'asc' : 'desc';\n const part: MangoQuerySortPart = { [k]: direction } as any;\n return part;\n });\n}\n\n/**\n * Because some prototype-methods are generated,\n * we have to define the type of NoSqlQueryBuilder here\n */\n\nexport interface NoSqlQueryBuilder extends NoSqlQueryBuilderClass {\n maxScan: ReturnSelfNumberFunction;\n batchSize: ReturnSelfNumberFunction;\n limit: ReturnSelfNumberFunction;\n skip: ReturnSelfNumberFunction;\n comment: ReturnSelfFunction;\n\n gt: ReturnSelfFunction;\n gte: ReturnSelfFunction;\n lt: ReturnSelfFunction;\n lte: ReturnSelfFunction;\n ne: ReturnSelfFunction;\n in: ReturnSelfFunction;\n nin: ReturnSelfFunction;\n all: ReturnSelfFunction;\n regex: ReturnSelfFunction;\n size: ReturnSelfFunction;\n\n}\n\ndeclare type ReturnSelfFunction = (v: any) => NoSqlQueryBuilder;\ndeclare type ReturnSelfNumberFunction = (v: number | null) => NoSqlQueryBuilder;\n\n/**\n * limit, skip, maxScan, batchSize, comment\n *\n * Sets these associated options.\n *\n * query.comment('feed query');\n */\nexport const OTHER_MANGO_ATTRIBUTES = ['limit', 'skip', 'maxScan', 'batchSize', 'comment'];\nOTHER_MANGO_ATTRIBUTES.forEach(function (method) {\n (NoSqlQueryBuilderClass.prototype as any)[method] = function (v: any) {\n this.options[method] = v;\n return this;\n };\n});\n\n\n/**\n * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance\n *\n * Thing.where('type').nin(array)\n */\nexport const OTHER_MANGO_OPERATORS = [\n 'gt', 'gte', 'lt', 'lte', 'ne',\n 'in', 'nin', 'all', 'regex', 'size'\n];\nOTHER_MANGO_OPERATORS.forEach(function ($conditional) {\n (NoSqlQueryBuilderClass.prototype as any)[$conditional] = function () {\n let path;\n let val;\n if (1 === arguments.length) {\n this._ensurePath($conditional);\n val = arguments[0];\n path = this._path;\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ?\n this._conditions[path] :\n (this._conditions[path] = {});\n conds['$' + $conditional] = val;\n return this;\n };\n});\n\n\nfunction push(opts: any, field: string, value: any) {\n if (Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ6', {\n opts,\n field,\n value\n });\n }\n\n if (value && value.$meta) {\n const sort = opts.sort || (opts.sort = {});\n sort[field] = {\n $meta: value.$meta\n };\n return;\n }\n\n const val = String(value || 1).toLowerCase();\n if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {\n if (Array.isArray(value)) value = '[' + value + ']';\n throw newRxTypeError('MQ7', {\n field,\n value\n });\n }\n // store `sort` in a sane format\n const s = opts.sort || (opts.sort = {});\n const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');\n s[field] = parseInt(valueStr, 10);\n}\n\nfunction _pushArr(opts: any, field: string, value: any) {\n opts.sort = opts.sort || [];\n if (!Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ8', {\n opts,\n field,\n value\n });\n }\n\n /* const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');*/\n opts.sort.push([field, value]);\n}\n\n\n/**\n * Determines if `conds` can be merged using `mquery().merge()`\n */\nexport function canMerge(conds: any): boolean {\n return conds instanceof NoSqlQueryBuilderClass || isObject(conds);\n}\n\n\nexport function createQueryBuilder(query?: MangoQuery): NoSqlQueryBuilder {\n return new NoSqlQueryBuilderClass(query) as NoSqlQueryBu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I,EAAE;EAC3B,IAAI,CAACS,KAAK,CAACC,OAAO,CAAC0D,IAAI,CAACpE,IAAI,CAAC,EAAE;IAC3B,MAAM,IAAAY,uBAAc,EAAC,KAAK,EAAE;MACxBwD,IAAI,EAAJA,IAAI;MACJxB,KAAK,EAALA,KAAK;MACLyB,KAAK,EAALA;IACJ,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;AACA;EACID,IAAI,CAACpE,IAAI,CAACqB,IAAI,CAAC,CAACuB,KAAK,EAAEyB,KAAK,CAAC,CAAC;AAClC;;AAGA;AACA;AACA;AACO,SAASlB,QAAQ,CAACtB,KAAU,EAAW;EAC1C,OAAOA,KAAK,YAAYvC,sBAAsB,IAAI,IAAA+C,qBAAQ,EAACR,KAAK,CAAC;AACrE;AAGO,SAASiD,kBAAkB,CAAUtB,KAA2B,EAA8B;EACjG,OAAO,IAAIlE,sBAAsB,CAACkE,KAAK,CAAC;AAC5C"} \ No newline at end of file +{"version":3,"file":"nosql-query-builder.js","names":["NoSqlQueryBuilderClass","mangoQuery","options","_conditions","_fields","queryBuilder","selector","find","limit","skip","sort","forEach","s","where","_path","_val","arguments","length","type","Array","isArray","merge","newRxTypeError","path","equals","val","_ensurePath","eq","or","array","$or","push","apply","nor","$nor","and","$and","mod","slice","conds","$mod","exists","$exists","elemMatch","_criteria","fn","criteria","isObject","$elemMatch","arg","len","i","_pushArr","split","field","ascend","substring","keys","Object","args","source","canMerge","_distinct","method","newRxError","toJSON","query","mQuerySortToRxDBSort","entries","map","k","v","direction","part","OTHER_MANGO_ATTRIBUTES","prototype","OTHER_MANGO_OPERATORS","$conditional","opts","value","$meta","String","toLowerCase","test","valueStr","toString","replace","parseInt","createQueryBuilder"],"sources":["../../../../../src/plugins/query-builder/mquery/nosql-query-builder.ts"],"sourcesContent":["/**\n * this is based on\n * @link https://github.com/aheckmann/mquery/blob/master/lib/mquery.js\n */\nimport {\n isObject,\n merge\n} from './mquery-utils';\nimport {\n newRxTypeError,\n newRxError\n} from '../../../rx-error';\nimport type {\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n MangoQuerySortDirection\n} from '../../../types';\n\n\ndeclare type MQueryOptions = {\n limit?: number;\n skip?: number;\n sort?: any;\n};\n\nexport class NoSqlQueryBuilderClass {\n\n public options: MQueryOptions = {};\n public _conditions: MangoQuerySelector = {};\n public _fields: any = {};\n public _path?: any;\n private _distinct: any;\n\n /**\n * MQuery constructor used for building queries.\n *\n * ####Example:\n * var query = new MQuery({ name: 'mquery' });\n * query.where('age').gte(21).exec(callback);\n *\n */\n constructor(\n mangoQuery?: MangoQuery\n ) {\n if (mangoQuery) {\n const queryBuilder: NoSqlQueryBuilder = this as any;\n\n if (mangoQuery.selector) {\n queryBuilder.find(mangoQuery.selector);\n }\n if (mangoQuery.limit) {\n queryBuilder.limit(mangoQuery.limit);\n }\n if (mangoQuery.skip) {\n queryBuilder.skip(mangoQuery.skip);\n }\n if (mangoQuery.sort) {\n mangoQuery.sort.forEach(s => queryBuilder.sort(s));\n }\n }\n }\n\n /**\n * Specifies a `path` for use with chaining.\n */\n where(_path: string, _val?: MangoQuerySelector): NoSqlQueryBuilder {\n if (!arguments.length) return this as any;\n const type = typeof arguments[0];\n if ('string' === type) {\n this._path = arguments[0];\n if (2 === arguments.length) {\n (this._conditions as any)[this._path] = arguments[1];\n }\n return this as any;\n }\n\n if ('object' === type && !Array.isArray(arguments[0])) {\n return this.merge(arguments[0]);\n }\n\n throw newRxTypeError('MQ1', {\n path: arguments[0]\n });\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * ####Example\n * User.where('age').equals(49);\n */\n equals(val: any): NoSqlQueryBuilder {\n this._ensurePath('equals');\n const path = this._path;\n (this._conditions as any)[path] = val;\n return this as any;\n }\n\n /**\n * Specifies the complementary comparison value for paths specified with `where()`\n * This is alias of `equals`\n */\n eq(val: any): NoSqlQueryBuilder {\n this._ensurePath('eq');\n const path = this._path;\n (this._conditions as any)[path] = val;\n return this as any;\n }\n\n /**\n * Specifies arguments for an `$or` condition.\n * ####Example\n * query.or([{ color: 'red' }, { status: 'emergency' }])\n */\n or(array: any[]): NoSqlQueryBuilder {\n const or = this._conditions.$or || (this._conditions.$or = []);\n if (!Array.isArray(array)) array = [array];\n or.push.apply(or, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$nor` condition.\n * ####Example\n * query.nor([{ color: 'green' }, { status: 'ok' }])\n */\n nor(array: any[]): NoSqlQueryBuilder {\n const nor = this._conditions.$nor || (this._conditions.$nor = []);\n if (!Array.isArray(array)) array = [array];\n nor.push.apply(nor, array);\n return this as any;\n }\n\n /**\n * Specifies arguments for a `$and` condition.\n * ####Example\n * query.and([{ color: 'green' }, { status: 'ok' }])\n * @see $and http://docs.mongodb.org/manual/reference/operator/and/\n */\n and(array: any[]): NoSqlQueryBuilder {\n const and = this._conditions.$and || (this._conditions.$and = []);\n if (!Array.isArray(array)) array = [array];\n and.push.apply(and, array);\n return this as any;\n }\n\n /**\n * Specifies a `$mod` condition\n */\n mod(_path: string, _val: number): NoSqlQueryBuilder {\n let val;\n let path;\n\n if (1 === arguments.length) {\n this._ensurePath('mod');\n val = arguments[0];\n path = this._path;\n } else if (2 === arguments.length && !Array.isArray(arguments[1])) {\n this._ensurePath('mod');\n val = (arguments as any).slice();\n path = this._path;\n } else if (3 === arguments.length) {\n val = (arguments as any).slice(1);\n path = arguments[0];\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = (this._conditions as any)[path] || ((this._conditions as any)[path] = {});\n conds.$mod = val;\n return this as any;\n }\n\n /**\n * Specifies an `$exists` condition\n * ####Example\n * // { name: { $exists: true }}\n * Thing.where('name').exists()\n * Thing.where('name').exists(true)\n * Thing.find().exists('name')\n */\n exists(_path: string, _val: number): NoSqlQueryBuilder {\n let path;\n let val;\n if (0 === arguments.length) {\n this._ensurePath('exists');\n path = this._path;\n val = true;\n } else if (1 === arguments.length) {\n if ('boolean' === typeof arguments[0]) {\n this._ensurePath('exists');\n path = this._path;\n val = arguments[0];\n } else {\n path = arguments[0];\n val = true;\n }\n } else if (2 === arguments.length) {\n path = arguments[0];\n val = arguments[1];\n }\n\n const conds = (this._conditions as any)[path] || ((this._conditions as any)[path] = {});\n conds.$exists = val;\n return this as any;\n }\n\n /**\n * Specifies an `$elemMatch` condition\n * ####Example\n * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})\n * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n * query.elemMatch('comment', function (elem) {\n * elem.where('author').equals('autobot');\n * elem.where('votes').gte(5);\n * })\n * query.where('comment').elemMatch(function (elem) {\n * elem.where({ author: 'autobot' });\n * elem.where('votes').gte(5);\n * })\n */\n elemMatch(_path: string, _criteria: any): NoSqlQueryBuilder {\n if (null === arguments[0])\n throw newRxTypeError('MQ2');\n\n let fn;\n let path;\n let criteria;\n\n if ('function' === typeof arguments[0]) {\n this._ensurePath('elemMatch');\n path = this._path;\n fn = arguments[0];\n } else if (isObject(arguments[0])) {\n this._ensurePath('elemMatch');\n path = this._path;\n criteria = arguments[0];\n } else if ('function' === typeof arguments[1]) {\n path = arguments[0];\n fn = arguments[1];\n } else if (arguments[1] && isObject(arguments[1])) {\n path = arguments[0];\n criteria = arguments[1];\n } else\n throw newRxTypeError('MQ2');\n\n if (fn) {\n criteria = new NoSqlQueryBuilderClass;\n fn(criteria);\n criteria = criteria._conditions;\n }\n\n const conds = (this._conditions as any)[path] || ((this._conditions as any)[path] = {});\n conds.$elemMatch = criteria;\n return this as any;\n }\n\n /**\n * Sets the sort order\n * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.\n * If a string is passed, it must be a space delimited list of path names.\n * The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n * ####Example\n * query.sort({ field: 'asc', test: -1 });\n * query.sort('field -test');\n * query.sort([['field', 1], ['test', -1]]);\n */\n sort(arg: any): NoSqlQueryBuilder {\n if (!arg) return this as any;\n let len;\n const type = typeof arg;\n // .sort([['field', 1], ['test', -1]])\n if (Array.isArray(arg)) {\n len = arg.length;\n for (let i = 0; i < arg.length; ++i) {\n _pushArr(this.options, arg[i][0], arg[i][1]);\n }\n\n return this as any;\n }\n\n // .sort('field -test')\n if (1 === arguments.length && 'string' === type) {\n arg = arg.split(/\\s+/);\n len = arg.length;\n for (let i = 0; i < len; ++i) {\n let field = arg[i];\n if (!field) continue;\n const ascend = '-' === field[0] ? -1 : 1;\n if (ascend === -1) field = field.substring(1);\n push(this.options, field, ascend);\n }\n\n return this as any;\n }\n\n // .sort({ field: 1, test: -1 })\n if (isObject(arg)) {\n const keys = Object.keys(arg);\n keys.forEach(field => push(this.options, field, arg[field]));\n return this as any;\n }\n\n throw newRxTypeError('MQ3', {\n args: arguments\n });\n }\n\n /**\n * Merges another MQuery or conditions object into this one.\n *\n * When a MQuery is passed, conditions, field selection and options are merged.\n *\n */\n merge(source: any): NoSqlQueryBuilder {\n if (!source) {\n return this as any;\n }\n\n if (!canMerge(source)) {\n throw newRxTypeError('MQ4', {\n source\n });\n }\n\n if (source instanceof NoSqlQueryBuilderClass) {\n // if source has a feature, apply it to ourselves\n\n if (source._conditions)\n merge(this._conditions, source._conditions);\n\n if (source._fields) {\n if (!this._fields) this._fields = {};\n merge(this._fields, source._fields);\n }\n\n if (source.options) {\n if (!this.options) this.options = {};\n merge(this.options, source.options);\n }\n\n if (source._distinct)\n this._distinct = source._distinct;\n\n return this as any;\n }\n\n // plain object\n merge(this._conditions, source);\n\n return this as any;\n }\n\n /**\n * Finds documents.\n * ####Example\n * query.find()\n * query.find({ name: 'Burning Lights' })\n */\n find(criteria: any): NoSqlQueryBuilder {\n if (canMerge(criteria)) {\n this.merge(criteria);\n }\n\n return this as any;\n }\n\n /**\n * Make sure _path is set.\n *\n * @parmam {String} method\n */\n _ensurePath(method: any) {\n if (!this._path) {\n throw newRxError('MQ5', {\n method\n });\n }\n }\n\n toJSON(): {\n query: MangoQuery;\n path?: string;\n } {\n const query: MangoQuery = {\n selector: this._conditions,\n };\n\n if (this.options.skip) {\n query.skip = this.options.skip;\n }\n if (this.options.limit) {\n query.limit = this.options.limit;\n }\n if (this.options.sort) {\n query.sort = mQuerySortToRxDBSort(this.options.sort);\n }\n\n return {\n query,\n path: this._path\n };\n }\n}\n\nexport function mQuerySortToRxDBSort(\n sort: { [k: string]: 1 | -1; }\n): MangoQuerySortPart[] {\n return Object.entries(sort).map(([k, v]) => {\n const direction: MangoQuerySortDirection = v === 1 ? 'asc' : 'desc';\n const part: MangoQuerySortPart = { [k]: direction } as any;\n return part;\n });\n}\n\n/**\n * Because some prototype-methods are generated,\n * we have to define the type of NoSqlQueryBuilder here\n */\n\nexport interface NoSqlQueryBuilder extends NoSqlQueryBuilderClass {\n maxScan: ReturnSelfNumberFunction;\n batchSize: ReturnSelfNumberFunction;\n limit: ReturnSelfNumberFunction;\n skip: ReturnSelfNumberFunction;\n comment: ReturnSelfFunction;\n\n gt: ReturnSelfFunction;\n gte: ReturnSelfFunction;\n lt: ReturnSelfFunction;\n lte: ReturnSelfFunction;\n ne: ReturnSelfFunction;\n in: ReturnSelfFunction;\n nin: ReturnSelfFunction;\n all: ReturnSelfFunction;\n regex: ReturnSelfFunction;\n size: ReturnSelfFunction;\n\n}\n\ndeclare type ReturnSelfFunction = (v: any) => NoSqlQueryBuilder;\ndeclare type ReturnSelfNumberFunction = (v: number | null) => NoSqlQueryBuilder;\n\n/**\n * limit, skip, maxScan, batchSize, comment\n *\n * Sets these associated options.\n *\n * query.comment('feed query');\n */\nexport const OTHER_MANGO_ATTRIBUTES = ['limit', 'skip', 'maxScan', 'batchSize', 'comment'];\nOTHER_MANGO_ATTRIBUTES.forEach(function (method) {\n (NoSqlQueryBuilderClass.prototype as any)[method] = function (v: any) {\n this.options[method] = v;\n return this;\n };\n});\n\n\n/**\n * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance\n *\n * Thing.where('type').nin(array)\n */\nexport const OTHER_MANGO_OPERATORS = [\n 'gt', 'gte', 'lt', 'lte', 'ne',\n 'in', 'nin', 'all', 'regex', 'size'\n];\nOTHER_MANGO_OPERATORS.forEach(function ($conditional) {\n (NoSqlQueryBuilderClass.prototype as any)[$conditional] = function () {\n let path;\n let val;\n if (1 === arguments.length) {\n this._ensurePath($conditional);\n val = arguments[0];\n path = this._path;\n } else {\n val = arguments[1];\n path = arguments[0];\n }\n\n const conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ?\n this._conditions[path] :\n (this._conditions[path] = {});\n conds['$' + $conditional] = val;\n return this;\n };\n});\n\n\nfunction push(opts: any, field: string, value: any) {\n if (Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ6', {\n opts,\n field,\n value\n });\n }\n\n if (value && value.$meta) {\n const sort = opts.sort || (opts.sort = {});\n sort[field] = {\n $meta: value.$meta\n };\n return;\n }\n\n const val = String(value || 1).toLowerCase();\n if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {\n if (Array.isArray(value)) value = '[' + value + ']';\n throw newRxTypeError('MQ7', {\n field,\n value\n });\n }\n // store `sort` in a sane format\n const s = opts.sort || (opts.sort = {});\n const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');\n s[field] = parseInt(valueStr, 10);\n}\n\nfunction _pushArr(opts: any, field: string, value: any) {\n opts.sort = opts.sort || [];\n if (!Array.isArray(opts.sort)) {\n throw newRxTypeError('MQ8', {\n opts,\n field,\n value\n });\n }\n\n /* const valueStr = value.toString()\n .replace('asc', '1')\n .replace('ascending', '1')\n .replace('desc', '-1')\n .replace('descending', '-1');*/\n opts.sort.push([field, value]);\n}\n\n\n/**\n * Determines if `conds` can be merged using `mquery().merge()`\n */\nexport function canMerge(conds: any): boolean {\n return conds instanceof NoSqlQueryBuilderClass || isObject(conds);\n}\n\n\nexport function createQueryBuilder(query?: MangoQuery): NoSqlQueryBuilder {\n return new NoSqlQueryBuilderClass(query) as NoSqlQueryBuilder;\n}\n"],"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AAI,CAACS,KAAK,CAACC,OAAO,CAAC0D,IAAI,CAACpE,IAAI,CAAC,EAAE;IAC3B,MAAM,IAAAY,uBAAc,EAAC,KAAK,EAAE;MACxBwD,IAAI,EAAJA,IAAI;MACJxB,KAAK,EAALA,KAAK;MACLyB,KAAK,EAALA;IACJ,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;AACA;EACID,IAAI,CAACpE,IAAI,CAACqB,IAAI,CAAC,CAACuB,KAAK,EAAEyB,KAAK,CAAC,CAAC;AAClC;;AAGA;AACA;AACA;AACO,SAASlB,QAAQ,CAACtB,KAAU,EAAW;EAC1C,OAAOA,KAAK,YAAYvC,sBAAsB,IAAI,IAAA+C,qBAAQ,EAACR,KAAK,CAAC;AACrE;AAGO,SAASiD,kBAAkB,CAAUtB,KAA2B,EAA8B;EACjG,OAAO,IAAIlE,sBAAsB,CAACkE,KAAK,CAAC;AAC5C"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb-new/couchdb-helper.js b/dist/lib/plugins/replication-couchdb-new/couchdb-helper.js deleted file mode 100644 index 8b3134b49cb..00000000000 --- a/dist/lib/plugins/replication-couchdb-new/couchdb-helper.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = void 0; -exports.couchDBDocToRxDocData = couchDBDocToRxDocData; -exports.mergeUrlQueryParams = mergeUrlQueryParams; -var _pouchdb = require("../pouchdb"); -var COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-'; -exports.COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX; -function mergeUrlQueryParams(params) { - return Object.entries(params).filter(function (_ref) { - var _k = _ref[0], - value = _ref[1]; - return typeof value !== 'undefined'; - }).map(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; - return key + '=' + value; - }).join('&'); -} -function couchDBDocToRxDocData(primaryPath, couchDocData) { - var doc = (0, _pouchdb.pouchSwapIdToPrimary)(primaryPath, couchDocData); - - // ensure deleted flag is set. - doc._deleted = !!doc._deleted; - return doc; -} -//# sourceMappingURL=couchdb-helper.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb-new/couchdb-helper.js.map b/dist/lib/plugins/replication-couchdb-new/couchdb-helper.js.map deleted file mode 100644 index 7fdd0f82da4..00000000000 --- a/dist/lib/plugins/replication-couchdb-new/couchdb-helper.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"couchdb-helper.js","names":["COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","mergeUrlQueryParams","params","Object","entries","filter","_k","value","map","key","join","couchDBDocToRxDocData","primaryPath","couchDocData","doc","pouchSwapIdToPrimary","_deleted"],"sources":["../../../../src/plugins/replication-couchdb-new/couchdb-helper.ts"],"sourcesContent":["import { WithDeleted } from '../../types';\nimport { pouchSwapIdToPrimary } from '../pouchdb';\nimport { URLQueryParams } from './couchdb-types';\n\n\nexport const COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-';\n\n\nexport function mergeUrlQueryParams(\n params: URLQueryParams\n): string {\n return Object.entries(params)\n .filter(([_k, value]) => typeof value !== 'undefined')\n .map(([key, value]) => key + '=' + value)\n .join('&');\n}\n\nexport function couchDBDocToRxDocData(\n primaryPath: string,\n couchDocData: any\n): WithDeleted {\n const doc = pouchSwapIdToPrimary(primaryPath, couchDocData);\n\n // ensure deleted flag is set.\n doc._deleted = !!doc._deleted;\n\n return doc;\n}\n"],"mappings":";;;;;;;;AACA;AAIO,IAAMA,8CAA8C,GAAG,2BAA2B;AAAC;AAGnF,SAASC,mBAAmB,CAC/BC,MAAsB,EAChB;EACN,OAAOC,MAAM,CAACC,OAAO,CAACF,MAAM,CAAC,CACxBG,MAAM,CAAC;IAAA,IAAEC,EAAE;MAAEC,KAAK;IAAA,OAAM,OAAOA,KAAK,KAAK,WAAW;EAAA,EAAC,CACrDC,GAAG,CAAC;IAAA,IAAEC,GAAG;MAAEF,KAAK;IAAA,OAAME,GAAG,GAAG,GAAG,GAAGF,KAAK;EAAA,EAAC,CACxCG,IAAI,CAAC,GAAG,CAAC;AAClB;AAEO,SAASC,qBAAqB,CACjCC,WAAmB,EACnBC,YAAiB,EACK;EACtB,IAAMC,GAAG,GAAG,IAAAC,6BAAoB,EAACH,WAAW,EAAEC,YAAY,CAAC;;EAE3D;EACAC,GAAG,CAACE,QAAQ,GAAG,CAAC,CAACF,GAAG,CAACE,QAAQ;EAE7B,OAAOF,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb-new/couchdb-types.js.map b/dist/lib/plugins/replication-couchdb-new/couchdb-types.js.map deleted file mode 100644 index 47c70bf8ac9..00000000000 --- a/dist/lib/plugins/replication-couchdb-new/couchdb-types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"couchdb-types.js","names":[],"sources":["../../../../src/plugins/replication-couchdb-new/couchdb-types.ts"],"sourcesContent":["import {\n ById,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nexport type CouchDBCheckpointType = {\n sequence: number;\n};\n\nexport type FetchMethodType = typeof fetch;\nexport type SyncOptionsCouchDBNew = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier' | 'collection'\n> & {\n url: string;\n /**\n * Here you can set a custom fetch method\n * to use http headers or credentials when doing requests.\n */\n fetch?: FetchMethodType;\n pull?: Omit, 'handler' | 'stream$'> & {\n /**\n * Heartbeat time in milliseconds\n * for the long polling of the changestream.\n */\n heartbeat?: number;\n };\n push?: Omit, 'handler'>;\n};\n\n\nexport type URLQueryParams = ById;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb-new/index.js b/dist/lib/plugins/replication-couchdb-new/index.js deleted file mode 100644 index 5a2632c24c9..00000000000 --- a/dist/lib/plugins/replication-couchdb-new/index.js +++ /dev/null @@ -1,414 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _exportNames = { - RxCouchDBNewReplicationState: true, - syncCouchDBNew: true, - RxDBReplicationCouchDBNewPlugin: true -}; -exports.RxDBReplicationCouchDBNewPlugin = exports.RxCouchDBNewReplicationState = void 0; -exports.syncCouchDBNew = syncCouchDBNew; -var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); -var _util = require("../../util"); -var _leaderElection = require("../leader-election"); -var _replication = require("../replication"); -var _index = require("../../index"); -var _rxjs = require("rxjs"); -var _couchdbHelper = require("./couchdb-helper"); -Object.keys(_couchdbHelper).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _couchdbHelper[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _couchdbHelper[key]; - } - }); -}); -var _pouchdb = require("../pouchdb"); -var _couchdbTypes = require("./couchdb-types"); -Object.keys(_couchdbTypes).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _couchdbTypes[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _couchdbTypes[key]; - } - }); -}); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -/** - * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb - * you can use it to sync collections with a remote CouchDB endpoint. - */ -var RxCouchDBNewReplicationState = /*#__PURE__*/function (_RxReplicationState) { - (0, _inheritsLoose2["default"])(RxCouchDBNewReplicationState, _RxReplicationState); - function RxCouchDBNewReplicationState(url, fetch, replicationIdentifierHash, collection, pull, push) { - var _this; - var live = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : true; - var retryTime = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 1000 * 5; - var autoStart = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : true; - _this = _RxReplicationState.call(this, replicationIdentifierHash, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; - _this.url = url; - _this.fetch = fetch; - _this.replicationIdentifierHash = replicationIdentifierHash; - _this.collection = collection; - _this.pull = pull; - _this.push = push; - _this.live = live; - _this.retryTime = retryTime; - _this.autoStart = autoStart; - return _this; - } - return RxCouchDBNewReplicationState; -}(_replication.RxReplicationState); -exports.RxCouchDBNewReplicationState = RxCouchDBNewReplicationState; -function syncCouchDBNew(options) { - options = (0, _util.flatClone)(options); - if (!options.url.endsWith('/')) { - options.url = options.url + '/'; - } - options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership; - var collection = this; - var pullStream$ = new _rxjs.Subject(); - var replicationPrimitivesPull; - if (options.pull) { - replicationPrimitivesPull = { - handler: function handler(lastPulledCheckpoint, batchSize) { - try { - /** - * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html - */ - var _url = options.url + '_changes?' + (0, _couchdbHelper.mergeUrlQueryParams)({ - style: 'all_docs', - feed: 'normal', - include_docs: true, - since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0, - heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, - limit: batchSize, - seq_interval: batchSize - }); - return Promise.resolve(replicationState.fetch(_url)).then(function (response) { - return Promise.resolve(response.json()).then(function (jsonResponse) { - var documents = jsonResponse.results.map(function (row) { - return (0, _couchdbHelper.couchDBDocToRxDocData)(collection.schema.primaryPath, (0, _util.ensureNotFalsy)(row.doc)); - }); - return { - documents: documents, - checkpoint: { - sequence: jsonResponse.last_seq - } - }; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }, - batchSize: (0, _util.ensureNotFalsy)(options.pull).batchSize, - modifier: (0, _util.ensureNotFalsy)(options.pull).modifier, - stream$: pullStream$.asObservable() - }; - } - var replicationPrimitivesPush; - if (options.push) { - replicationPrimitivesPush = { - handler: function handler(rows) { - try { - /** - * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs - */ - var _url2 = options.url + '_bulk_docs?' + (0, _couchdbHelper.mergeUrlQueryParams)({}); - var body = { - docs: rows.map(function (row) { - var sendDoc = (0, _util.flatClone)(row.newDocumentState); - if (row.assumedMasterState) { - sendDoc._rev = (0, _util.ensureNotFalsy)(row.assumedMasterState._rev); - } - return (0, _pouchdb.pouchSwapPrimaryToId)(collection.schema.primaryPath, sendDoc); - }) - }; - return Promise.resolve(replicationState.fetch(_url2, { - method: 'POST', - headers: { - 'content-type': 'application/json' - }, - body: JSON.stringify(body) - })).then(function (response) { - return Promise.resolve(response.json()).then(function (responseJson) { - var conflicts = responseJson.filter(function (row) { - var isConflict = row.error === 'conflict'; - if (!row.ok && !isConflict) { - throw (0, _index.newRxError)('SNH', { - args: { - row: row - } - }); - } - return isConflict; - }); - if (conflicts.length === 0) { - return []; - } - var getConflictDocsUrl = options.url + '_all_docs?' + (0, _couchdbHelper.mergeUrlQueryParams)({ - include_docs: true, - keys: JSON.stringify(conflicts.map(function (c) { - return c.id; - })) - }); - return Promise.resolve(replicationState.fetch(getConflictDocsUrl)).then(function (conflictResponse) { - return Promise.resolve(conflictResponse.json()).then(function (conflictResponseJson) { - var conflictDocsMasterState = conflictResponseJson.rows.map(function (r) { - return (0, _couchdbHelper.couchDBDocToRxDocData)(collection.schema.primaryPath, r.doc); - }); - return conflictDocsMasterState; - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }, - batchSize: options.push.batchSize, - modifier: options.push.modifier - }; - } - var replicationState = new RxCouchDBNewReplicationState(options.url, options.fetch ? options.fetch : fetch, _couchdbHelper.COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + (0, _util.fastUnsecureHash)(options.url), collection, replicationPrimitivesPull, replicationPrimitivesPush, options.live, options.retryTime, options.autoStart); - - /** - * Use long polling to get live changes for the pull.stream$ - */ - if (options.live && options.pull) { - var startBefore = replicationState.start.bind(replicationState); - replicationState.start = function () { - var since = 'now'; - var batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20; - (function () { - try { - var _temp3 = _for(function () { - return !replicationState.isStopped(); - }, void 0, function () { - function _temp2() { - var documents = jsonResponse.results.map(function (row) { - return (0, _couchdbHelper.couchDBDocToRxDocData)(collection.schema.primaryPath, (0, _util.ensureNotFalsy)(row.doc)); - }); - since = jsonResponse.last_seq; - pullStream$.next({ - documents: documents, - checkpoint: { - sequence: jsonResponse.last_seq - } - }); - } - var url = options.url + '_changes?' + (0, _couchdbHelper.mergeUrlQueryParams)({ - style: 'all_docs', - feed: 'longpoll', - since: since, - include_docs: true, - heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, - limit: batchSize, - seq_interval: batchSize - }); - var jsonResponse; - var _temp = _catch(function () { - return Promise.resolve(replicationState.fetch(url)).then(function (_replicationState$fet) { - return Promise.resolve(_replicationState$fet.json()).then(function (_await$replicationSta) { - jsonResponse = _await$replicationSta; - }); - }); - }, function (err) { - pullStream$.error(err); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - return _temp3 && _temp3.then ? _temp3.then(function () {}) : void 0; - } catch (e) { - Promise.reject(e); - } - })(); - return startBefore(); - }; - } - (0, _replication.startReplicationOnLeaderShip)(options.waitForLeadership, replicationState); - return replicationState; -} -var RxDBReplicationCouchDBNewPlugin = { - name: 'replication-couchdb-new', - init: function init() { - (0, _index.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncCouchDBNew = syncCouchDBNew; - } - } -}; -exports.RxDBReplicationCouchDBNewPlugin = RxDBReplicationCouchDBNewPlugin; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb-new/index.js.map b/dist/lib/plugins/replication-couchdb-new/index.js.map deleted file mode 100644 index b497c4071e0..00000000000 --- a/dist/lib/plugins/replication-couchdb-new/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","RxCouchDBNewReplicationState","url","fetch","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","RxReplicationState","syncCouchDBNew","options","flatClone","endsWith","waitForLeadership","pullStream$","Subject","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","mergeUrlQueryParams","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","replicationState","response","json","jsonResponse","documents","results","map","row","couchDBDocToRxDocData","schema","primaryPath","ensureNotFalsy","doc","checkpoint","last_seq","modifier","stream$","asObservable","replicationPrimitivesPush","rows","docs","sendDoc","newDocumentState","assumedMasterState","_rev","pouchSwapPrimaryToId","method","headers","JSON","stringify","responseJson","conflicts","filter","isConflict","error","ok","newRxError","args","length","getConflictDocsUrl","keys","c","id","conflictResponse","conflictResponseJson","conflictDocsMasterState","r","COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","fastUnsecureHash","startBefore","start","isStopped","next","err","startReplicationOnLeaderShip","RxDBReplicationCouchDBNewPlugin","name","init","addRxPlugin","RxDBLeaderElectionPlugin","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-couchdb-new/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb\n * you can use it to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n fastUnsecureHash,\n flatClone\n} from '../../util';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n RxPlugin,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n PouchdbChangesResult,\n PouchBulkDocResultRow,\n PouchAllDocsResponse\n} from '../../types';\nimport {\n RxReplicationState, startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDBNew\n} from './couchdb-types';\nimport {\n couchDBDocToRxDocData,\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n mergeUrlQueryParams\n} from './couchdb-helper';\nimport { pouchSwapPrimaryToId } from '../pouchdb';\n\nexport * from './couchdb-helper';\nexport * from './couchdb-types';\n\nexport class RxCouchDBNewReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function syncCouchDBNew(\n this: RxCollection,\n options: SyncOptionsCouchDBNew\n) {\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = this;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: PouchdbChangesResult = await response.json();\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: rows.map(row => {\n const sendDoc = flatClone(row.newDocumentState);\n if (row.assumedMasterState) {\n (sendDoc as any)._rev = ensureNotFalsy((row.assumedMasterState as any)._rev);\n }\n return pouchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: PouchBulkDocResultRow[] = await response.json();\n\n const conflicts = responseJson.filter(row => {\n const isConflict = row.error === 'conflict';\n if (!row.ok && !isConflict) {\n throw newRxError('SNH', { args: { row } });\n }\n return isConflict;\n });\n\n if (conflicts.length === 0) {\n return [];\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflicts.map(c => c.id))\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: PouchAllDocsResponse = await conflictResponse.json();\n const conflictDocsMasterState: WithDeleted[] = conflictResponseJson.rows\n .map(r => couchDBDocToRxDocData(collection.schema.primaryPath, r.doc));\n\n return conflictDocsMasterState;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxCouchDBNewReplicationState(\n options.url,\n options.fetch ? options.fetch : fetch,\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.url),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: PouchdbChangesResult;\n try {\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err) {\n pullStream$.error(err);\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n\n\nexport const RxDBReplicationCouchDBNewPlugin: RxPlugin = {\n name: 'replication-couchdb-new',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncCouchDBNew = syncCouchDBNew;\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAIA;AAMA;AAYA;AAGA;AAMA;AAMA;AAOA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAFA;AAGA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAqgBO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AArhBO,iBAAiBG,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KA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AC,YAAQkD,GAAG,EAAE;cACVpE,WAAW,CAACiD,KAAK,CAACmB,GAAG,CAAC;YAE1B,CAAC;YAAA;UAWL,CAAC;UAAA;QACL,CAAC;UAAA;QAAA;MAAA,IAAG;MACJ,OAAOJ,WAAW,EAAE;IACxB,CAAC;EACL;EAEA,IAAAK,yCAA4B,EAACzE,OAAO,CAACG,iBAAiB,EAAEgB,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B;AAGO,IAAMuD,+BAAyC,GAAG;EACrDC,IAAI,EAAE,yBAAyB;EAC/BC,IAAI,kBAAG;IACH,IAAAC,kBAAW,EAACC,wCAAwB,CAAC;EACzC,CAAC;EACDC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAACnF,cAAc,GAAGA,cAAc;IACzC;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb/couchdb-helper.js b/dist/lib/plugins/replication-couchdb/couchdb-helper.js new file mode 100644 index 00000000000..47a441b462f --- /dev/null +++ b/dist/lib/plugins/replication-couchdb/couchdb-helper.js @@ -0,0 +1,68 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = void 0; +exports.couchDBDocToRxDocData = couchDBDocToRxDocData; +exports.couchSwapIdToPrimary = couchSwapIdToPrimary; +exports.couchSwapPrimaryToId = couchSwapPrimaryToId; +exports.getDefaultFetch = getDefaultFetch; +exports.mergeUrlQueryParams = mergeUrlQueryParams; +var _utils = require("../../plugins/utils"); +var COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-'; +exports.COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX; +function mergeUrlQueryParams(params) { + return Object.entries(params).filter(function (_ref) { + var _k = _ref[0], + value = _ref[1]; + return typeof value !== 'undefined'; + }).map(function (_ref2) { + var key = _ref2[0], + value = _ref2[1]; + return key + '=' + value; + }).join('&'); +} +function couchDBDocToRxDocData(primaryPath, couchDocData) { + var doc = couchSwapIdToPrimary(primaryPath, couchDocData); + + // ensure deleted flag is set. + doc._deleted = !!doc._deleted; + return doc; +} +function couchSwapIdToPrimary(primaryKey, docData) { + if (primaryKey === '_id' || docData[primaryKey]) { + return docData; + } + docData = (0, _utils.flatClone)(docData); + docData[primaryKey] = docData._id; + delete docData._id; + return docData; +} + +/** + * Swaps the primaryKey of the document + * to the _id property. + */ +function couchSwapPrimaryToId(primaryKey, docData) { + // optimisation shortcut + if (primaryKey === '_id') { + return docData; + } + var idValue = docData[primaryKey]; + var ret = (0, _utils.flatClone)(docData); + delete ret[primaryKey]; + ret._id = idValue; + return ret; +} +function getDefaultFetch() { + if (typeof window === 'object' && window['fetch']) { + /** + * @link https://stackoverflow.com/a/47180009/3443137 + */ + return window.fetch.bind(window); + } else { + return fetch; + } +} +//# sourceMappingURL=couchdb-helper.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb/couchdb-helper.js.map b/dist/lib/plugins/replication-couchdb/couchdb-helper.js.map new file mode 100644 index 00000000000..4f973cd78ca --- /dev/null +++ b/dist/lib/plugins/replication-couchdb/couchdb-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"couchdb-helper.js","names":["COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","mergeUrlQueryParams","params","Object","entries","filter","_k","value","map","key","join","couchDBDocToRxDocData","primaryPath","couchDocData","doc","couchSwapIdToPrimary","_deleted","primaryKey","docData","flatClone","_id","couchSwapPrimaryToId","idValue","ret","getDefaultFetch","window","fetch","bind"],"sources":["../../../../src/plugins/replication-couchdb/couchdb-helper.ts"],"sourcesContent":["import type { RxDocumentData, StringKeys, WithDeleted } from '../../types';\nimport { flatClone } from '../../plugins/utils';\nimport { URLQueryParams } from './couchdb-types';\n\n\nexport const COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-couchdb-';\n\n\nexport function mergeUrlQueryParams(\n params: URLQueryParams\n): string {\n return Object.entries(params)\n .filter(([_k, value]) => typeof value !== 'undefined')\n .map(([key, value]) => key + '=' + value)\n .join('&');\n}\n\nexport function couchDBDocToRxDocData(\n primaryPath: string,\n couchDocData: any\n): WithDeleted {\n const doc = couchSwapIdToPrimary(primaryPath, couchDocData);\n\n // ensure deleted flag is set.\n doc._deleted = !!doc._deleted;\n\n return doc;\n}\n\n\nexport function couchSwapIdToPrimary(\n primaryKey: StringKeys>,\n docData: any\n): any {\n if (primaryKey === '_id' || docData[primaryKey]) {\n return docData;\n }\n docData = flatClone(docData);\n docData[primaryKey] = docData._id;\n delete docData._id;\n\n return docData;\n}\n\n/**\n * Swaps the primaryKey of the document\n * to the _id property.\n */\nexport function couchSwapPrimaryToId(\n primaryKey: StringKeys>,\n docData: any\n): RxDocType & { _id: string; } {\n // optimisation shortcut\n if (primaryKey === '_id') {\n return docData;\n }\n\n const idValue = docData[primaryKey];\n const ret = flatClone(docData);\n delete ret[primaryKey];\n ret._id = idValue;\n return ret;\n}\n\n\nexport function getDefaultFetch() {\n if (\n typeof window === 'object' &&\n (window as any)['fetch']\n ) {\n /**\n * @link https://stackoverflow.com/a/47180009/3443137\n */\n return window.fetch.bind(window);\n } else {\n return fetch;\n }\n}\n"],"mappings":";;;;;;;;;;;AACA;AAIO,IAAMA,8CAA8C,GAAG,2BAA2B;AAAC;AAGnF,SAASC,mBAAmB,CAC/BC,MAAsB,EAChB;EACN,OAAOC,MAAM,CAACC,OAAO,CAACF,MAAM,CAAC,CACxBG,MAAM,CAAC;IAAA,IAAEC,EAAE;MAAEC,KAAK;IAAA,OAAM,OAAOA,KAAK,KAAK,WAAW;EAAA,EAAC,CACrDC,GAAG,CAAC;IAAA,IAAEC,GAAG;MAAEF,KAAK;IAAA,OAAME,GAAG,GAAG,GAAG,GAAGF,KAAK;EAAA,EAAC,CACxCG,IAAI,CAAC,GAAG,CAAC;AAClB;AAEO,SAASC,qBAAqB,CACjCC,WAAmB,EACnBC,YAAiB,EACK;EACtB,IAAMC,GAAG,GAAGC,oBAAoB,CAACH,WAAW,EAAEC,YAAY,CAAC;;EAE3D;EACAC,GAAG,CAACE,QAAQ,GAAG,CAAC,CAACF,GAAG,CAACE,QAAQ;EAE7B,OAAOF,GAAG;AACd;AAGO,SAASC,oBAAoB,CAChCE,UAAyC,EACzCC,OAAY,EACT;EACH,IAAID,UAAU,KAAK,KAAK,IAAIC,OAAO,CAACD,UAAU,CAAC,EAAE;IAC7C,OAAOC,OAAO;EAClB;EACAA,OAAO,GAAG,IAAAC,gBAAS,EAACD,OAAO,CAAC;EAC5BA,OAAO,CAACD,UAAU,CAAC,GAAGC,OAAO,CAACE,GAAG;EACjC,OAAOF,OAAO,CAACE,GAAG;EAElB,OAAOF,OAAO;AAClB;;AAEA;AACA;AACA;AACA;AACO,SAASG,oBAAoB,CAChCJ,UAAiD,EACjDC,OAAY,EACgB;EAC5B;EACA,IAAID,UAAU,KAAK,KAAK,EAAE;IACtB,OAAOC,OAAO;EAClB;EAEA,IAAMI,OAAO,GAAGJ,OAAO,CAACD,UAAU,CAAC;EACnC,IAAMM,GAAG,GAAG,IAAAJ,gBAAS,EAACD,OAAO,CAAC;EAC9B,OAAOK,GAAG,CAACN,UAAU,CAAC;EACtBM,GAAG,CAACH,GAAG,GAAGE,OAAO;EACjB,OAAOC,GAAG;AACd;AAGO,SAASC,eAAe,GAAG;EAC9B,IACI,OAAOC,MAAM,KAAK,QAAQ,IACzBA,MAAM,CAAS,OAAO,CAAC,EAC1B;IACE;AACR;AACA;IACQ,OAAOA,MAAM,CAACC,KAAK,CAACC,IAAI,CAACF,MAAM,CAAC;EACpC,CAAC,MAAM;IACH,OAAOC,KAAK;EAChB;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb-new/couchdb-types.js b/dist/lib/plugins/replication-couchdb/couchdb-types.js similarity index 100% rename from dist/lib/plugins/replication-couchdb-new/couchdb-types.js rename to dist/lib/plugins/replication-couchdb/couchdb-types.js diff --git a/dist/lib/plugins/replication-couchdb/couchdb-types.js.map b/dist/lib/plugins/replication-couchdb/couchdb-types.js.map new file mode 100644 index 00000000000..338944e2b7d --- /dev/null +++ b/dist/lib/plugins/replication-couchdb/couchdb-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"couchdb-types.js","names":[],"sources":["../../../../src/plugins/replication-couchdb/couchdb-types.ts"],"sourcesContent":["import {\n ById,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nexport type CouchDBCheckpointType = {\n sequence: number;\n};\n\nexport type FetchMethodType = typeof fetch;\nexport type SyncOptionsCouchDB = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier'\n> & {\n url: string;\n /**\n * Here you can set a custom fetch method\n * to use http headers or credentials when doing requests.\n */\n fetch?: FetchMethodType;\n pull?: Omit, 'handler' | 'stream$'> & {\n /**\n * Heartbeat time in milliseconds\n * for the long polling of the changestream.\n */\n heartbeat?: number;\n };\n push?: Omit, 'handler'>;\n};\n\n\nexport type URLQueryParams = ById;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb/index.js b/dist/lib/plugins/replication-couchdb/index.js index 4c4aa7454eb..08373dda38a 100644 --- a/dist/lib/plugins/replication-couchdb/index.js +++ b/dist/lib/plugins/replication-couchdb/index.js @@ -4,312 +4,294 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.RxDBReplicationCouchDBPlugin = exports.RxCouchDBReplicationStateBase = void 0; -exports.createRxCouchDBReplicationState = createRxCouchDBReplicationState; -exports.pouchReplicationFunction = pouchReplicationFunction; -exports.setPouchEventEmitter = setPouchEventEmitter; -exports.syncCouchDB = syncCouchDB; -var _pouchdbReplication = _interopRequireDefault(require("pouchdb-replication")); +var _exportNames = { + RxCouchDBReplicationState: true, + replicateCouchDB: true +}; +exports.RxCouchDBReplicationState = void 0; +exports.replicateCouchDB = replicateCouchDB; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); +var _utils = require("../../plugins/utils"); +var _leaderElection = require("../leader-election"); +var _replication = require("../replication"); +var _index = require("../../index"); var _rxjs = require("rxjs"); -var _operators = require("rxjs/operators"); -var _util = require("../../util"); -var _rxError = require("../../rx-error"); -var _pouchdb = require("../../plugins/pouchdb"); -var _rxCollection = require("../../rx-collection"); -/** - * this plugin adds the RxCollection.sync()-function to rxdb - * you can use it to sync collections with remote or local couchdb-instances - */ - -/** - * Contains all pouchdb instances that - * are used inside of RxDB by collections or databases. - * Used to ensure the remote of a replication cannot be an internal pouchdb. - */ -var INTERNAL_POUCHDBS = new WeakSet(); -var RxCouchDBReplicationStateBase = /*#__PURE__*/function () { - function RxCouchDBReplicationStateBase(collection, syncOptions) { - var _this = this; - this._subs = []; - this._subjects = { - change: new _rxjs.Subject(), - docs: new _rxjs.Subject(), - denied: new _rxjs.Subject(), - active: new _rxjs.BehaviorSubject(false), - complete: new _rxjs.BehaviorSubject(false), - alive: new _rxjs.BehaviorSubject(false), - error: new _rxjs.Subject() - }; - this.canceled = false; - this.collection = collection; - this.syncOptions = syncOptions; - // create getters - Object.keys(this._subjects).forEach(function (key) { - Object.defineProperty(_this, key + '$', { - get: function get() { - return this._subjects[key].asObservable(); - } - }); - }); - } - var _proto = RxCouchDBReplicationStateBase.prototype; - _proto.awaitInitialReplication = function awaitInitialReplication() { - if (this.syncOptions.options && this.syncOptions.options.live) { - throw (0, _rxError.newRxError)('RC4', { - database: this.collection.database.name, - collection: this.collection.name - }); - } - if (this.collection.database.multiInstance && this.syncOptions.waitForLeadership) { - throw (0, _rxError.newRxError)('RC5', { - database: this.collection.database.name, - collection: this.collection.name - }); - } - var that = this; - return (0, _rxjs.firstValueFrom)(that.complete$.pipe((0, _operators.filter)(function (x) { - return !!x; - }))); - } - - /** - * Returns false when the replication has already been canceled - */; - _proto.cancel = function cancel() { - var _this2 = this; - if (this.canceled) { - return _util.PROMISE_RESOLVE_FALSE; +var _couchdbHelper = require("./couchdb-helper"); +Object.keys(_couchdbHelper).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _couchdbHelper[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _couchdbHelper[key]; } - this.canceled = true; - var ret = _util.PROMISE_RESOLVE_TRUE; - if (this._pouchEventEmitterObject) { - /** - * Calling cancel() does not return a promise, - * so we have to await the complete event - * to know that everything is cleaned up properly. - */ - ret = new Promise(function (res) { - (0, _util.ensureNotFalsy)(_this2._pouchEventEmitterObject).on('complete', function () { - res(true); - }); - }); - this._pouchEventEmitterObject.cancel(); - } - this._subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - return ret; - }; - return RxCouchDBReplicationStateBase; -}(); -exports.RxCouchDBReplicationStateBase = RxCouchDBReplicationStateBase; -function setPouchEventEmitter(rxRepState, evEmitter) { - if (rxRepState._pouchEventEmitterObject) { - throw (0, _rxError.newRxError)('RC1'); - } - rxRepState._pouchEventEmitterObject = evEmitter; - - // change - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'change').subscribe(function (ev) { - rxRepState._subjects.change.next(ev); - })); - - // denied - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'denied').subscribe(function (ev) { - return rxRepState._subjects.denied.next(ev); - })); - - // docs - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'change').subscribe(function (ev) { - if (rxRepState._subjects.docs.observers.length === 0 || ev.direction !== 'pull') return; - ev.change.docs.filter(function (doc) { - return doc.language !== 'query'; - }) // remove internal docs - // do primary-swap and keycompression - .forEach(function (doc) { - return rxRepState._subjects.docs.next(doc); - }); - })); - - // error - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'error').subscribe(function (ev) { - return rxRepState._subjects.error.next(ev); - })); - - // active - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'active').subscribe(function () { - return rxRepState._subjects.active.next(true); - })); - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'paused').subscribe(function () { - return rxRepState._subjects.active.next(false); - })); - - // complete - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'complete').subscribe(function (info) { - try { - /** - * when complete fires, it might be that not all changeEvents - * have passed through, because of the delay of .wachtForChanges() - * Therefore we have to first ensure that all previous changeEvents have been handled - */ - return Promise.resolve((0, _util.promiseWait)(100)).then(function () { - rxRepState._subjects.complete.next(info); - }); - } catch (e) { - return Promise.reject(e); - } - })); - // auto-cancel one-time replications on complelete to not cause memory leak - if (!rxRepState.syncOptions.options || !rxRepState.syncOptions.options.live) { - rxRepState._subs.push(rxRepState.complete$.pipe((0, _operators.filter)(function (x) { - return !!x; - }), (0, _operators.first)(), (0, _operators.mergeMap)(function () { - return rxRepState.collection.database.requestIdlePromise().then(function () { - return rxRepState.cancel(); - }); - })).subscribe()); - } - function getIsAlive(emitter) { - // "state" will live in emitter.state if single direction replication - // or in emitter.push.state & emitter.pull.state when syncing for both - var state = emitter.state; - if (!state) { - state = [emitter.pull.state, emitter.push.state].reduce(function (acc, val) { - if (acc === 'active' || val === 'active') return 'active'; - return acc === 'stopped' ? acc : val; - }, ''); - } - - // If it's active, we can't determine whether the connection is active - // or not yet - if (state === 'active') { - return (0, _util.promiseWait)(15).then(function () { - return getIsAlive(emitter); - }); + }); +}); +var _couchdbTypes = require("./couchdb-types"); +Object.keys(_couchdbTypes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _couchdbTypes[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _couchdbTypes[key]; } - var isAlive = state !== 'stopped'; - return Promise.resolve(isAlive); - } - rxRepState._subs.push((0, _rxjs.fromEvent)(evEmitter, 'paused').pipe((0, _operators.skipUntil)((0, _rxjs.fromEvent)(evEmitter, 'active'))).subscribe(function () { - getIsAlive(rxRepState._pouchEventEmitterObject).then(function (isAlive) { - return rxRepState._subjects.alive.next(isAlive); - }); - })); -} -function createRxCouchDBReplicationState(collection, syncOptions) { - return new RxCouchDBReplicationStateBase(collection, syncOptions); -} - + }); +}); /** - * get the correct function-name for pouchdb-replication + * This plugin can be used to sync collections with a remote CouchDB endpoint. */ -function pouchReplicationFunction(pouch, _ref) { - var _ref$pull = _ref.pull, - pull = _ref$pull === void 0 ? true : _ref$pull, - _ref$push = _ref.push, - push = _ref$push === void 0 ? true : _ref$push; - if (pull && push) { - return pouch.sync.bind(pouch); +var RxCouchDBReplicationState = /*#__PURE__*/function (_RxReplicationState) { + (0, _inheritsLoose2["default"])(RxCouchDBReplicationState, _RxReplicationState); + function RxCouchDBReplicationState(url, fetch, replicationIdentifierHash, collection, pull, push) { + var _this; + var live = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : true; + var retryTime = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 1000 * 5; + var autoStart = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : true; + _this = _RxReplicationState.call(this, replicationIdentifierHash, collection, '_deleted', pull, push, live, retryTime, autoStart) || this; + _this.url = url; + _this.fetch = fetch; + _this.replicationIdentifierHash = replicationIdentifierHash; + _this.collection = collection; + _this.pull = pull; + _this.push = push; + _this.live = live; + _this.retryTime = retryTime; + _this.autoStart = autoStart; + return _this; } - if (!pull && push) { - return pouch.replicate.to.bind(pouch); + return RxCouchDBReplicationState; +}(_replication.RxReplicationState); +exports.RxCouchDBReplicationState = RxCouchDBReplicationState; +function replicateCouchDB(options) { + var collection = options.collection; + (0, _index.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); + options = (0, _utils.flatClone)(options); + if (!options.url.endsWith('/')) { + options.url = options.url + '/'; } - if (pull && !push) { - return pouch.replicate.from.bind(pouch); - } - if (!pull && !push) { - throw (0, _rxError.newRxError)('UT3', { - pull: pull, - push: push - }); + options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership; + var pullStream$ = new _rxjs.Subject(); + var replicationPrimitivesPull; + if (options.pull) { + replicationPrimitivesPull = { + handler: function () { + var _handler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(lastPulledCheckpoint, batchSize) { + var url, response, jsonResponse, documents; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html + */ + url = options.url + '_changes?' + (0, _couchdbHelper.mergeUrlQueryParams)({ + style: 'all_docs', + feed: 'normal', + include_docs: true, + since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0, + heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, + limit: batchSize, + seq_interval: batchSize + }); + _context.next = 3; + return replicationState.fetch(url); + case 3: + response = _context.sent; + _context.next = 6; + return response.json(); + case 6: + jsonResponse = _context.sent; + documents = jsonResponse.results.map(function (row) { + return (0, _couchdbHelper.couchDBDocToRxDocData)(collection.schema.primaryPath, (0, _utils.ensureNotFalsy)(row.doc)); + }); + return _context.abrupt("return", { + documents: documents, + checkpoint: { + sequence: jsonResponse.last_seq + } + }); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + function handler(_x, _x2) { + return _handler.apply(this, arguments); + } + return handler; + }(), + batchSize: (0, _utils.ensureNotFalsy)(options.pull).batchSize, + modifier: (0, _utils.ensureNotFalsy)(options.pull).modifier, + stream$: pullStream$.asObservable() + }; } -} -function syncCouchDB(_ref2) { - var _this3 = this; - var remote = _ref2.remote, - _ref2$waitForLeadersh = _ref2.waitForLeadership, - waitForLeadership = _ref2$waitForLeadersh === void 0 ? true : _ref2$waitForLeadersh, - _ref2$direction = _ref2.direction, - direction = _ref2$direction === void 0 ? { - pull: true, - push: true - } : _ref2$direction, - _ref2$options = _ref2.options, - options = _ref2$options === void 0 ? { - live: true, - retry: true - } : _ref2$options, - query = _ref2.query; - var useOptions = (0, _util.flatClone)(options); - - // prevent #641 by not allowing internal pouchdbs as remote - if ((0, _pouchdb.isInstanceOf)(remote) && INTERNAL_POUCHDBS.has(remote)) { - throw (0, _rxError.newRxError)('RC3', { - database: this.database.name, - collection: this.name - }); + var replicationPrimitivesPush; + if (options.push) { + replicationPrimitivesPush = { + handler: function () { + var _handler2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rows) { + var url, body, response, responseJson, conflicts, getConflictDocsUrl, conflictResponse, conflictResponseJson, conflictDocsMasterState; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + /** + * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs + */ + url = options.url + '_bulk_docs?' + (0, _couchdbHelper.mergeUrlQueryParams)({}); + body = { + docs: rows.map(function (row) { + var sendDoc = (0, _utils.flatClone)(row.newDocumentState); + if (row.assumedMasterState) { + sendDoc._rev = (0, _utils.ensureNotFalsy)(row.assumedMasterState._rev); + } + return (0, _couchdbHelper.couchSwapPrimaryToId)(collection.schema.primaryPath, sendDoc); + }) + }; + _context2.next = 4; + return replicationState.fetch(url, { + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify(body) + }); + case 4: + response = _context2.sent; + _context2.next = 7; + return response.json(); + case 7: + responseJson = _context2.sent; + conflicts = responseJson.filter(function (row) { + var isConflict = row.error === 'conflict'; + if (!row.ok && !isConflict) { + throw (0, _index.newRxError)('SNH', { + args: { + row: row + } + }); + } + return isConflict; + }); + if (!(conflicts.length === 0)) { + _context2.next = 11; + break; + } + return _context2.abrupt("return", []); + case 11: + getConflictDocsUrl = options.url + '_all_docs?' + (0, _couchdbHelper.mergeUrlQueryParams)({ + include_docs: true, + keys: JSON.stringify(conflicts.map(function (c) { + return c.id; + })) + }); + _context2.next = 14; + return replicationState.fetch(getConflictDocsUrl); + case 14: + conflictResponse = _context2.sent; + _context2.next = 17; + return conflictResponse.json(); + case 17: + conflictResponseJson = _context2.sent; + conflictDocsMasterState = conflictResponseJson.rows.map(function (r) { + return (0, _couchdbHelper.couchDBDocToRxDocData)(collection.schema.primaryPath, r.doc); + }); + return _context2.abrupt("return", conflictDocsMasterState); + case 20: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x3) { + return _handler2.apply(this, arguments); + } + return handler; + }(), + batchSize: options.push.batchSize, + modifier: options.push.modifier + }; } + var replicationState = new RxCouchDBReplicationState(options.url, options.fetch ? options.fetch : (0, _couchdbHelper.getDefaultFetch)(), _couchdbHelper.COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + (0, _utils.fastUnsecureHash)(options.url), collection, replicationPrimitivesPull, replicationPrimitivesPush, options.live, options.retryTime, options.autoStart); - // if remote is RxCollection, get internal pouchdb - if ((0, _rxCollection.isRxCollection)(remote)) { - remote = remote.storageInstance.internals.pouch; - } - if (query && this !== query.collection) { - throw (0, _rxError.newRxError)('RC2', { - query: query - }); - } - var pouch = (0, _pouchdb.getPouchDBOfRxCollection)(this); - var syncFun = pouchReplicationFunction(pouch, direction); - if (query) { - useOptions.selector = query.getPreparedQuery().selector; + /** + * Use long polling to get live changes for the pull.stream$ + */ + if (options.live && options.pull) { + var startBefore = replicationState.start.bind(replicationState); + replicationState.start = function () { + var since = 'now'; + var batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20; + (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var _url, jsonResponse, documents; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (replicationState.isStopped()) { + _context3.next = 22; + break; + } + _url = options.url + '_changes?' + (0, _couchdbHelper.mergeUrlQueryParams)({ + style: 'all_docs', + feed: 'longpoll', + since: since, + include_docs: true, + heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000, + limit: batchSize, + seq_interval: batchSize + }); + jsonResponse = void 0; + _context3.prev = 3; + _context3.next = 6; + return replicationState.fetch(_url); + case 6: + _context3.next = 8; + return _context3.sent.json(); + case 8: + jsonResponse = _context3.sent; + _context3.next = 17; + break; + case 11: + _context3.prev = 11; + _context3.t0 = _context3["catch"](3); + pullStream$.error((0, _index.newRxError)('RC_STREAM', { + args: { + url: _url + }, + error: (0, _utils.errorToPlainJson)(_context3.t0) + })); + // await next tick here otherwise we could go in to a 100% CPU blocking cycle. + _context3.next = 16; + return collection.promiseWait(0); + case 16: + return _context3.abrupt("continue", 0); + case 17: + documents = jsonResponse.results.map(function (row) { + return (0, _couchdbHelper.couchDBDocToRxDocData)(collection.schema.primaryPath, (0, _utils.ensureNotFalsy)(row.doc)); + }); + since = jsonResponse.last_seq; + pullStream$.next({ + documents: documents, + checkpoint: { + sequence: jsonResponse.last_seq + } + }); + _context3.next = 0; + break; + case 22: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[3, 11]]); + }))(); + return startBefore(); + }; } - var repState = createRxCouchDBReplicationState(this, { - remote: remote, - waitForLeadership: waitForLeadership, - direction: direction, - options: options, - query: query - }); - - // run internal so .sync() does not have to be async - var waitTillRun = waitForLeadership && this.database.multiInstance // do not await leadership if not multiInstance - ? this.database.waitForLeadership() : (0, _util.promiseWait)(0); - waitTillRun.then(function () { - if (_this3.destroyed || repState.canceled) { - return; - } - var pouchSync = syncFun(remote, useOptions); - setPouchEventEmitter(repState, pouchSync); - _this3.onDestroy.push(function () { - return repState.cancel(); - }); - }); - return repState; + (0, _replication.startReplicationOnLeaderShip)(options.waitForLeadership, replicationState); + return replicationState; } -var RxDBReplicationCouchDBPlugin = { - name: 'replication-couchdb', - rxdb: true, - init: function init() { - // add pouchdb-replication-plugin - (0, _pouchdb.addPouchPlugin)(_pouchdbReplication["default"]); - }, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncCouchDB = syncCouchDB; - } - }, - hooks: { - createRxCollection: { - after: function after(args) { - var collection = args.collection; - var pouch = collection.storageInstance.internals.pouch; - if (pouch) { - INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch); - } - } - } - } -}; -exports.RxDBReplicationCouchDBPlugin = RxDBReplicationCouchDBPlugin; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-couchdb/index.js.map b/dist/lib/plugins/replication-couchdb/index.js.map index 0a7d6e8fdaf..46c72470369 100644 --- a/dist/lib/plugins/replication-couchdb/index.js.map +++ b/dist/lib/plugins/replication-couchdb/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["INTERNAL_POUCHDBS","WeakSet","RxCouchDBReplicationStateBase","collection","syncOptions","_subs","_subjects","change","Subject","docs","denied","active","BehaviorSubject","complete","alive","error","canceled","Object","keys","forEach","key","defineProperty","get","asObservable","awaitInitialReplication","options","live","newRxError","database","name","multiInstance","waitForLeadership","that","firstValueFrom","complete$","pipe","filter","x","cancel","PROMISE_RESOLVE_FALSE","ret","PROMISE_RESOLVE_TRUE","_pouchEventEmitterObject","Promise","res","ensureNotFalsy","on","sub","unsubscribe","setPouchEventEmitter","rxRepState","evEmitter","push","fromEvent","subscribe","ev","next","observers","length","direction","doc","language","info","promiseWait","first","mergeMap","requestIdlePromise","then","getIsAlive","emitter","state","pull","reduce","acc","val","isAlive","resolve","skipUntil","createRxCouchDBReplicationState","pouchReplicationFunction","pouch","sync","bind","replicate","to","from","syncCouchDB","remote","retry","query","useOptions","flatClone","isInstanceOfPouchDB","has","isRxCollection","storageInstance","internals","getPouchDBOfRxCollection","syncFun","selector","getPreparedQuery","repState","waitTillRun","destroyed","pouchSync","onDestroy","RxDBReplicationCouchDBPlugin","rxdb","init","addPouchPlugin","PouchReplicationPlugin","prototypes","RxCollection","proto","hooks","createRxCollection","after","args","add"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.sync()-function to rxdb\n * you can use it to sync collections with remote or local couchdb-instances\n */\n\nimport PouchReplicationPlugin from 'pouchdb-replication';\nimport {\n BehaviorSubject,\n Subject,\n fromEvent,\n Subscription,\n Observable,\n firstValueFrom\n} from 'rxjs';\nimport {\n skipUntil,\n filter,\n first,\n mergeMap\n} from 'rxjs/operators';\n\nimport {\n promiseWait,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n ensureNotFalsy\n} from '../../util';\nimport {\n newRxError\n} from '../../rx-error';\nimport {\n isInstanceOf as isInstanceOfPouchDB,\n addPouchPlugin,\n getPouchDBOfRxCollection\n} from '../../plugins/pouchdb';\n\nimport {\n isRxCollection\n} from '../../rx-collection';\nimport type {\n RxCollection,\n PouchSyncHandler,\n PouchReplicationOptions,\n RxPlugin,\n SyncOptions,\n PouchDBInstance\n} from '../../types';\n\n/**\n * Contains all pouchdb instances that\n * are used inside of RxDB by collections or databases.\n * Used to ensure the remote of a replication cannot be an internal pouchdb.\n */\nconst INTERNAL_POUCHDBS = new WeakSet();\n\nexport class RxCouchDBReplicationStateBase {\n public _subs: Subscription[] = [];\n\n // can be used for debugging or custom event-handling\n // will be set some time after sync() is called\n public _pouchEventEmitterObject?: PouchSyncHandler | null;\n public _subjects = {\n change: new Subject(),\n docs: new Subject(),\n denied: new Subject(),\n active: new BehaviorSubject(false),\n complete: new BehaviorSubject(false),\n alive: new BehaviorSubject(false),\n error: new Subject(),\n };\n\n public canceled: boolean = false;\n\n constructor(\n public readonly collection: RxCollection,\n public readonly syncOptions: SyncOptions\n ) {\n // create getters\n Object.keys(this._subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this._subjects[key].asObservable();\n }\n });\n });\n }\n\n awaitInitialReplication(): Promise {\n if (this.syncOptions.options && this.syncOptions.options.live) {\n throw newRxError('RC4', {\n database: this.collection.database.name,\n collection: this.collection.name\n });\n }\n if (this.collection.database.multiInstance && this.syncOptions.waitForLeadership) {\n throw newRxError('RC5', {\n database: this.collection.database.name,\n collection: this.collection.name\n });\n }\n\n const that: RxCouchDBReplicationState = this as any;\n return firstValueFrom(\n that.complete$.pipe(\n filter(x => !!x)\n )\n );\n }\n\n /**\n * Returns false when the replication has already been canceled\n */\n cancel(): Promise {\n if (this.canceled) {\n return PROMISE_RESOLVE_FALSE;\n }\n this.canceled = true;\n let ret = PROMISE_RESOLVE_TRUE;\n if (this._pouchEventEmitterObject) {\n /**\n * Calling cancel() does not return a promise,\n * so we have to await the complete event\n * to know that everything is cleaned up properly.\n */\n ret = new Promise(res => {\n ensureNotFalsy(this._pouchEventEmitterObject)\n .on('complete', () => {\n res(true);\n });\n });\n this._pouchEventEmitterObject.cancel();\n }\n this._subs.forEach(sub => sub.unsubscribe());\n return ret;\n }\n}\n\nexport type RxCouchDBReplicationState = RxCouchDBReplicationStateBase & {\n change$: Observable;\n docs$: Observable;\n denied$: Observable;\n active$: Observable;\n alive$: Observable;\n complete$: Observable;\n error$: Observable;\n};\n\nexport function setPouchEventEmitter(\n rxRepState: RxCouchDBReplicationState,\n evEmitter: PouchSyncHandler\n) {\n if (rxRepState._pouchEventEmitterObject) {\n throw newRxError('RC1');\n }\n rxRepState._pouchEventEmitterObject = evEmitter;\n\n // change\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'change')\n .subscribe(ev => {\n rxRepState._subjects.change.next(ev);\n })\n );\n\n // denied\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'denied')\n .subscribe(ev => rxRepState._subjects.denied.next(ev))\n );\n\n // docs\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'change')\n .subscribe(ev => {\n if (\n rxRepState._subjects.docs.observers.length === 0 ||\n (ev as any).direction !== 'pull'\n ) return;\n\n (ev as any).change.docs\n .filter((doc: any) => doc.language !== 'query') // remove internal docs\n // do primary-swap and keycompression\n .forEach((doc: any) => rxRepState._subjects.docs.next(doc));\n }));\n\n // error\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'error')\n .subscribe(ev => rxRepState._subjects.error.next(ev))\n );\n\n // active\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'active')\n .subscribe(() => rxRepState._subjects.active.next(true))\n );\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'paused')\n .subscribe(() => rxRepState._subjects.active.next(false))\n );\n\n // complete\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'complete')\n .subscribe(async (info: any) => {\n /**\n * when complete fires, it might be that not all changeEvents\n * have passed through, because of the delay of .wachtForChanges()\n * Therefore we have to first ensure that all previous changeEvents have been handled\n */\n await promiseWait(100);\n rxRepState._subjects.complete.next(info);\n })\n );\n // auto-cancel one-time replications on complelete to not cause memory leak\n if (\n !rxRepState.syncOptions.options ||\n !rxRepState.syncOptions.options.live\n ) {\n rxRepState._subs.push(\n rxRepState.complete$.pipe(\n filter(x => !!x),\n first(),\n mergeMap(() => {\n return rxRepState.collection.database\n .requestIdlePromise()\n .then(() => rxRepState.cancel());\n })\n ).subscribe()\n );\n }\n\n function getIsAlive(emitter: any): Promise {\n // \"state\" will live in emitter.state if single direction replication\n // or in emitter.push.state & emitter.pull.state when syncing for both\n let state = emitter.state;\n if (!state) {\n state = [emitter.pull.state, emitter.push.state]\n .reduce((acc, val) => {\n if (acc === 'active' || val === 'active') return 'active';\n return acc === 'stopped' ? acc : val;\n }, '');\n }\n\n // If it's active, we can't determine whether the connection is active\n // or not yet\n if (state === 'active') {\n return promiseWait(15).then(() => getIsAlive(emitter));\n }\n\n const isAlive = state !== 'stopped';\n return Promise.resolve(isAlive);\n }\n\n rxRepState._subs.push(\n fromEvent(evEmitter as any, 'paused')\n .pipe(\n skipUntil(fromEvent(evEmitter as any, 'active'))\n ).subscribe(() => {\n getIsAlive(rxRepState._pouchEventEmitterObject)\n .then(isAlive => rxRepState._subjects.alive.next(isAlive));\n })\n );\n}\n\nexport function createRxCouchDBReplicationState(\n collection: RxCollection,\n syncOptions: SyncOptions\n): RxCouchDBReplicationState {\n return new RxCouchDBReplicationStateBase(\n collection,\n syncOptions\n ) as RxCouchDBReplicationState;\n}\n\n/**\n * get the correct function-name for pouchdb-replication\n */\nexport function pouchReplicationFunction(\n pouch: PouchDBInstance,\n {\n pull = true,\n push = true\n }\n): any {\n if (pull && push) {\n return pouch.sync.bind(pouch);\n }\n if (!pull && push) {\n return (pouch.replicate as any).to.bind(pouch);\n }\n if (pull && !push) {\n return (pouch.replicate as any).from.bind(pouch);\n }\n if (!pull && !push) {\n throw newRxError('UT3', {\n pull,\n push\n });\n }\n}\n\nexport function syncCouchDB(\n this: RxCollection,\n {\n remote,\n waitForLeadership = true,\n direction = {\n pull: true,\n push: true\n },\n options = {\n live: true,\n retry: true\n },\n query\n }: SyncOptions) {\n const useOptions: PouchReplicationOptions & { selector: any; } = flatClone(options) as any;\n\n // prevent #641 by not allowing internal pouchdbs as remote\n if (\n isInstanceOfPouchDB(remote) &&\n INTERNAL_POUCHDBS.has(remote)\n ) {\n throw newRxError('RC3', {\n database: this.database.name,\n collection: this.name\n });\n }\n\n // if remote is RxCollection, get internal pouchdb\n if (isRxCollection(remote)) {\n remote = (remote as RxCollection).storageInstance.internals.pouch;\n }\n\n if (query && this !== query.collection) {\n throw newRxError('RC2', {\n query\n });\n }\n\n const pouch = getPouchDBOfRxCollection(this);\n const syncFun = pouchReplicationFunction(pouch, direction);\n if (query) {\n useOptions.selector = query.getPreparedQuery().selector;\n }\n\n const repState: any = createRxCouchDBReplicationState(\n this,\n {\n remote,\n waitForLeadership,\n direction,\n options,\n query\n }\n );\n\n // run internal so .sync() does not have to be async\n const waitTillRun = (\n waitForLeadership &&\n this.database.multiInstance // do not await leadership if not multiInstance\n ) ? this.database.waitForLeadership() : promiseWait(0);\n (waitTillRun as any).then(() => {\n if (this.destroyed || repState.canceled) {\n return;\n }\n const pouchSync = syncFun(remote, useOptions);\n setPouchEventEmitter(repState, pouchSync);\n\n this.onDestroy.push(() => repState.cancel());\n });\n\n return repState;\n}\n\n\n\nexport const RxDBReplicationCouchDBPlugin: RxPlugin = {\n name: 'replication-couchdb',\n rxdb: true,\n init() {\n // add pouchdb-replication-plugin\n addPouchPlugin(PouchReplicationPlugin);\n },\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncCouchDB = syncCouchDB;\n }\n },\n hooks: {\n createRxCollection: {\n after: args => {\n const collection = args.collection;\n const pouch: PouchDBInstance | undefined = collection.storageInstance.internals.pouch;\n if (pouch) {\n INTERNAL_POUCHDBS.add(collection.storageInstance.internals.pouch);\n }\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;AAKA;AACA;AAQA;AAOA;AAOA;AAGA;AAMA;AArCA;AACA;AACA;AACA;;AA8CA;AACA;AACA;AACA;AACA;AACA,IAAMA,iBAAiB,GAAG,IAAIC,OAAO,EAAE;AAAC,IAE3BC,6BAA6B;EAkBtC,uCACoBC,UAAwB,EACxBC,WAAwB,EAC1C;IAAA;IAAA,KApBKC,KAAK,GAAmB,EAAE;IAAA,KAK1BC,SAAS,GAAG;MACfC,MAAM,EAAE,IAAIC,aAAO,EAAE;MACrBC,IAAI,EAAE,IAAID,aAAO,EAAE;MACnBE,MAAM,EAAE,IAAIF,aAAO,EAAE;MACrBG,MAAM,EAAE,IAAIC,qBAAe,CAAC,KAAK,CAAC;MAClCC,QAAQ,EAAE,IAAID,qBAAe,CAAC,KAAK,CAAC;MACpCE,KAAK,EAAE,IAAIF,qBAAe,CAAC,KAAK,CAAC;MACjCG,KAAK,EAAE,IAAIP,aAAO;IACtB,CAAC;IAAA,KAEMQ,QAAQ,GAAY,KAAK;IAAA,KAGZb,UAAwB,GAAxBA,UAAwB;IAAA,KACxBC,WAAwB,GAAxBA,WAAwB;IAExC;IACAa,MAAM,CAACC,IAAI,CAAC,IAAI,CAACZ,SAAS,CAAC,CAACa,OAA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,EAAE;MAChBC,KAAK,EAAE,eAAAC,IAAI,EAAI;QACX,IAAMlH,UAAU,GAAGkH,IAAI,CAAClH,UAAU;QAClC,IAAM6E,KAAkC,GAAG7E,UAAU,CAAC4F,eAAe,CAACC,SAAS,CAAChB,KAAK;QACrF,IAAIA,KAAK,EAAE;UACPhF,iBAAiB,CAACsH,GAAG,CAACnH,UAAU,CAAC4F,eAAe,CAACC,SAAS,CAAChB,KAAK,CAAC;QACrE;MACJ;IACJ;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["RxCouchDBReplicationState","url","fetch","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","RxReplicationState","replicateCouchDB","options","addRxPlugin","RxDBLeaderElectionPlugin","flatClone","endsWith","waitForLeadership","pullStream$","Subject","replicationPrimitivesPull","handler","lastPulledCheckpoint","batchSize","mergeUrlQueryParams","style","feed","include_docs","since","sequence","heartbeat","limit","seq_interval","replicationState","response","json","jsonResponse","documents","results","map","row","couchDBDocToRxDocData","schema","primaryPath","ensureNotFalsy","doc","checkpoint","last_seq","modifier","stream$","asObservable","replicationPrimitivesPush","rows","body","docs","sendDoc","newDocumentState","assumedMasterState","_rev","couchSwapPrimaryToId","method","headers","JSON","stringify","responseJson","conflicts","filter","isConflict","error","ok","newRxError","args","length","getConflictDocsUrl","keys","c","id","conflictResponse","conflictResponseJson","conflictDocsMasterState","r","getDefaultFetch","COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX","fastUnsecureHash","startBefore","start","bind","isStopped","errorToPlainJson","promiseWait","next","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-couchdb/index.ts"],"sourcesContent":["/**\n * This plugin can be used to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n fastUnsecureHash,\n flatClone\n} from '../../plugins/utils';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem,\n CouchdbChangesResult,\n CouchBulkDocResultRow,\n CouchAllDocsResponse\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n newRxError,\n WithDeleted\n} from '../../index';\n\nimport { Subject } from 'rxjs';\nimport type {\n CouchDBCheckpointType,\n FetchMethodType,\n SyncOptionsCouchDB\n} from './couchdb-types';\nimport {\n couchDBDocToRxDocData,\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n mergeUrlQueryParams,\n couchSwapPrimaryToId,\n getDefaultFetch\n} from './couchdb-helper';\n\nexport * from './couchdb-helper';\nexport * from './couchdb-types';\n\nexport class RxCouchDBReplicationState extends RxReplicationState {\n constructor(\n public readonly url: string,\n public fetch: FetchMethodType,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateCouchDB(\n options: SyncOptionsCouchDB\n) {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n options = flatClone(options);\n if (!options.url.endsWith('/')) {\n options.url = options.url + '/';\n }\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CouchDBCheckpointType | undefined,\n batchSize: number\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/changes.html\n */\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'normal',\n include_docs: true,\n since: lastPulledCheckpoint ? lastPulledCheckpoint.sequence : 0,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n const response = await replicationState.fetch(url);\n const jsonResponse: CouchdbChangesResult = await response.json();\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n return {\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n };\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n /**\n * @link https://docs.couchdb.org/en/3.2.2-docs/api/database/bulk-api.html#db-bulk-docs\n */\n const url = options.url + '_bulk_docs?' + mergeUrlQueryParams({});\n const body = {\n docs: rows.map(row => {\n const sendDoc = flatClone(row.newDocumentState);\n if (row.assumedMasterState) {\n (sendDoc as any)._rev = ensureNotFalsy((row.assumedMasterState as any)._rev);\n }\n return couchSwapPrimaryToId(collection.schema.primaryPath, sendDoc);\n })\n };\n\n const response = await replicationState.fetch(\n url,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json'\n },\n body: JSON.stringify(body)\n }\n );\n const responseJson: CouchBulkDocResultRow[] = await response.json();\n\n const conflicts = responseJson.filter(row => {\n const isConflict = row.error === 'conflict';\n if (!row.ok && !isConflict) {\n throw newRxError('SNH', { args: { row } });\n }\n return isConflict;\n });\n\n if (conflicts.length === 0) {\n return [];\n }\n\n const getConflictDocsUrl = options.url + '_all_docs?' + mergeUrlQueryParams({\n include_docs: true,\n keys: JSON.stringify(conflicts.map(c => c.id))\n });\n const conflictResponse = await replicationState.fetch(getConflictDocsUrl);\n const conflictResponseJson: CouchAllDocsResponse = await conflictResponse.json();\n const conflictDocsMasterState: WithDeleted[] = conflictResponseJson.rows\n .map(r => couchDBDocToRxDocData(collection.schema.primaryPath, r.doc));\n\n return conflictDocsMasterState;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxCouchDBReplicationState(\n options.url,\n options.fetch ? options.fetch : getDefaultFetch(),\n COUCHDB_NEW_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.url),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n replicationState.start = () => {\n let since: string | number = 'now';\n const batchSize = options.pull && options.pull.batchSize ? options.pull.batchSize : 20;\n\n (async () => {\n while (!replicationState.isStopped()) {\n const url = options.url + '_changes?' + mergeUrlQueryParams({\n style: 'all_docs',\n feed: 'longpoll',\n since,\n include_docs: true,\n heartbeat: options.pull && options.pull.heartbeat ? options.pull.heartbeat : 60000,\n limit: batchSize,\n seq_interval: batchSize\n });\n\n let jsonResponse: CouchdbChangesResult;\n try {\n jsonResponse = await (await replicationState.fetch(url)).json();\n } catch (err: any) {\n pullStream$.error(newRxError('RC_STREAM', {\n args: { url },\n error: errorToPlainJson(err)\n }));\n // await next tick here otherwise we could go in to a 100% CPU blocking cycle.\n await collection.promiseWait(0);\n continue;\n }\n const documents: WithDeleted[] = jsonResponse.results\n .map(row => couchDBDocToRxDocData(collection.schema.primaryPath, ensureNotFalsy(row.doc)));\n since = jsonResponse.last_seq;\n\n pullStream$.next({\n documents,\n checkpoint: {\n sequence: jsonResponse.last_seq\n }\n });\n }\n })();\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA;AAOA;AAWA;AAIA;AAMA;AAMA;AAQA;EAAA;EAAA;EAAA;EAAA;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ER,SAAS;gBAChBS,YAAY,EAAET;cAClB,CAAC,CAAC;cAEEa,YAAkC;cAAA;cAAA;cAAA,OAENH,gBAAgB,CAAC/B,KAAK,CAACD,IAAG,CAAC;YAAA;cAAA;cAAA,sBAAEkC,IAAI;YAAA;cAA7DC,YAAY;cAAA;cAAA;YAAA;cAAA;cAAA;cAEZlB,WAAW,CAACkD,KAAK,CAAC,IAAAE,iBAAU,EAAC,WAAW,EAAE;gBACtCC,IAAI,EAAE;kBAAEtE,GAAG,EAAHA;gBAAI,CAAC;gBACbmE,KAAK,EAAE,IAAAoB,uBAAgB;cAC3B,CAAC,CAAC,CAAC;cACH;cAAA;cAAA,OACMpF,UAAU,CAACqF,WAAW,CAAC,CAAC,CAAC;YAAA;cAAA;YAAA;cAG7BpD,SAAmC,GAAGD,YAAY,CAACE,OAAO,CAC3DC,GAAG,CAAC,UAAAC,GAAG;gBAAA,OAAI,IAAAC,oCAAqB,EAACrC,UAAU,CAACsC,MAAM,CAACC,WAAW,EAAE,IAAAC,qBAAc,EAACJ,GAAG,CAACK,GAAG,CAAC,CAAC;cAAA,EAAC;cAC9FjB,KAAK,GAAGQ,YAAY,CAACW,QAAQ;cAE7B7B,WAAW,CAACwE,IAAI,CAAC;gBACbrD,SAAS,EAATA,SAAS;gBACTS,UAAU,EAAE;kBACRjB,QAAQ,EAAEO,YAAY,CAACW;gBAC3B;cACJ,CAAC,CAAC;cAAC;cAAA;YAAA;YAAA;cAAA;UAAA;QAAA;MAAA,CAEV,IAAG;MACJ,OAAOqC,WAAW,EAAE;IACxB,CAAC;EACL;EAEA,IAAAO,yCAA4B,EAAC/E,OAAO,CAACK,iBAAiB,EAAEgB,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-firestore/firestore-helper.js b/dist/lib/plugins/replication-firestore/firestore-helper.js index 3eb46eebdaa..2a35ea3ca70 100644 --- a/dist/lib/plugins/replication-firestore/firestore-helper.js +++ b/dist/lib/plugins/replication-firestore/firestore-helper.js @@ -11,15 +11,15 @@ exports.serverTimestampToIsoString = serverTimestampToIsoString; exports.stripPrimaryKey = stripPrimaryKey; exports.stripServerTimestampField = stripServerTimestampField; var _firestore = require("firebase/firestore"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-firestore-'; exports.FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX; function getFirestoreSortFieldValue(docData, primaryKey) { - var timeString = (0, _util.now)() + ''; + var timeString = (0, _utils.now)() + ''; return 'rxdb-' + timeString.padStart(15, '0') + '-' + docData[primaryKey]; } function stripServerTimestampField(serverTimestampField, docData) { - var data = (0, _util.flatClone)(docData); + var data = (0, _utils.flatClone)(docData); delete data[serverTimestampField]; return data; } @@ -38,7 +38,7 @@ function firestoreRowToDocData(serverTimestampField, primaryPath, row) { return docData; } function stripPrimaryKey(primaryPath, docData) { - docData = (0, _util.flatClone)(docData); + docData = (0, _utils.flatClone)(docData); delete docData[primaryPath]; return docData; } diff --git a/dist/lib/plugins/replication-firestore/firestore-helper.js.map b/dist/lib/plugins/replication-firestore/firestore-helper.js.map index c838ff91dc1..4785d0e19f5 100644 --- a/dist/lib/plugins/replication-firestore/firestore-helper.js.map +++ b/dist/lib/plugins/replication-firestore/firestore-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"firestore-helper.js","names":["FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","getFirestoreSortFieldValue","docData","primaryKey","timeString","now","padStart","stripServerTimestampField","serverTimestampField","data","flatClone","serverTimestampToIsoString","timestamp","date","toDate","toISOString","isoStringToServerTimestamp","isoString","Date","Timestamp","fromDate","firestoreRowToDocData","primaryPath","row","id","stripPrimaryKey"],"sources":["../../../../src/plugins/replication-firestore/firestore-helper.ts"],"sourcesContent":["import {\n QueryDocumentSnapshot,\n Timestamp\n} from 'firebase/firestore';\nimport type {\n WithDeleted\n} from '../../types';\nimport { flatClone, now } from '../../util';\n\nexport const FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-firestore-';\n\n\nexport function getFirestoreSortFieldValue(docData: any, primaryKey: string): string {\n const timeString = now() + '';\n return 'rxdb-' + timeString.padStart(15, '0') + '-' + docData[primaryKey];\n}\n\nexport function stripServerTimestampField(\n serverTimestampField: string,\n docData: RxDocType\n): WithDeleted {\n const data = flatClone(docData);\n delete (data as any)[serverTimestampField];\n return data as any;\n}\n\n\nexport function serverTimestampToIsoString(serverTimestampField: string, docData: any): string {\n const timestamp = (docData as any)[serverTimestampField];\n const date: Date = timestamp.toDate();\n return date.toISOString();\n}\n\nexport function isoStringToServerTimestamp(isoString: string): Timestamp {\n const date = new Date(isoString);\n return Timestamp.fromDate(date);\n}\n\nexport function firestoreRowToDocData(\n serverTimestampField: string,\n primaryPath: string,\n row: QueryDocumentSnapshot\n): WithDeleted {\n const docData = stripServerTimestampField(\n serverTimestampField,\n row.data()\n );\n (docData as any)[primaryPath] = row.id;\n return docData;\n}\n\nexport function stripPrimaryKey(\n primaryPath: string,\n docData: any\n): any {\n docData = flatClone(docData);\n delete (docData as any)[primaryPath];\n return docData;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAOA;AAEO,IAAMA,4CAA4C,GAAG,6BAA6B;AAAC;AAGnF,SAASC,0BAA0B,CAACC,OAAY,EAAEC,UAAkB,EAAU;EACjF,IAAMC,UAAU,GAAG,IAAAC,SAAG,GAAE,GAAG,EAAE;EAC7B,OAAO,OAAO,GAAGD,UAAU,CAACE,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,GAAG,GAAG,GAAGJ,OAAO,CAACC,UAAU,CAAC;AAC7E;AAEO,SAASI,yBAAyB,CACrCC,oBAA4B,EAC5BN,OAAkB,EACI;EACtB,IAAMO,IAAI,GAAG,IAAAC,eAAS,EAACR,OAAO,CAAC;EAC/B,OAAQO,IAAI,CAASD,oBAAoB,CAAC;EAC1C,OAAOC,IAAI;AACf;AAGO,SAASE,0BAA0B,CAACH,oBAA4B,EAAEN,OAAY,EAAU;EAC3F,IAAMU,SAAS,GAAIV,OAAO,CAASM,oBAAoB,CAAC;EACxD,IAAMK,IAAU,GAAGD,SAAS,CAACE,MAAM,EAAE;EACrC,OAAOD,IAAI,CAACE,WAAW,EAAE;AAC7B;AAEO,SAASC,0BAA0B,CAACC,SAAiB,EAAa;EACrE,IAAMJ,IAAI,GAAG,IAAIK,IAAI,CAACD,SAAS,CAAC;EAChC,OAAOE,oBAAS,CAACC,QAAQ,CAACP,IAAI,CAAC;AACnC;AAEO,SAASQ,qBAAqB,CACjCb,oBAA4B,EAC5Bc,WAAmB,EACnBC,GAAqC,EACf;EACtB,IAAMrB,OAAO,GAAGK,yBAAyB,CACrCC,oBAAoB,EACpBe,GAAG,CAACd,IAAI,EAAE,CACb;EACAP,OAAO,CAASoB,WAAW,CAAC,GAAGC,GAAG,CAACC,EAAE;EACtC,OAAOtB,OAAO;AAClB;AAEO,SAASuB,eAAe,CAC3BH,WAAmB,EACnBpB,OAAY,EACT;EACHA,OAAO,GAAG,IAAAQ,eAAS,EAACR,OAAO,CAAC;EAC5B,OAAQA,OAAO,CAASoB,WAAW,CAAC;EACpC,OAAOpB,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"firestore-helper.js","names":["FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","getFirestoreSortFieldValue","docData","primaryKey","timeString","now","padStart","stripServerTimestampField","serverTimestampField","data","flatClone","serverTimestampToIsoString","timestamp","date","toDate","toISOString","isoStringToServerTimestamp","isoString","Date","Timestamp","fromDate","firestoreRowToDocData","primaryPath","row","id","stripPrimaryKey"],"sources":["../../../../src/plugins/replication-firestore/firestore-helper.ts"],"sourcesContent":["import {\n QueryDocumentSnapshot,\n Timestamp\n} from 'firebase/firestore';\nimport type {\n WithDeleted\n} from '../../types';\nimport { flatClone, now } from '../../plugins/utils';\n\nexport const FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-firestore-';\n\n\nexport function getFirestoreSortFieldValue(docData: any, primaryKey: string): string {\n const timeString = now() + '';\n return 'rxdb-' + timeString.padStart(15, '0') + '-' + docData[primaryKey];\n}\n\nexport function stripServerTimestampField(\n serverTimestampField: string,\n docData: RxDocType\n): WithDeleted {\n const data = flatClone(docData);\n delete (data as any)[serverTimestampField];\n return data as any;\n}\n\n\nexport function serverTimestampToIsoString(serverTimestampField: string, docData: any): string {\n const timestamp = (docData as any)[serverTimestampField];\n const date: Date = timestamp.toDate();\n return date.toISOString();\n}\n\nexport function isoStringToServerTimestamp(isoString: string): Timestamp {\n const date = new Date(isoString);\n return Timestamp.fromDate(date);\n}\n\nexport function firestoreRowToDocData(\n serverTimestampField: string,\n primaryPath: string,\n row: QueryDocumentSnapshot\n): WithDeleted {\n const docData = stripServerTimestampField(\n serverTimestampField,\n row.data()\n );\n (docData as any)[primaryPath] = row.id;\n return docData;\n}\n\nexport function stripPrimaryKey(\n primaryPath: string,\n docData: any\n): any {\n docData = flatClone(docData);\n delete (docData as any)[primaryPath];\n return docData;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAOA;AAEO,IAAMA,4CAA4C,GAAG,6BAA6B;AAAC;AAGnF,SAASC,0BAA0B,CAACC,OAAY,EAAEC,UAAkB,EAAU;EACjF,IAAMC,UAAU,GAAG,IAAAC,UAAG,GAAE,GAAG,EAAE;EAC7B,OAAO,OAAO,GAAGD,UAAU,CAACE,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,GAAG,GAAG,GAAGJ,OAAO,CAACC,UAAU,CAAC;AAC7E;AAEO,SAASI,yBAAyB,CACrCC,oBAA4B,EAC5BN,OAAkB,EACI;EACtB,IAAMO,IAAI,GAAG,IAAAC,gBAAS,EAACR,OAAO,CAAC;EAC/B,OAAQO,IAAI,CAASD,oBAAoB,CAAC;EAC1C,OAAOC,IAAI;AACf;AAGO,SAASE,0BAA0B,CAACH,oBAA4B,EAAEN,OAAY,EAAU;EAC3F,IAAMU,SAAS,GAAIV,OAAO,CAASM,oBAAoB,CAAC;EACxD,IAAMK,IAAU,GAAGD,SAAS,CAACE,MAAM,EAAE;EACrC,OAAOD,IAAI,CAACE,WAAW,EAAE;AAC7B;AAEO,SAASC,0BAA0B,CAACC,SAAiB,EAAa;EACrE,IAAMJ,IAAI,GAAG,IAAIK,IAAI,CAACD,SAAS,CAAC;EAChC,OAAOE,oBAAS,CAACC,QAAQ,CAACP,IAAI,CAAC;AACnC;AAEO,SAASQ,qBAAqB,CACjCb,oBAA4B,EAC5Bc,WAAmB,EACnBC,GAAqC,EACf;EACtB,IAAMrB,OAAO,GAAGK,yBAAyB,CACrCC,oBAAoB,EACpBe,GAAG,CAACd,IAAI,EAAE,CACb;EACAP,OAAO,CAASoB,WAAW,CAAC,GAAGC,GAAG,CAACC,EAAE;EACtC,OAAOtB,OAAO;AAClB;AAEO,SAASuB,eAAe,CAC3BH,WAAmB,EACnBpB,OAAY,EACT;EACHA,OAAO,GAAG,IAAAQ,gBAAS,EAACR,OAAO,CAAC;EAC5B,OAAQA,OAAO,CAASoB,WAAW,CAAC;EACpC,OAAOpB,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-firestore/firestore-types.js.map b/dist/lib/plugins/replication-firestore/firestore-types.js.map index 9660465da16..53c6362ddd6 100644 --- a/dist/lib/plugins/replication-firestore/firestore-types.js.map +++ b/dist/lib/plugins/replication-firestore/firestore-types.js.map @@ -1 +1 @@ -{"version":3,"file":"firestore-types.js","names":[],"sources":["../../../../src/plugins/replication-firestore/firestore-types.ts"],"sourcesContent":["import {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nimport {\n CollectionReference,\n Firestore\n} from 'firebase/firestore';\n\nexport type FirestoreCheckpointType = {\n id: string;\n /**\n * Firestore internally sets the time to an object like\n * {\n * \"seconds\": 1669807105,\n * \"nanoseconds\": 476000000\n * }\n * But to be able to query that, we have to use a date string\n * like '2022-11-30T11:18:25.141Z'\n * so we store that string instead.\n */\n serverTimestamp: string;\n};\nexport type FirestoreCollection = CollectionReference;\n\nexport type FirestoreOptions = {\n projectId: string;\n collection: FirestoreCollection;\n database: Firestore;\n};\n\nexport type SyncOptionsFirestore = Omit<\n ReplicationOptions,\n 'pull' | 'push' | 'replicationIdentifier' | 'collection'\n> & {\n firestore: FirestoreOptions;\n /**\n * In firestore it is not possible to read out\n * the internally used write timestamp.\n * Even if we could read it out, it is not indexed which\n * is required for fetch 'changes-since-x'.\n * So instead we have to rely on a custom user defined field\n * that contains the server time which is set by firestore via serverTimestamp()\n * IMPORTANT: The serverTimestampField MUST NOT be part of the collections RxJsonSchema!\n * [default='serverTimestamp']\n * @link https://groups.google.com/g/firebase-talk/c/tAmPzPei-mE\n */\n serverTimestampField?: string;\n pull?: Omit, 'handler' | 'stream$'>;\n push?: Omit, 'handler'>;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"firestore-types.js","names":[],"sources":["../../../../src/plugins/replication-firestore/firestore-types.ts"],"sourcesContent":["import {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions\n} from '../../types';\n\nimport {\n CollectionReference,\n Firestore\n} from 'firebase/firestore';\n\nexport type FirestoreCheckpointType = {\n id: string;\n /**\n * Firestore internally sets the time to an object like\n * {\n * \"seconds\": 1669807105,\n * \"nanoseconds\": 476000000\n * }\n * But to be able to query that, we have to use a date string\n * like '2022-11-30T11:18:25.141Z'\n * so we store that string instead.\n */\n serverTimestamp: string;\n};\nexport type FirestoreCollection = CollectionReference;\n\nexport type FirestoreOptions = {\n projectId: string;\n collection: FirestoreCollection;\n database: Firestore;\n};\n\nexport type SyncOptionsFirestore = Omit<\n ReplicationOptions,\n 'pull' | 'push' | 'replicationIdentifier'\n> & {\n firestore: FirestoreOptions;\n /**\n * In firestore it is not possible to read out\n * the internally used write timestamp.\n * Even if we could read it out, it is not indexed which\n * is required for fetch 'changes-since-x'.\n * So instead we have to rely on a custom user defined field\n * that contains the server time which is set by firestore via serverTimestamp()\n * IMPORTANT: The serverTimestampField MUST NOT be part of the collections RxJsonSchema!\n * [default='serverTimestamp']\n * @link https://groups.google.com/g/firebase-talk/c/tAmPzPei-mE\n */\n serverTimestampField?: string;\n pull?: Omit, 'handler' | 'stream$'>;\n push?: Omit, 'handler'>;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/replication-firestore/index.js b/dist/lib/plugins/replication-firestore/index.js index 49b12287297..4f191d5cbb5 100644 --- a/dist/lib/plugins/replication-firestore/index.js +++ b/dist/lib/plugins/replication-firestore/index.js @@ -6,13 +6,14 @@ Object.defineProperty(exports, "__esModule", { }); var _exportNames = { RxFirestoreReplicationState: true, - syncFirestore: true, - RxDBReplicationFirestorePlugin: true + replicateFirestore: true }; -exports.RxFirestoreReplicationState = exports.RxDBReplicationFirestorePlugin = void 0; -exports.syncFirestore = syncFirestore; +exports.RxFirestoreReplicationState = void 0; +exports.replicateFirestore = replicateFirestore; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _firestore = require("firebase/firestore"); var _leaderElection = require("../leader-election"); var _replication = require("../replication"); @@ -42,159 +43,6 @@ Object.keys(_firestoreTypes).forEach(function (key) { } }); }); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -/** - * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb - * you can use it to sync collections with a remote CouchDB endpoint. - */ var RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationState) { (0, _inheritsLoose2["default"])(RxFirestoreReplicationState, _RxReplicationState); function RxFirestoreReplicationState(firestore, replicationIdentifierHash, collection, pull, push) { @@ -216,8 +64,9 @@ var RxFirestoreReplicationState = /*#__PURE__*/function (_RxReplicationState) { return RxFirestoreReplicationState; }(_replication.RxReplicationState); exports.RxFirestoreReplicationState = RxFirestoreReplicationState; -function syncFirestore(options) { - var collection = this; +function replicateFirestore(options) { + var collection = options.collection; + (0, _.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); var pullStream$ = new _rxjs.Subject(); var replicationPrimitivesPull; options.live = typeof options.live === 'undefined' ? true : options.live; @@ -229,199 +78,275 @@ function syncFirestore(options) { /** * The serverTimestampField MUST NOT be part of the collections RxJsonSchema. */ - var schemaPart = (0, _.getSchemaByObjectPath)(this.schema.jsonSchema, serverTimestampField); + var schemaPart = (0, _.getSchemaByObjectPath)(collection.schema.jsonSchema, serverTimestampField); if (schemaPart || // also must not be nested. serverTimestampField.includes('.')) { throw (0, _.newRxError)('RC6', { field: serverTimestampField, - schema: this.schema.jsonSchema + schema: collection.schema.jsonSchema }); } if (options.pull) { replicationPrimitivesPull = { - handler: function handler(lastPulledCheckpoint, batchSize) { - try { - var _temp2 = function _temp2() { - if (useDocs.length === 0) { - return { - checkpoint: lastPulledCheckpoint, - documents: [] - }; - } - var lastDoc = (0, _util.ensureNotFalsy)((0, _util.lastOfArray)(useDocs)); - var documents = useDocs.map(function (row) { - return (0, _firestoreHelper.firestoreRowToDocData)(serverTimestampField, primaryPath, row); - }); - var newCheckpoint = { - id: lastDoc.id, - serverTimestamp: (0, _firestoreHelper.serverTimestampToIsoString)(serverTimestampField, lastDoc.data()) - }; - var ret = { - documents: documents, - checkpoint: newCheckpoint - }; - return ret; - }; - var newerQuery; - var sameTimeQuery; - if (lastPulledCheckpoint) { - var lastServerTimestamp = (0, _firestoreHelper.isoStringToServerTimestamp)(lastPulledCheckpoint.serverTimestamp); - newerQuery = (0, _firestore.query)(options.firestore.collection, (0, _firestore.where)(serverTimestampField, '>', lastServerTimestamp), (0, _firestore.orderBy)(serverTimestampField, 'asc'), (0, _firestore.limit)(batchSize)); - sameTimeQuery = (0, _firestore.query)(options.firestore.collection, (0, _firestore.where)(serverTimestampField, '==', lastServerTimestamp), (0, _firestore.where)(primaryPath, '>', lastPulledCheckpoint.id), (0, _firestore.orderBy)(primaryPath, 'asc'), (0, _firestore.orderBy)(serverTimestampField, 'asc'), (0, _firestore.limit)(batchSize)); - } else { - newerQuery = (0, _firestore.query)(options.firestore.collection, (0, _firestore.orderBy)(serverTimestampField, 'asc'), (0, _firestore.limit)(batchSize)); - } - var mustsReRun = true; - var useDocs = []; - var _temp = _for(function () { - return !!mustsReRun; - }, void 0, function () { - /** - * Local writes that have not been persisted to the server - * are in pending state and do not have a correct serverTimestamp set. - * We have to ensure we only use document states that are in sync with the server. - * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b - */ - return Promise.resolve((0, _firestore.waitForPendingWrites)(options.firestore.database)).then(function () { - return Promise.resolve((0, _firestore.runTransaction)(options.firestore.database, function (_tx) { - try { - useDocs = []; - return Promise.resolve(Promise.all([(0, _firestore.getDocs)(newerQuery), sameTimeQuery ? (0, _firestore.getDocs)(sameTimeQuery) : undefined])).then(function (_ref) { - var newerQueryResult = _ref[0], - sameTimeQueryResult = _ref[1]; - if (newerQueryResult.metadata.hasPendingWrites || sameTimeQuery && (0, _util.ensureNotFalsy)(sameTimeQueryResult).metadata.hasPendingWrites) {} else { - mustsReRun = false; - if (sameTimeQuery) { - useDocs = (0, _util.ensureNotFalsy)(sameTimeQueryResult).docs; - } - var missingAmount = batchSize - useDocs.length; - if (missingAmount > 0) { - var additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(function (x) { - return !!x; - }); - useDocs = useDocs.concat(additonalDocs); + handler: function () { + var _handler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(lastPulledCheckpoint, batchSize) { + var newerQuery, sameTimeQuery, lastServerTimestamp, mustsReRun, useDocs, lastDoc, documents, newCheckpoint, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (lastPulledCheckpoint) { + lastServerTimestamp = (0, _firestoreHelper.isoStringToServerTimestamp)(lastPulledCheckpoint.serverTimestamp); + newerQuery = (0, _firestore.query)(options.firestore.collection, (0, _firestore.where)(serverTimestampField, '>', lastServerTimestamp), (0, _firestore.orderBy)(serverTimestampField, 'asc'), (0, _firestore.limit)(batchSize)); + sameTimeQuery = (0, _firestore.query)(options.firestore.collection, (0, _firestore.where)(serverTimestampField, '==', lastServerTimestamp), (0, _firestore.where)(primaryPath, '>', lastPulledCheckpoint.id), (0, _firestore.orderBy)(primaryPath, 'asc'), (0, _firestore.orderBy)(serverTimestampField, 'asc'), (0, _firestore.limit)(batchSize)); + } else { + newerQuery = (0, _firestore.query)(options.firestore.collection, (0, _firestore.orderBy)(serverTimestampField, 'asc'), (0, _firestore.limit)(batchSize)); + } + mustsReRun = true; + useDocs = []; + case 3: + if (!mustsReRun) { + _context2.next = 10; + break; + } + _context2.next = 6; + return (0, _firestore.waitForPendingWrites)(options.firestore.database); + case 6: + _context2.next = 8; + return (0, _firestore.runTransaction)(options.firestore.database, /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_tx) { + var _yield$Promise$all, newerQueryResult, sameTimeQueryResult, missingAmount, additonalDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + useDocs = []; + _context.next = 3; + return Promise.all([(0, _firestore.getDocs)(newerQuery), sameTimeQuery ? (0, _firestore.getDocs)(sameTimeQuery) : undefined]); + case 3: + _yield$Promise$all = _context.sent; + newerQueryResult = _yield$Promise$all[0]; + sameTimeQueryResult = _yield$Promise$all[1]; + if (!(newerQueryResult.metadata.hasPendingWrites || sameTimeQuery && (0, _utils.ensureNotFalsy)(sameTimeQueryResult).metadata.hasPendingWrites)) { + _context.next = 10; + break; + } + return _context.abrupt("return"); + case 10: + mustsReRun = false; + if (sameTimeQuery) { + useDocs = (0, _utils.ensureNotFalsy)(sameTimeQueryResult).docs; + } + missingAmount = batchSize - useDocs.length; + if (missingAmount > 0) { + additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(function (x) { + return !!x; + }); + useDocs = useDocs.concat(additonalDocs); + } + case 14: + case "end": + return _context.stop(); } - } - }); - } catch (e) { - return Promise.reject(e); + }, _callee); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + case 8: + _context2.next = 3; + break; + case 10: + if (!(useDocs.length === 0)) { + _context2.next = 12; + break; } - })).then(function () {}); - }); - }); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); + return _context2.abrupt("return", { + checkpoint: lastPulledCheckpoint, + documents: [] + }); + case 12: + lastDoc = (0, _utils.ensureNotFalsy)((0, _utils.lastOfArray)(useDocs)); + documents = useDocs.map(function (row) { + return (0, _firestoreHelper.firestoreRowToDocData)(serverTimestampField, primaryPath, row); + }); + newCheckpoint = { + id: lastDoc.id, + serverTimestamp: (0, _firestoreHelper.serverTimestampToIsoString)(serverTimestampField, lastDoc.data()) + }; + ret = { + documents: documents, + checkpoint: newCheckpoint + }; + return _context2.abrupt("return", ret); + case 17: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x, _x2) { + return _handler.apply(this, arguments); } - }, - batchSize: (0, _util.ensureNotFalsy)(options.pull).batchSize, - modifier: (0, _util.ensureNotFalsy)(options.pull).modifier, + return handler; + }(), + batchSize: (0, _utils.ensureNotFalsy)(options.pull).batchSize, + modifier: (0, _utils.ensureNotFalsy)(options.pull).modifier, stream$: pullStream$.asObservable() }; } var replicationPrimitivesPush; if (options.push) { replicationPrimitivesPush = { - handler: function handler(rows) { - try { - var writeRowsById = {}; - var docIds = rows.map(function (row) { - var docId = row.newDocumentState[primaryPath]; - writeRowsById[docId] = row; - return docId; - }); - return Promise.resolve((0, _firestore.waitForPendingWrites)(options.firestore.database)).then(function () { - var conflicts = []; - - /** - * Everything must run INSIDE of the transaction - * because on tx-errors, firebase will re-run the transaction on some cases. - * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure - * @link https://firebase.google.com/docs/firestore/manage-data/transactions - */ - return Promise.resolve((0, _firestore.runTransaction)(options.firestore.database, function (_tx) { - try { - conflicts = []; // reset in case the tx has re-run. + handler: function () { + var _handler2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(rows) { + var writeRowsById, docIds, conflicts; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + writeRowsById = {}; + docIds = rows.map(function (row) { + var docId = row.newDocumentState[primaryPath]; + writeRowsById[docId] = row; + return docId; + }); + _context5.next = 4; + return (0, _firestore.waitForPendingWrites)(options.firestore.database); + case 4: + conflicts = []; /** - * @link https://stackoverflow.com/a/48423626/3443137 + * Everything must run INSIDE of the transaction + * because on tx-errors, firebase will re-run the transaction on some cases. + * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure + * @link https://firebase.google.com/docs/firestore/manage-data/transactions */ - return Promise.resolve((0, _firestore.getDocs)((0, _firestore.query)(options.firestore.collection, (0, _firestore.where)((0, _firestore.documentId)(), 'in', docIds)))).then(function (docsInDbResult) { - var docsInDbById = {}; - docsInDbResult.docs.forEach(function (row) { - var docDataInDb = (0, _firestoreHelper.stripServerTimestampField)(serverTimestampField, row.data()); - var docId = row.id; - docDataInDb[primaryPath] = docId; - docsInDbById[docId] = docDataInDb; - }); + _context5.next = 7; + return (0, _firestore.runTransaction)(options.firestore.database, /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_tx) { + var docsInDbResult, docsInDbById, batch, hasWrite; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + conflicts = []; // reset in case the tx has re-run. + /** + * @link https://stackoverflow.com/a/48423626/3443137 + */ + _context4.next = 3; + return (0, _firestore.getDocs)((0, _firestore.query)(options.firestore.collection, (0, _firestore.where)((0, _firestore.documentId)(), 'in', docIds))); + case 3: + docsInDbResult = _context4.sent; + docsInDbById = {}; + docsInDbResult.docs.forEach(function (row) { + var docDataInDb = (0, _firestoreHelper.stripServerTimestampField)(serverTimestampField, row.data()); + var docId = row.id; + docDataInDb[primaryPath] = docId; + docsInDbById[docId] = docDataInDb; + }); - /** - * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes - */ - var batch = (0, _firestore.writeBatch)(options.firestore.database); - var hasWrite = false; - return Promise.resolve(Promise.all(Object.entries(writeRowsById).map(function (_ref2) { - try { - var _temp4 = function _temp4(_collection$conflictH) { - if (docInDb && (_writeRow$assumedMast || _collection$conflictH.isEqual === false)) { - // conflict - conflicts.push(docInDb); - } else { - // no conflict - hasWrite = true; - var docRef = (0, _firestore.doc)(options.firestore.collection, docId); - var writeDocData = (0, _util.flatClone)(writeRow.newDocumentState); - writeDocData[serverTimestampField] = (0, _firestore.serverTimestamp)(); - if (!docInDb) { - // insert - batch.set(docRef, (0, _firestoreHelper.stripPrimaryKey)(primaryPath, writeDocData)); - } else { - // update - batch.update(docRef, (0, _firestoreHelper.stripPrimaryKey)(primaryPath, writeDocData)); + /** + * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes + */ + batch = (0, _firestore.writeBatch)(options.firestore.database); + hasWrite = false; + _context4.next = 10; + return Promise.all(Object.entries(writeRowsById).map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(_ref3) { + var docId, writeRow, docInDb, docRef, writeDocData; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + docId = _ref3[0], writeRow = _ref3[1]; + docInDb = docsInDbById[docId]; + _context3.t0 = docInDb; + if (!_context3.t0) { + _context3.next = 11; + break; + } + _context3.t1 = !writeRow.assumedMasterState; + if (_context3.t1) { + _context3.next = 10; + break; + } + _context3.next = 8; + return collection.conflictHandler({ + newDocumentState: docInDb, + realMasterState: writeRow.assumedMasterState + }, 'replication-firestore-push'); + case 8: + _context3.t2 = _context3.sent.isEqual; + _context3.t1 = _context3.t2 === false; + case 10: + _context3.t0 = _context3.t1; + case 11: + if (!_context3.t0) { + _context3.next = 15; + break; + } + // conflict + conflicts.push(docInDb); + _context3.next = 20; + break; + case 15: + // no conflict + hasWrite = true; + docRef = (0, _firestore.doc)(options.firestore.collection, docId); + writeDocData = (0, _utils.flatClone)(writeRow.newDocumentState); + writeDocData[serverTimestampField] = (0, _firestore.serverTimestamp)(); + if (!docInDb) { + // insert + batch.set(docRef, (0, _firestoreHelper.stripPrimaryKey)(primaryPath, writeDocData)); + } else { + // update + batch.update(docRef, (0, _firestoreHelper.stripPrimaryKey)(primaryPath, writeDocData)); + } + case 20: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x6) { + return _ref4.apply(this, arguments); + }; + }())); + case 10: + if (!hasWrite) { + _context4.next = 13; + break; } - } - }; - var docId = _ref2[0], - writeRow = _ref2[1]; - var docInDb = docsInDbById[docId]; - var _writeRow$assumedMast = !writeRow.assumedMasterState; - return Promise.resolve(!docInDb || _writeRow$assumedMast ? _temp4(docInDb && (_writeRow$assumedMast || collection.conflictHandler({ - newDocumentState: docInDb, - realMasterState: writeRow.assumedMasterState - }, 'replication-firestore-push'))) : Promise.resolve(docInDb && (_writeRow$assumedMast || collection.conflictHandler({ - newDocumentState: docInDb, - realMasterState: writeRow.assumedMasterState - }, 'replication-firestore-push'))).then(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp3 = function () { - if (hasWrite) { - return Promise.resolve(batch.commit()).then(function () {}); + _context4.next = 13; + return batch.commit(); + case 13: + case "end": + return _context4.stop(); } - }(); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })).then(function () { - return Promise.resolve((0, _firestore.waitForPendingWrites)(options.firestore.database)).then(function () { - return conflicts; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + }, _callee4); + })); + return function (_x5) { + return _ref2.apply(this, arguments); + }; + }()); + case 7: + _context5.next = 9; + return (0, _firestore.waitForPendingWrites)(options.firestore.database); + case 9: + return _context5.abrupt("return", conflicts); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + function handler(_x4) { + return _handler2.apply(this, arguments); } - }, + return handler; + }(), batchSize: options.push.batchSize, modifier: options.push.modifier }; } - var replicationState = new RxFirestoreReplicationState(options.firestore, _firestoreHelper.FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX + (0, _util.fastUnsecureHash)(options.firestore.projectId), collection, replicationPrimitivesPull, replicationPrimitivesPush, options.live, options.retryTime, options.autoStart); + var replicationState = new RxFirestoreReplicationState(options.firestore, _firestoreHelper.FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX + (0, _utils.fastUnsecureHash)(options.firestore.projectId), collection, replicationPrimitivesPull, replicationPrimitivesPush, options.live, options.retryTime, options.autoStart); /** * Use long polling to get live changes for the pull.stream$ @@ -440,7 +365,7 @@ function syncFirestore(options) { replicationState.reSync(); }, function (error) { replicationState.subjects.error.next((0, _.newRxError)('RC_STREAM', { - error: error + error: (0, _utils.errorToPlainJson)(error) })); }); replicationState.cancel = function () { @@ -453,17 +378,4 @@ function syncFirestore(options) { (0, _replication.startReplicationOnLeaderShip)(options.waitForLeadership, replicationState); return replicationState; } -var RxDBReplicationFirestorePlugin = { - name: 'replication-firestore', - init: function init() { - (0, _.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncFirestore = syncFirestore; - } - } -}; -exports.RxDBReplicationFirestorePlugin = RxDBReplicationFirestorePlugin; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-firestore/index.js.map b/dist/lib/plugins/replication-firestore/index.js.map index bb5c93e96ee..c9ba512700e 100644 --- a/dist/lib/plugins/replication-firestore/index.js.map +++ b/dist/lib/plugins/replication-firestore/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","RxFirestoreReplicationState","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","RxReplicationState","syncFirestore","options","pullStream$","Subject","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","getSchemaByObjectPath","jsonSchema","includes","newRxError","field","handler","lastPulledCheckpoint","batchSize","useDocs","length","checkpoint","documents","lastDoc","ensureNotFalsy","lastOfArray","map","row","firestoreRowToDocData","newCheckpoint","id","serverTimestamp","serverTimestampToIsoString","data","ret","newerQuery","sameTimeQuery","lastServerTimestamp","isoStringToServerTimestamp","query","where","orderBy","limit","mustsReRun","waitForPendingWrites","database","runTransaction","_tx","Promise","all","getDocs","undefined","newerQueryResult","sameTimeQueryResult","metadata","hasPendingWrites","docs","missingAmount","additonalDocs","slice","filter","x","concat","modifier","stream$","asObservable","replicationPrimitivesPush","rows","writeRowsById","docIds","docId","newDocumentState","conflicts","documentId","docsInDbResult","docsInDbById","forEach","docDataInDb","stripServerTimestampField","batch","writeBatch","hasWrite","Object","entries","docInDb","isEqual","docRef","doc","writeDocData","flatClone","writeRow","set","stripPrimaryKey","assumedMasterState","conflictHandler","realMasterState","commit","replicationState","FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","fastUnsecureHash","projectId","startBefore","start","cancelBefore","cancel","lastChangeQuery","unsubscribe","onSnapshot","_querySnapshot","reSync","error","subjects","next","startReplicationOnLeaderShip","RxDBReplicationFirestorePlugin","name","init","addRxPlugin","RxDBLeaderElectionPlugin","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncCouchDBNew()-function to rxdb\n * you can use it to sync collections with a remote CouchDB endpoint.\n */\nimport {\n ensureNotFalsy,\n fastUnsecureHash,\n flatClone,\n lastOfArray\n} from '../../util';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n RxPlugin,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper';\n\nexport * from './firestore-helper';\nexport * from './firestore-types';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function syncFirestore(\n this: RxCollection,\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = this;\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(this.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: this.schema.jsonSchema\n });\n }\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(options.firestore.collection,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(options.firestore.collection,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(options.firestore.collection,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n useDocs = useDocs.concat(additonalDocs as any);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n const docsInDbResult = await getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', docIds)\n )\n );\n const docsInDbById: ById = {};\n docsInDbResult.docs.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.firestore.projectId),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n options.firestore.collection,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n\nexport const RxDBReplicationFirestorePlugin: RxPlugin = {\n name: 'replication-firestore',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncFirestore = syncFirestore;\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAIA;AAOA;AAgBA;AASA;AAIA;AAaA;AACA;AASA;EAAA;EAAA;EAAA;EAAA;IAAA;IA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AoB,EAAE,MAAM,CAAC,EACrC,IAAAmC,gBAAK,EAAC,CAAC,CAAC,CACX;MACD,IAAMgE,WAAW,GAAG,IAAAC,qBAAU,EAC1BF,eAAe,EACf,UAACG,cAAc,EAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBX,gBAAgB,CAACY,MAAM,EAAE;MAC7B,CAAC,EACD,UAACC,KAAK,EAAK;QACPb,gBAAgB,CAACc,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChC,IAAAlG,YAAU,EAAC,WAAW,EAAE;UAAEgG,KAAK,EAALA;QAAM,CAAC,CAAC,CACrC;MACL,CAAC,CACJ;MACDb,gBAAgB,CAACO,MAAM,GAAG,YAAM;QAC5BE,WAAW,EAAE;QACb,OAAOH,YAAY,EAAE;MACzB,CAAC;MACD,OAAOF,WAAW,EAAE;IACxB,CAAC;EACL;EAEA,IAAAY,yCAA4B,EAAC/G,OAAO,CAACI,iBAAiB,EAAE2F,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B;AAEO,IAAMiB,8BAAwC,GAAG;EACpDC,IAAI,EAAE,uBAAuB;EAC7BC,IAAI,kBAAG;IACH,IAAAC,aAAW,EAACC,wCAAwB,CAAC;EACzC,CAAC;EACDC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAACzH,aAAa,GAAGA,aAAa;IACvC;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["RxFirestoreReplicationState","firestore","replicationIdentifierHash","collection","pull","push","live","retryTime","autoStart","RxReplicationState","replicateFirestore","options","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","Subject","replicationPrimitivesPull","waitForLeadership","serverTimestampField","primaryPath","schema","schemaPart","getSchemaByObjectPath","jsonSchema","includes","newRxError","field","handler","lastPulledCheckpoint","batchSize","lastServerTimestamp","isoStringToServerTimestamp","serverTimestamp","newerQuery","query","where","orderBy","limit","sameTimeQuery","id","mustsReRun","useDocs","waitForPendingWrites","database","runTransaction","_tx","Promise","all","getDocs","undefined","newerQueryResult","sameTimeQueryResult","metadata","hasPendingWrites","ensureNotFalsy","docs","missingAmount","length","additonalDocs","slice","filter","x","concat","checkpoint","documents","lastDoc","lastOfArray","map","row","firestoreRowToDocData","newCheckpoint","serverTimestampToIsoString","data","ret","modifier","stream$","asObservable","replicationPrimitivesPush","rows","writeRowsById","docIds","docId","newDocumentState","conflicts","documentId","docsInDbResult","docsInDbById","forEach","docDataInDb","stripServerTimestampField","batch","writeBatch","hasWrite","Object","entries","writeRow","docInDb","assumedMasterState","conflictHandler","realMasterState","isEqual","docRef","doc","writeDocData","flatClone","set","stripPrimaryKey","update","commit","replicationState","FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX","fastUnsecureHash","projectId","startBefore","start","bind","cancelBefore","cancel","lastChangeQuery","unsubscribe","onSnapshot","_querySnapshot","reSync","error","subjects","next","errorToPlainJson","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-firestore/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n errorToPlainJson,\n fastUnsecureHash,\n flatClone,\n lastOfArray\n} from '../../plugins/utils';\n\nimport {\n doc,\n query,\n where,\n orderBy,\n limit,\n getDocs,\n onSnapshot,\n runTransaction,\n writeBatch,\n serverTimestamp,\n QueryDocumentSnapshot,\n waitForPendingWrites,\n documentId\n} from 'firebase/firestore';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n RxReplicationPullStreamItem\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n ById,\n getSchemaByObjectPath,\n newRxError,\n WithDeleted\n} from '../../';\n\nimport type {\n FirestoreCheckpointType,\n FirestoreOptions,\n SyncOptionsFirestore\n} from './firestore-types';\nimport { Subject } from 'rxjs';\nimport {\n firestoreRowToDocData,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX,\n isoStringToServerTimestamp,\n serverTimestampToIsoString,\n stripPrimaryKey,\n stripServerTimestampField\n} from './firestore-helper';\n\nexport * from './firestore-helper';\nexport * from './firestore-types';\n\nexport class RxFirestoreReplicationState extends RxReplicationState {\n constructor(\n public readonly firestore: FirestoreOptions,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true\n ) {\n super(\n replicationIdentifierHash,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n}\n\nexport function replicateFirestore(\n options: SyncOptionsFirestore\n): RxFirestoreReplicationState {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n const pullStream$: Subject> = new Subject();\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const serverTimestampField = typeof options.serverTimestampField === 'undefined' ? 'serverTimestamp' : options.serverTimestampField;\n options.serverTimestampField = serverTimestampField;\n const primaryPath = collection.schema.primaryPath;\n\n /**\n * The serverTimestampField MUST NOT be part of the collections RxJsonSchema.\n */\n const schemaPart = getSchemaByObjectPath(collection.schema.jsonSchema, serverTimestampField);\n if (\n schemaPart ||\n // also must not be nested.\n serverTimestampField.includes('.')\n ) {\n throw newRxError('RC6', {\n field: serverTimestampField,\n schema: collection.schema.jsonSchema\n });\n }\n\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: FirestoreCheckpointType,\n batchSize: number\n ) {\n let newerQuery: ReturnType;\n let sameTimeQuery: ReturnType | undefined;\n\n if (lastPulledCheckpoint) {\n const lastServerTimestamp = isoStringToServerTimestamp(lastPulledCheckpoint.serverTimestamp);\n newerQuery = query(options.firestore.collection,\n where(serverTimestampField, '>', lastServerTimestamp),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n sameTimeQuery = query(options.firestore.collection,\n where(serverTimestampField, '==', lastServerTimestamp),\n where(primaryPath, '>', lastPulledCheckpoint.id),\n orderBy(primaryPath, 'asc'),\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n } else {\n newerQuery = query(options.firestore.collection,\n orderBy(serverTimestampField, 'asc'),\n limit(batchSize)\n );\n }\n\n let mustsReRun = true;\n let useDocs: QueryDocumentSnapshot[] = [];\n while (mustsReRun) {\n /**\n * Local writes that have not been persisted to the server\n * are in pending state and do not have a correct serverTimestamp set.\n * We have to ensure we only use document states that are in sync with the server.\n * @link https://medium.com/firebase-developers/the-secrets-of-firestore-fieldvalue-servertimestamp-revealed-29dd7a38a82b\n */\n await waitForPendingWrites(options.firestore.database);\n await runTransaction(options.firestore.database, async (_tx) => {\n useDocs = [];\n const [\n newerQueryResult,\n sameTimeQueryResult\n ] = await Promise.all([\n getDocs(newerQuery),\n sameTimeQuery ? getDocs(sameTimeQuery) : undefined\n ]);\n\n if (\n newerQueryResult.metadata.hasPendingWrites ||\n (sameTimeQuery && ensureNotFalsy(sameTimeQueryResult).metadata.hasPendingWrites)\n ) {\n return;\n } else {\n mustsReRun = false;\n\n if (sameTimeQuery) {\n useDocs = ensureNotFalsy(sameTimeQueryResult).docs as any;\n }\n const missingAmount = batchSize - useDocs.length;\n if (missingAmount > 0) {\n const additonalDocs = newerQueryResult.docs.slice(0, missingAmount).filter(x => !!x);\n useDocs = useDocs.concat(additonalDocs as any);\n }\n }\n });\n }\n\n if (useDocs.length === 0) {\n return {\n checkpoint: lastPulledCheckpoint,\n documents: []\n };\n }\n const lastDoc = ensureNotFalsy(lastOfArray(useDocs));\n const documents: WithDeleted[] = useDocs\n .map(row => firestoreRowToDocData(\n serverTimestampField,\n primaryPath,\n row\n ));\n const newCheckpoint: FirestoreCheckpointType = {\n id: lastDoc.id,\n serverTimestamp: serverTimestampToIsoString(serverTimestampField, lastDoc.data())\n };\n const ret = {\n documents: documents,\n checkpoint: newCheckpoint\n };\n return ret;\n },\n batchSize: ensureNotFalsy(options.pull).batchSize,\n modifier: ensureNotFalsy(options.pull).modifier,\n stream$: pullStream$.asObservable()\n };\n }\n\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const writeRowsById: ById> = {};\n const docIds: string[] = rows.map(row => {\n const docId = (row.newDocumentState as any)[primaryPath];\n writeRowsById[docId] = row;\n return docId;\n });\n await waitForPendingWrites(options.firestore.database);\n let conflicts: WithDeleted[] = [];\n\n /**\n * Everything must run INSIDE of the transaction\n * because on tx-errors, firebase will re-run the transaction on some cases.\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions\n */\n await runTransaction(options.firestore.database, async (_tx) => {\n conflicts = []; // reset in case the tx has re-run.\n /**\n * @link https://stackoverflow.com/a/48423626/3443137\n */\n const docsInDbResult = await getDocs(\n query(\n options.firestore.collection,\n where(documentId(), 'in', docIds)\n )\n );\n const docsInDbById: ById = {};\n docsInDbResult.docs.forEach(row => {\n const docDataInDb = stripServerTimestampField(serverTimestampField, row.data());\n const docId = row.id;\n (docDataInDb as any)[primaryPath] = docId;\n docsInDbById[docId] = docDataInDb;\n });\n\n /**\n * @link https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes\n */\n const batch = writeBatch(options.firestore.database);\n let hasWrite = false;\n await Promise.all(\n Object.entries(writeRowsById).map(async ([docId, writeRow]) => {\n const docInDb: RxDocType | undefined = docsInDbById[docId];\n\n if (\n docInDb &&\n (\n !writeRow.assumedMasterState ||\n (await collection.conflictHandler({\n newDocumentState: docInDb as any,\n realMasterState: writeRow.assumedMasterState\n }, 'replication-firestore-push')).isEqual === false\n )\n ) {\n // conflict\n conflicts.push(docInDb as any);\n } else {\n // no conflict\n hasWrite = true;\n const docRef = doc(options.firestore.collection, docId);\n const writeDocData = flatClone(writeRow.newDocumentState);\n (writeDocData as any)[serverTimestampField] = serverTimestamp();\n if (!docInDb) {\n // insert\n batch.set(docRef, stripPrimaryKey(primaryPath, writeDocData));\n } else {\n // update\n batch.update(docRef, stripPrimaryKey(primaryPath, writeDocData));\n }\n }\n })\n );\n\n if (hasWrite) {\n await batch.commit();\n }\n });\n await waitForPendingWrites(options.firestore.database);\n return conflicts;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n\n const replicationState = new RxFirestoreReplicationState(\n options.firestore,\n FIRESTORE_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(options.firestore.projectId),\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart\n );\n\n /**\n * Use long polling to get live changes for the pull.stream$\n */\n if (options.live && options.pull) {\n const startBefore = replicationState.start.bind(replicationState);\n const cancelBefore = replicationState.cancel.bind(replicationState);\n replicationState.start = () => {\n const lastChangeQuery = query(\n options.firestore.collection,\n orderBy(serverTimestampField, 'desc'),\n limit(1)\n );\n const unsubscribe = onSnapshot(\n lastChangeQuery,\n (_querySnapshot) => {\n /**\n * There is no good way to observe the event stream in firestore.\n * So instead we listen to any write to the collection\n * and then emit a 'RESYNC' flag.\n */\n replicationState.reSync();\n },\n (error) => {\n replicationState.subjects.error.next(\n newRxError('RC_STREAM', { error: errorToPlainJson(error) })\n );\n }\n );\n replicationState.cancel = () => {\n unsubscribe();\n return cancelBefore();\n };\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAQA;AAgBA;AAQA;AAIA;AAaA;AACA;AASA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAA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9B,IAAM6G,WAAW,GAAGJ,gBAAgB,CAACK,KAAK,CAACC,IAAI,CAACN,gBAAgB,CAAC;IACjE,IAAMO,YAAY,GAAGP,gBAAgB,CAACQ,MAAM,CAACF,IAAI,CAACN,gBAAgB,CAAC;IACnEA,gBAAgB,CAACK,KAAK,GAAG,YAAM;MAC3B,IAAMI,eAAe,GAAG,IAAApF,gBAAK,EACzBvB,OAAO,CAACV,SAAS,CAACE,UAAU,EAC5B,IAAAiC,kBAAO,EAAClB,oBAAoB,EAAE,MAAM,CAAC,EACrC,IAAAmB,gBAAK,EAAC,CAAC,CAAC,CACX;MACD,IAAMkF,WAAW,GAAG,IAAAC,qBAAU,EAC1BF,eAAe,EACf,UAACG,cAAc,EAAK;QAChB;AACpB;AACA;AACA;AACA;QACoBZ,gBAAgB,CAACa,MAAM,EAAE;MAC7B,CAAC,EACD,UAACC,KAAK,EAAK;QACPd,gBAAgB,CAACe,QAAQ,CAACD,KAAK,CAACE,IAAI,CAChC,IAAApG,YAAU,EAAC,WAAW,EAAE;UAAEkG,KAAK,EAAE,IAAAG,uBAAgB,EAACH,KAAK;QAAE,CAAC,CAAC,CAC9D;MACL,CAAC,CACJ;MACDd,gBAAgB,CAACQ,MAAM,GAAG,YAAM;QAC5BE,WAAW,EAAE;QACb,OAAOH,YAAY,EAAE;MACzB,CAAC;MACD,OAAOH,WAAW,EAAE;IACxB,CAAC;EACL;EAEA,IAAAc,yCAA4B,EAACpH,OAAO,CAACM,iBAAiB,EAAE4F,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js index 9b0d343f912..8166c7cbc2f 100644 --- a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js +++ b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js @@ -8,7 +8,7 @@ exports.fillUpOptionals = fillUpOptionals; exports.graphQLSchemaFromRxSchema = graphQLSchemaFromRxSchema; var _getGraphqlFromJsonschema = require("get-graphql-from-jsonschema"); var _rxSchemaHelper = require("../../rx-schema-helper"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); // we use two spaces because get-graphql-from-jsonschema does also var SPACING = ' '; @@ -30,12 +30,12 @@ function graphQLSchemaFromRxSchema(input) { collectionSettings = _ref[1]; collectionSettings = fillUpOptionals(collectionSettings); var schema = collectionSettings.schema; - var prefixes = (0, _util.ensureNotFalsy)(collectionSettings.prefixes); - var ucCollectionName = (0, _util.ucfirst)(collectionName); - var collectionNameInput = (0, _util.ucfirst)(collectionName) + 'Input'; + var prefixes = (0, _utils.ensureNotFalsy)(collectionSettings.prefixes); + var ucCollectionName = (0, _utils.ucfirst)(collectionName); + var collectionNameInput = (0, _utils.ucfirst)(collectionName) + 'Input'; // input - var inputSchema = stripKeysFromSchema(schema, (0, _util.ensureNotFalsy)(collectionSettings.ignoreInputKeys)); + var inputSchema = stripKeysFromSchema(schema, (0, _utils.ensureNotFalsy)(collectionSettings.ignoreInputKeys)); var inputGraphQL = (0, _getGraphqlFromJsonschema.getGraphqlSchemaFromJsonSchema)({ rootName: collectionNameInput, schema: inputSchema, @@ -83,7 +83,7 @@ function graphQLSchemaFromRxSchema(input) { properties: {}, required: [] }; - (0, _util.ensureNotFalsy)(collectionSettings.headerFields).forEach(function (headerField) { + (0, _utils.ensureNotFalsy)(collectionSettings.headerFields).forEach(function (headerField) { headersSchema.properties[headerField] = { type: 'string' }; @@ -95,14 +95,14 @@ function graphQLSchemaFromRxSchema(input) { schema: headersSchema, direction: 'input' }); - if ((0, _util.ensureNotFalsy)(collectionSettings.headerFields).length > 0) { + if ((0, _utils.ensureNotFalsy)(collectionSettings.headerFields).length > 0) { ret.inputs = ret.inputs.concat(headersInputGraphQL.typeDefinitions.map(function (str) { return replaceTopLevelTypeName(str, headersInputName); })); } // output - var outputSchema = stripKeysFromSchema(schema, (0, _util.ensureNotFalsy)(collectionSettings.ignoreOutputKeys)); + var outputSchema = stripKeysFromSchema(schema, (0, _utils.ensureNotFalsy)(collectionSettings.ignoreOutputKeys)); var outputGraphQL = (0, _getGraphqlFromJsonschema.getGraphqlSchemaFromJsonSchema)({ rootName: collectionName, schema: outputSchema, @@ -169,7 +169,7 @@ function graphQLSchemaFromRxSchema(input) { return ret; } function fillUpOptionals(input) { - input = (0, _util.flatClone)(input); + input = (0, _utils.flatClone)(input); var schema = (0, _rxSchemaHelper.fillWithDefaultSettings)(input.schema); // strip internal attributes Object.keys(schema.properties).forEach(function (key) { @@ -229,7 +229,7 @@ function fillUpOptionals(input) { return input; } function stripKeysFromSchema(schema, strip) { - var cloned = (0, _util.clone)(schema); + var cloned = (0, _utils.clone)(schema); strip.forEach(function (key) { delete cloned.properties[key]; }); diff --git a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map index b74b523695f..607e6f50bae 100644 --- a/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map +++ b/dist/lib/plugins/replication-graphql/graphql-schema-from-rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["SPACING","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ensureNotFalsy","ucCollectionName","ucfirst","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","getGraphqlSchemaFromJsonSchema","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","flatClone","fillWithDefaultSettings","keys","startsWith","deletedField","withRevisions","strip","cloned","clone","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../util';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":";;;;;;;;AAAA;AAEA;AAGA;AAsDA;AACO,IAAMA,OAAO,GAAG,IAAI;;AAE3B;AACA;AACA;AAFA;AAGO,SAASC,yBAAyB,CACrCC,KAAqC,EACN;EAC/B,IAAMC,GAAoC,GAAG;IACzCC,QAAQ,EAAE,EAAE;IACZC,OAAO,EAAE,EAAE;IACXC,SAAS,EAAE,EAAE;IACbC,aAAa,EAAE,EAAE;IACjBC,MAAM,EAAE,EAAE;IACVC,KAAK,EAAE;EACX,CAAC;EAEDC,MAAM,CAACC,OAAO,CAACT,KAAK,CAAC,CAACU,OAAO,CAAC,gBAA0C;IAAA,IAAxCC,cAAc;MAAEC,kBAAkB;IAC9DA,kB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AW,EAAE5B,gBAAwB,EAAU;EAC5E,OAAO4B,GAAG,CAAC2C,OAAO,CAAC,GAAG,GAAGvE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file +{"version":3,"file":"graphql-schema-from-rx-schema.js","names":["SPACING","graphQLSchemaFromRxSchema","input","ret","asString","queries","mutations","subscriptions","inputs","types","Object","entries","forEach","collectionName","collectionSettings","fillUpOptionals","schema","prefixes","ensureNotFalsy","ucCollectionName","ucfirst","collectionNameInput","inputSchema","stripKeysFromSchema","ignoreInputKeys","inputGraphQL","getGraphqlSchemaFromJsonSchema","rootName","direction","pushRowGraphQL","pushRow","type","properties","assumedMasterState","newDocumentState","required","additionalProperties","checkpointSchema","checkpointFields","key","subSchema","push","checkpointInputGraphQL","checkpoint","concat","typeDefinitions","map","str","replaceTopLevelTypeName","headersSchema","headerFields","headerField","headersInputName","headers","headersInputGraphQL","length","outputSchema","ignoreOutputKeys","outputGraphQL","checkpointOutputGraphQL","pullBulkOutputGraphQL","pullBulk","documents","items","queryName","pull","queryKeys","queryString","join","mutationName","mutationString","subscriptionHeaderInputString","subscriptionName","stream","subscriptionString","fullQueryString","fullMutationString","fullSubscriptionString","fullTypeString","fullInputString","fullSchemaString","flatClone","fillWithDefaultSettings","keys","startsWith","deletedField","withRevisions","strip","cloned","clone","replace"],"sources":["../../../../src/plugins/replication-graphql/graphql-schema-from-rx-schema.ts"],"sourcesContent":["import { getGraphqlSchemaFromJsonSchema } from 'get-graphql-from-jsonschema';\n\nimport { fillWithDefaultSettings } from '../../rx-schema-helper';\n\nimport { RxJsonSchema } from '../../types';\nimport { clone, ensureNotFalsy, flatClone, ucfirst } from '../../plugins/utils';\n\nexport type Prefixes = {\n push?: string;\n pushRow?: string;\n checkpoint?: string;\n pull?: string;\n pullBulk?: string;\n stream?: string;\n headers?: string;\n};\n\n/**\n * just type some common types\n * to have better IDE autocomplete,\n * all strings are allowed\n */\nexport type GraphQLParamType = 'ID' | 'ID!' |\n'String' | 'String!' |\n'Int' | 'Int!' |\n'Float' | 'Float!' |\nstring;\n\nexport type GraphQLSchemaFromRxSchemaInputSingleCollection = {\n schema: RxJsonSchema;\n /**\n * These fields of the document data\n * will be used for the checkpoint.\n */\n checkpointFields: string[];\n ignoreInputKeys?: string[];\n ignoreOutputKeys?: string[];\n withRevisions?: boolean;\n prefixes?: Prefixes;\n headerFields?: string[];\n /**\n * Name of the boolean field that marks deleted documents.\n * [default='_deleted']\n */\n deletedField?: string;\n};\n\nexport type GraphQLSchemaFromRxSchemaInput = {\n [collectionName: string]: GraphQLSchemaFromRxSchemaInputSingleCollection;\n};\nexport type GraphQLSchemaFromRxSchemaOutput = {\n asString: string;\n queries: string[];\n mutations: string[];\n subscriptions: string[];\n inputs: string[];\n types: string[];\n};\n\n// we use two spaces because get-graphql-from-jsonschema does also\nexport const SPACING = ' ';\n\n/**\n * Create a GraphQL schema from a given RxJsonSchema\n */\nexport function graphQLSchemaFromRxSchema(\n input: GraphQLSchemaFromRxSchemaInput\n): GraphQLSchemaFromRxSchemaOutput {\n const ret: GraphQLSchemaFromRxSchemaOutput = {\n asString: '',\n queries: [],\n mutations: [],\n subscriptions: [],\n inputs: [],\n types: []\n };\n\n Object.entries(input).forEach(([collectionName, collectionSettings]) => {\n collectionSettings = fillUpOptionals(collectionSettings);\n\n const schema = collectionSettings.schema;\n const prefixes: Prefixes = ensureNotFalsy(collectionSettings.prefixes);\n const ucCollectionName = ucfirst(collectionName);\n const collectionNameInput = ucfirst(collectionName) + 'Input';\n\n // input\n const inputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreInputKeys));\n\n const inputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput,\n schema: inputSchema as any,\n direction: 'input'\n });\n const pushRowGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.pushRow,\n schema: {\n type: 'object',\n properties: {\n assumedMasterState: inputSchema as any,\n newDocumentState: inputSchema as any\n },\n required: ['newDocumentState'],\n additionalProperties: false\n },\n direction: 'input'\n });\n\n const checkpointSchema = {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n } as any;\n collectionSettings.checkpointFields.forEach(key => {\n const subSchema: any = schema.properties[key];\n checkpointSchema.properties[key] = subSchema;\n checkpointSchema.required.push(key);\n });\n const checkpointInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionNameInput + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'input'\n });\n\n ret.inputs = ret.inputs.concat(\n inputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput))\n ).concat(\n pushRowGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.pushRow))\n ).concat(\n checkpointInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, collectionNameInput + prefixes.checkpoint))\n );\n\n const headersSchema: any = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n required: []\n };\n ensureNotFalsy(collectionSettings.headerFields).forEach(headerField => {\n headersSchema.properties[headerField] = {\n type: 'string'\n };\n headersSchema.required.push(headerField);\n });\n const headersInputName = collectionNameInput + prefixes.headers;\n const headersInputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: headersInputName,\n schema: headersSchema,\n direction: 'input'\n });\n if (ensureNotFalsy(collectionSettings.headerFields).length > 0) {\n ret.inputs = ret.inputs.concat(\n headersInputGraphQL\n .typeDefinitions\n .map(str => replaceTopLevelTypeName(str, headersInputName))\n );\n }\n\n // output\n const outputSchema = stripKeysFromSchema(schema, ensureNotFalsy(collectionSettings.ignoreOutputKeys));\n const outputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: collectionName,\n schema: outputSchema as any,\n direction: 'output'\n });\n const checkpointOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.checkpoint,\n schema: checkpointSchema as any,\n direction: 'output'\n });\n const pullBulkOutputGraphQL = getGraphqlSchemaFromJsonSchema({\n rootName: ucCollectionName + prefixes.pullBulk,\n schema: {\n type: 'object',\n properties: {\n documents: {\n type: 'array',\n items: inputSchema as any\n },\n checkpoint: checkpointSchema as any\n },\n required: ['documents', 'checkpoint'],\n additionalProperties: false\n },\n direction: 'output'\n });\n ret.types = ret.types.concat(\n outputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName))\n ).concat(\n checkpointOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.checkpoint))\n ).concat(\n pullBulkOutputGraphQL.typeDefinitions\n .map(str => replaceTopLevelTypeName(str, ucCollectionName + prefixes.pullBulk))\n );\n\n // query\n const queryName = prefixes.pull + ucCollectionName;\n const queryKeys = [\n 'checkpoint: ' + collectionNameInput + prefixes.checkpoint,\n 'limit: Int!'\n ];\n const queryString = queryName + '(' + queryKeys.join(', ') + '): ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.queries.push(SPACING + queryString);\n\n // mutation\n const mutationName = prefixes.push + ucCollectionName;\n const mutationString = mutationName + '(' + collectionName + prefixes.pushRow + ': [' + collectionNameInput + prefixes.pushRow + ']): [' + ucCollectionName + '!]!';\n ret.mutations.push(SPACING + mutationString);\n\n // subscription\n let subscriptionHeaderInputString = '';\n if (collectionSettings.headerFields && collectionSettings.headerFields.length > 0) {\n subscriptionHeaderInputString = '(headers: ' + headersInputName + ')';\n }\n const subscriptionName = prefixes.stream + ucCollectionName;\n const subscriptionString = subscriptionName + subscriptionHeaderInputString + ': ' + ucCollectionName + prefixes.pullBulk + '!';\n ret.subscriptions.push(SPACING + subscriptionString);\n });\n\n // build full string\n const fullQueryString = 'type Query {\\n' + ret.queries.join('\\n') + '\\n}\\n';\n const fullMutationString = 'type Mutation {\\n' + ret.mutations.join('\\n') + '\\n}\\n';\n const fullSubscriptionString = 'type Subscription {\\n' + ret.subscriptions.join('\\n') + '\\n}\\n';\n\n const fullTypeString = ret.types.join('\\n');\n const fullInputString = ret.inputs.join('\\n');\n\n const fullSchemaString = '' +\n 'schema {\\n' +\n SPACING + 'query: Query\\n' +\n SPACING + 'mutation: Mutation\\n' +\n SPACING + 'subscription: Subscription\\n' +\n '}\\n';\n\n ret.asString = '' +\n fullQueryString + '\\n' +\n fullMutationString + '\\n' +\n fullSubscriptionString + '\\n' +\n fullTypeString + '\\n' +\n fullInputString + '\\n' +\n fullSchemaString;\n\n return ret;\n}\n\n\nexport function fillUpOptionals(\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): GraphQLSchemaFromRxSchemaInputSingleCollection {\n input = flatClone(input);\n\n const schema = fillWithDefaultSettings(input.schema);\n // strip internal attributes\n Object.keys(schema.properties).forEach(key => {\n if (key.startsWith('_')) {\n delete schema.properties[key];\n }\n });\n input.schema = schema;\n\n // add deleted field to schema\n if (!input.deletedField) {\n input.deletedField = '_deleted';\n }\n schema.properties[input.deletedField] = {\n type: 'boolean'\n };\n (schema.required as string[]).push(input.deletedField);\n\n // fill up prefixes\n if (!input.prefixes) {\n input.prefixes = {} as any;\n }\n const prefixes: Prefixes = input.prefixes as any;\n if (!prefixes.push) {\n prefixes.push = 'push';\n }\n if (!prefixes.pushRow) {\n prefixes.pushRow = 'PushRow';\n }\n if (!prefixes.checkpoint) {\n prefixes.checkpoint = 'Checkpoint';\n }\n if (!prefixes.pull) {\n prefixes.pull = 'pull';\n }\n if (!prefixes.pullBulk) {\n prefixes.pullBulk = 'PullBulk';\n }\n if (!prefixes.stream) {\n prefixes.stream = 'stream';\n }\n if (!prefixes.headers) {\n prefixes.headers = 'Headers';\n }\n if (!input.headerFields) {\n input.headerFields = [];\n }\n\n\n if (!input.withRevisions) {\n input.withRevisions = false;\n }\n\n if (!input.ignoreInputKeys) {\n input.ignoreInputKeys = [];\n }\n if (!input.ignoreOutputKeys) {\n input.ignoreOutputKeys = [];\n }\n\n return input;\n}\n\nfunction stripKeysFromSchema(schema: RxJsonSchema, strip: string[]): RxJsonSchema> {\n const cloned: any = clone(schema);\n strip.forEach(key => {\n delete cloned.properties[key];\n });\n return cloned;\n}\n\n/**\n * get-graphql-from-jsonschema add a T0-suffix\n * that we do not want for the top level type\n */\nfunction replaceTopLevelTypeName(str: string, ucCollectionName: string): string {\n return str.replace(' ' + ucCollectionName + 'T0 ', ' ' + ucCollectionName + ' ');\n}\n"],"mappings":";;;;;;;;AAAA;AAEA;AAGA;AAsDA;AACO,IAAMA,OAAO,GAAG,IAAI;;AAE3B;AACA;AACA;AAFA;AAGO,SAASC,yBAAyB,CACrCC,KAAqC,EACN;EAC/B,IAAMC,GAAoC,GAAG;IACzCC,QAAQ,EAAE,EAAE;IACZC,OAAO,EAAE,EAAE;IACXC,SAAS,EAAE,EAAE;IACbC,aAAa,EAAE,EAAE;IACjBC,MAAM,EAAE,EAAE;IACVC,KAAK,EAAE;EACX,CAAC;EAEDC,MAAM,CAACC,OAAO,CAACT,KAAK,CAAC,CAACU,OAAO,CAAC,gBAA0C;IAAA,IAAxCC,cAAc;MAAEC,kBAAkB;IAC9DA,kBAAkB,GAAGC,eAAe,CAACD,kBAAkB,CAAC;IAExD,IAAME,MAAM,GAAGF,kBAAkB,CAACE,MAAM;IACxC,IAAMC,QAAkB,GAAG,IAAAC,qBAAc,EAACJ,kBAAkB,CAACG,QAAQ,CAAC;IACtE,IAAME,gBAAgB,GAAG,IAAAC,cAAO,EAACP,cAAc,CAAC;IAChD,IAAMQ,mBAAmB,GAAG,IAAAD,cAAO,EAACP,cAAc,CAAC,GAAG,OAAO;;IAE7D;IACA,IAAMS,WAAW,GAAGC,mBAAmB,CAACP,MAAM,EAAE,IAAAE,qBAAc,EAACJ,kBAAkB,CAACU,eAAe,CAAC,CAAC;IAEnG,IAAMC,YAAY,GAAG,IAAAC,wDAA8B,EAAC;MAChDC,QAAQ,EAAEN,mBAAmB;MAC7BL,MAAM,EAAEM,WAAkB;MAC1BM,SAAS,EAAE;IACf,CAAC,CAAC;IACF,IA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Y,EAAE;IACrBhD,KAAK,CAACgD,YAAY,GAAG,EAAE;EAC3B;EAGA,IAAI,CAAChD,KAAK,CAACoF,aAAa,EAAE;IACtBpF,KAAK,CAACoF,aAAa,GAAG,KAAK;EAC/B;EAEA,IAAI,CAACpF,KAAK,CAACsB,eAAe,EAAE;IACxBtB,KAAK,CAACsB,eAAe,GAAG,EAAE;EAC9B;EACA,IAAI,CAACtB,KAAK,CAACuD,gBAAgB,EAAE;IACzBvD,KAAK,CAACuD,gBAAgB,GAAG,EAAE;EAC/B;EAEA,OAAOvD,KAAK;AAChB;AAEA,SAASqB,mBAAmB,CAAIP,MAAuB,EAAEuE,KAAe,EAA4B;EAChG,IAAMC,MAAW,GAAG,IAAAC,YAAK,EAACzE,MAAM,CAAC;EACjCuE,KAAK,CAAC3E,OAAO,CAAC,UAAA2B,GAAG,EAAI;IACjB,OAAOiD,MAAM,CAACxD,UAAU,CAACO,GAAG,CAAC;EACjC,CAAC,CAAC;EACF,OAAOiD,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA,SAASxC,uBAAuB,CAACD,GAAW,EAAE5B,gBAAwB,EAAU;EAC5E,OAAO4B,GAAG,CAAC2C,OAAO,CAAC,GAAG,GAAGvE,gBAAgB,GAAG,KAAK,EAAE,GAAG,GAAGA,gBAAgB,GAAG,GAAG,CAAC;AACpF"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/graphql-websocket.js b/dist/lib/plugins/replication-graphql/graphql-websocket.js index 711f1a101aa..124bb379fab 100644 --- a/dist/lib/plugins/replication-graphql/graphql-websocket.js +++ b/dist/lib/plugins/replication-graphql/graphql-websocket.js @@ -8,7 +8,7 @@ exports.GRAPHQL_WEBSOCKET_BY_URL = void 0; exports.getGraphQLWebSocket = getGraphQLWebSocket; exports.removeGraphQLWebSocketRef = removeGraphQLWebSocketRef; var _graphqlWs = require("graphql-ws"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _isomorphicWs = _interopRequireDefault(require("isomorphic-ws")); var IsomorphicWebSocket = _isomorphicWs["default"].WebSocket; var GRAPHQL_WEBSOCKET_BY_URL = new Map(); @@ -35,7 +35,7 @@ function getGraphQLWebSocket(url) { return has.socket; } function removeGraphQLWebSocketRef(url) { - var obj = (0, _util.getFromMapOrThrow)(GRAPHQL_WEBSOCKET_BY_URL, url); + var obj = (0, _utils.getFromMapOrThrow)(GRAPHQL_WEBSOCKET_BY_URL, url); obj.refCount = obj.refCount - 1; if (obj.refCount === 0) { GRAPHQL_WEBSOCKET_BY_URL["delete"](url); diff --git a/dist/lib/plugins/replication-graphql/graphql-websocket.js.map b/dist/lib/plugins/replication-graphql/graphql-websocket.js.map index eb4a67a3dc8..ef68965feef 100644 --- a/dist/lib/plugins/replication-graphql/graphql-websocket.js.map +++ b/dist/lib/plugins/replication-graphql/graphql-websocket.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-websocket.js","names":["IsomorphicWebSocket","ws","WebSocket","GRAPHQL_WEBSOCKET_BY_URL","Map","getGraphQLWebSocket","url","has","get","wsClient","createClient","shouldRetry","webSocketImpl","socket","refCount","set","removeGraphQLWebSocketRef","obj","getFromMapOrThrow","dispose"],"sources":["../../../../src/plugins/replication-graphql/graphql-websocket.ts"],"sourcesContent":["import { Client, createClient } from 'graphql-ws';\nimport { getFromMapOrThrow } from '../../util';\nimport ws from 'isomorphic-ws';\n\nconst { WebSocket: IsomorphicWebSocket } = ws;\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: Client;\n refCount: number;\n};\n\nexport const GRAPHQL_WEBSOCKET_BY_URL: Map = new Map();\n\n\nexport function getGraphQLWebSocket(\n url: string\n): Client {\n let has = GRAPHQL_WEBSOCKET_BY_URL.get(url);\n if (!has) {\n const wsClient = createClient({\n url,\n shouldRetry: () => true,\n webSocketImpl: IsomorphicWebSocket,\n });\n has = {\n url,\n socket: wsClient,\n refCount: 1\n };\n GRAPHQL_WEBSOCKET_BY_URL.set(url, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n return has.socket;\n}\n\n\nexport function removeGraphQLWebSocketRef(\n url: string\n) {\n const obj = getFromMapOrThrow(GRAPHQL_WEBSOCKET_BY_URL, url);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n GRAPHQL_WEBSOCKET_BY_URL.delete(url);\n obj.socket.dispose();\n }\n}\n"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AAEA,IAAmBA,mBAAmB,GAAKC,wBAAE,CAArCC,SAAS;AAQV,IAAMC,wBAA4D,GAAG,IAAIC,GAAG,EAAE;AAAC;AAG/E,SAASC,mBAAmB,CAC/BC,GAAW,EACL;EACN,IAAIC,GAAG,GAAGJ,wBAAwB,CAACK,GAAG,CAACF,GAAG,CAAC;EAC3C,IAAI,CAACC,GAAG,EAAE;IACN,IAAME,QAAQ,GAAG,IAAAC,uBAAY,EAAC;MAC1BJ,GAAG,EAAHA,GAAG;MACHK,WAAW,EAAE;QAAA,OAAM,IAAI;MAAA;MACvBC,aAAa,EAAEZ;IACnB,CAAC,CAAC;IACFO,GAAG,GAAG;MACFD,GAAG,EAAHA,GAAG;MACHO,MAAM,EAAEJ,QAAQ;MAChBK,QAAQ,EAAE;IACd,CAAC;IACDX,wBAAwB,CAACY,GAAG,CAACT,GAAG,EAAEC,GAAG,CAAC;EAC1C,CAAC,MAAM;IACHA,GAAG,CAACO,QAAQ,GAAGP,GAAG,CAACO,QAAQ,GAAG,CAAC;EACnC;EACA,OAAOP,GAAG,CAACM,MAAM;AACrB;AAGO,SAASG,yBAAyB,CACrCV,GAAW,EACb;EACE,IAAMW,GAAG,GAAG,IAAAC,uBAAiB,EAACf,wBAAwB,EAAEG,GAAG,CAAC;EAC5DW,GAAG,CAACH,QAAQ,GAAGG,GAAG,CAACH,QAAQ,GAAG,CAAC;EAC/B,IAAIG,GAAG,CAACH,QAAQ,KAAK,CAAC,EAAE;IACpBX,wBAAwB,UAAO,CAACG,GAAG,CAAC;IACpCW,GAAG,CAACJ,MAAM,CAACM,OAAO,EAAE;EACxB;AACJ"} \ No newline at end of file +{"version":3,"file":"graphql-websocket.js","names":["IsomorphicWebSocket","ws","WebSocket","GRAPHQL_WEBSOCKET_BY_URL","Map","getGraphQLWebSocket","url","has","get","wsClient","createClient","shouldRetry","webSocketImpl","socket","refCount","set","removeGraphQLWebSocketRef","obj","getFromMapOrThrow","dispose"],"sources":["../../../../src/plugins/replication-graphql/graphql-websocket.ts"],"sourcesContent":["import { Client, createClient } from 'graphql-ws';\nimport { getFromMapOrThrow } from '../../plugins/utils';\nimport ws from 'isomorphic-ws';\n\nconst { WebSocket: IsomorphicWebSocket } = ws;\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: Client;\n refCount: number;\n};\n\nexport const GRAPHQL_WEBSOCKET_BY_URL: Map = new Map();\n\n\nexport function getGraphQLWebSocket(\n url: string\n): Client {\n let has = GRAPHQL_WEBSOCKET_BY_URL.get(url);\n if (!has) {\n const wsClient = createClient({\n url,\n shouldRetry: () => true,\n webSocketImpl: IsomorphicWebSocket,\n });\n has = {\n url,\n socket: wsClient,\n refCount: 1\n };\n GRAPHQL_WEBSOCKET_BY_URL.set(url, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n return has.socket;\n}\n\n\nexport function removeGraphQLWebSocketRef(\n url: string\n) {\n const obj = getFromMapOrThrow(GRAPHQL_WEBSOCKET_BY_URL, url);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n GRAPHQL_WEBSOCKET_BY_URL.delete(url);\n obj.socket.dispose();\n }\n}\n"],"mappings":";;;;;;;;;AAAA;AACA;AACA;AAEA,IAAmBA,mBAAmB,GAAKC,wBAAE,CAArCC,SAAS;AAQV,IAAMC,wBAA4D,GAAG,IAAIC,GAAG,EAAE;AAAC;AAG/E,SAASC,mBAAmB,CAC/BC,GAAW,EACL;EACN,IAAIC,GAAG,GAAGJ,wBAAwB,CAACK,GAAG,CAACF,GAAG,CAAC;EAC3C,IAAI,CAACC,GAAG,EAAE;IACN,IAAME,QAAQ,GAAG,IAAAC,uBAAY,EAAC;MAC1BJ,GAAG,EAAHA,GAAG;MACHK,WAAW,EAAE;QAAA,OAAM,IAAI;MAAA;MACvBC,aAAa,EAAEZ;IACnB,CAAC,CAAC;IACFO,GAAG,GAAG;MACFD,GAAG,EAAHA,GAAG;MACHO,MAAM,EAAEJ,QAAQ;MAChBK,QAAQ,EAAE;IACd,CAAC;IACDX,wBAAwB,CAACY,GAAG,CAACT,GAAG,EAAEC,GAAG,CAAC;EAC1C,CAAC,MAAM;IACHA,GAAG,CAACO,QAAQ,GAAGP,GAAG,CAACO,QAAQ,GAAG,CAAC;EACnC;EACA,OAAOP,GAAG,CAACM,MAAM;AACrB;AAGO,SAASG,yBAAyB,CACrCV,GAAW,EACb;EACE,IAAMW,GAAG,GAAG,IAAAC,wBAAiB,EAACf,wBAAwB,EAAEG,GAAG,CAAC;EAC5DW,GAAG,CAACH,QAAQ,GAAGG,GAAG,CAACH,QAAQ,GAAG,CAAC;EAC/B,IAAIG,GAAG,CAACH,QAAQ,KAAK,CAAC,EAAE;IACpBX,wBAAwB,UAAO,CAACG,GAAG,CAAC;IACpCW,GAAG,CAACJ,MAAM,CAACM,OAAO,EAAE;EACxB;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/helper.js b/dist/lib/plugins/replication-graphql/helper.js index 785778ebf19..a1c56e0d4db 100644 --- a/dist/lib/plugins/replication-graphql/helper.js +++ b/dist/lib/plugins/replication-graphql/helper.js @@ -5,13 +5,13 @@ Object.defineProperty(exports, "__esModule", { }); exports.GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = void 0; exports.graphQLRequest = graphQLRequest; -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-graphql-'; exports.GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX; function graphQLRequest(httpUrl, clientState, queryParams) { var headers = new Headers(clientState.headers || {}); headers.append('Content-Type', 'application/json'); - var req = new Request((0, _util.ensureNotFalsy)(httpUrl), { + var req = new Request((0, _utils.ensureNotFalsy)(httpUrl), { method: 'POST', body: JSON.stringify(queryParams), headers: headers, diff --git a/dist/lib/plugins/replication-graphql/helper.js.map b/dist/lib/plugins/replication-graphql/helper.js.map index 75676c62d9d..1193964a058 100644 --- a/dist/lib/plugins/replication-graphql/helper.js.map +++ b/dist/lib/plugins/replication-graphql/helper.js.map @@ -1 +1 @@ -{"version":3,"file":"helper.js","names":["GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","graphQLRequest","httpUrl","clientState","queryParams","headers","Headers","append","req","Request","ensureNotFalsy","method","body","JSON","stringify","credentials","fetch","then","res","json"],"sources":["../../../../src/plugins/replication-graphql/helper.ts"],"sourcesContent":["import { RxGraphQLReplicationClientState, RxGraphQLReplicationQueryBuilderResponseObject } from '../../types';\nimport { ensureNotFalsy } from '../../util';\n\nexport const GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-graphql-';\n\nexport interface GraphQLError {\n message: string;\n locations: Array<{\n line: number;\n column: number;\n }>;\n path: string[];\n}\nexport type GraphQLErrors = Array;\n\n\n\nexport function graphQLRequest(\n httpUrl: string,\n clientState: RxGraphQLReplicationClientState,\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n) {\n\n const headers = new Headers(clientState.headers || {});\n headers.append('Content-Type', 'application/json');\n\n const req = new Request(\n ensureNotFalsy(httpUrl),\n {\n method: 'POST',\n body: JSON.stringify(queryParams),\n headers,\n credentials: clientState.credentials,\n }\n );\n return fetch(req)\n .then((res) => res.json())\n .then((body) => {\n return body;\n });\n}\n"],"mappings":";;;;;;;AACA;AAEO,IAAMA,0CAA0C,GAAG,2BAA2B;AAAC;AAc/E,SAASC,cAAc,CAC1BC,OAAe,EACfC,WAA4C,EAC5CC,WAA2D,EAC7D;EAEE,IAAMC,OAAO,GAAG,IAAIC,OAAO,CAACH,WAAW,CAACE,OAAO,IAAI,CAAC,CAAC,CAAC;EACtDA,OAAO,CAACE,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC;EAElD,IAAMC,GAAG,GAAG,IAAIC,OAAO,CACnB,IAAAC,oBAAc,EAACR,OAAO,CAAC,EACvB;IACIS,MAAM,EAAE,MAAM;IACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAACV,WAAW,CAAC;IACjCC,OAAO,EAAPA,OAAO;IACPU,WAAW,EAAEZ,WAAW,CAACY;EAC7B,CAAC,CACJ;EACD,OAAOC,KAAK,CAACR,GAAG,CAAC,CACZS,IAAI,CAAC,UAACC,GAAG;IAAA,OAAKA,GAAG,CAACC,IAAI,EAAE;EAAA,EAAC,CACzBF,IAAI,CAAC,UAACL,IAAI,EAAK;IACZ,OAAOA,IAAI;EACf,CAAC,CAAC;AACV"} \ No newline at end of file +{"version":3,"file":"helper.js","names":["GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","graphQLRequest","httpUrl","clientState","queryParams","headers","Headers","append","req","Request","ensureNotFalsy","method","body","JSON","stringify","credentials","fetch","then","res","json"],"sources":["../../../../src/plugins/replication-graphql/helper.ts"],"sourcesContent":["import { RxGraphQLReplicationClientState, RxGraphQLReplicationQueryBuilderResponseObject } from '../../types';\nimport { ensureNotFalsy } from '../../plugins/utils';\n\nexport const GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX = 'rxdb-replication-graphql-';\n\nexport interface GraphQLError {\n message: string;\n locations: Array<{\n line: number;\n column: number;\n }>;\n path: string[];\n}\nexport type GraphQLErrors = Array;\n\n\n\nexport function graphQLRequest(\n httpUrl: string,\n clientState: RxGraphQLReplicationClientState,\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n) {\n\n const headers = new Headers(clientState.headers || {});\n headers.append('Content-Type', 'application/json');\n\n const req = new Request(\n ensureNotFalsy(httpUrl),\n {\n method: 'POST',\n body: JSON.stringify(queryParams),\n headers,\n credentials: clientState.credentials,\n }\n );\n return fetch(req)\n .then((res) => res.json())\n .then((body) => {\n return body;\n });\n}\n"],"mappings":";;;;;;;AACA;AAEO,IAAMA,0CAA0C,GAAG,2BAA2B;AAAC;AAc/E,SAASC,cAAc,CAC1BC,OAAe,EACfC,WAA4C,EAC5CC,WAA2D,EAC7D;EAEE,IAAMC,OAAO,GAAG,IAAIC,OAAO,CAACH,WAAW,CAACE,OAAO,IAAI,CAAC,CAAC,CAAC;EACtDA,OAAO,CAACE,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC;EAElD,IAAMC,GAAG,GAAG,IAAIC,OAAO,CACnB,IAAAC,qBAAc,EAACR,OAAO,CAAC,EACvB;IACIS,MAAM,EAAE,MAAM;IACdC,IAAI,EAAEC,IAAI,CAACC,SAAS,CAACV,WAAW,CAAC;IACjCC,OAAO,EAAPA,OAAO;IACPU,WAAW,EAAEZ,WAAW,CAACY;EAC7B,CAAC,CACJ;EACD,OAAOC,KAAK,CAACR,GAAG,CAAC,CACZS,IAAI,CAAC,UAACC,GAAG;IAAA,OAAKA,GAAG,CAACC,IAAI,EAAE;EAAA,EAAC,CACzBF,IAAI,CAAC,UAACL,IAAI,EAAK;IACZ,OAAOA,IAAI;EACf,CAAC,CAAC;AACV"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/index.js b/dist/lib/plugins/replication-graphql/index.js index de5b27dde91..9f24dcc6694 100644 --- a/dist/lib/plugins/replication-graphql/index.js +++ b/dist/lib/plugins/replication-graphql/index.js @@ -6,14 +6,15 @@ Object.defineProperty(exports, "__esModule", { }); var _exportNames = { RxGraphQLReplicationState: true, - syncGraphQL: true, - RxDBReplicationGraphQLPlugin: true + replicateGraphQL: true }; -exports.RxGraphQLReplicationState = exports.RxDBReplicationGraphQLPlugin = void 0; -exports.syncGraphQL = syncGraphQL; +exports.RxGraphQLReplicationState = void 0; +exports.replicateGraphQL = replicateGraphQL; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _objectPath = _interopRequireDefault(require("object-path")); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _helper = require("./helper"); Object.keys(_helper).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -95,13 +96,14 @@ var RxGraphQLReplicationState = /*#__PURE__*/function (_RxReplicationState) { this.clientState.credentials = credentials; }; _proto.graphQLRequest = function graphQLRequest(queryParams) { - return (0, _helper.graphQLRequest)((0, _util.ensureNotFalsy)(this.url.http), this.clientState, queryParams); + return (0, _helper.graphQLRequest)((0, _utils.ensureNotFalsy)(this.url.http), this.clientState, queryParams); }; return RxGraphQLReplicationState; }(_replication.RxReplicationState); exports.RxGraphQLReplicationState = RxGraphQLReplicationState; -function syncGraphQL(_ref) { - var url = _ref.url, +function replicateGraphQL(_ref) { + var collection = _ref.collection, + url = _ref.url, _ref$headers = _ref.headers, headers = _ref$headers === void 0 ? {} : _ref$headers, credentials = _ref.credentials, @@ -117,8 +119,7 @@ function syncGraphQL(_ref) { retryTime = _ref$retryTime === void 0 ? 1000 * 5 : _ref$retryTime, _ref$autoStart = _ref.autoStart, autoStart = _ref$autoStart === void 0 ? true : _ref$autoStart; - var collection = this; - + (0, _index.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); /** * We use this object to store the GraphQL client * so we can later swap out the client inside of the replication handlers. @@ -132,37 +133,54 @@ function syncGraphQL(_ref) { if (pull) { var pullBatchSize = pull.batchSize ? pull.batchSize : 20; replicationPrimitivesPull = { - handler: function handler(lastPulledCheckpoint) { - try { - return Promise.resolve(pull.queryBuilder(lastPulledCheckpoint, pullBatchSize)).then(function (pullGraphQL) { - return Promise.resolve(graphqlReplicationState.graphQLRequest(pullGraphQL)).then(function (result) { - function _temp2() { - var docsData = data.documents; - var newCheckpoint = data.checkpoint; - return { - documents: docsData, - checkpoint: newCheckpoint - }; - } - if (result.errors) { + handler: function () { + var _handler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(lastPulledCheckpoint) { + var pullGraphQL, result, dataPath, data, docsData, newCheckpoint; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return pull.queryBuilder(lastPulledCheckpoint, pullBatchSize); + case 2: + pullGraphQL = _context.sent; + _context.next = 5; + return graphqlReplicationState.graphQLRequest(pullGraphQL); + case 5: + result = _context.sent; + if (!result.errors) { + _context.next = 8; + break; + } throw result.errors; - } - var dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]]; - var data = _objectPath["default"].get(result, dataPath); - var _temp = function () { - if (pull.responseModifier) { - return Promise.resolve(pull.responseModifier(data, 'handler', lastPulledCheckpoint)).then(function (_pull$responseModifie) { - data = _pull$responseModifie; - }); + case 8: + dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]]; + data = _objectPath["default"].get(result, dataPath); + if (!pull.responseModifier) { + _context.next = 14; + break; } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - }); - } catch (e) { - return Promise.reject(e); + _context.next = 13; + return pull.responseModifier(data, 'handler', lastPulledCheckpoint); + case 13: + data = _context.sent; + case 14: + docsData = data.documents; + newCheckpoint = data.checkpoint; + return _context.abrupt("return", { + documents: docsData, + checkpoint: newCheckpoint + }); + case 17: + case "end": + return _context.stop(); + } + }, _callee); + })); + function handler(_x) { + return _handler.apply(this, arguments); } - }, + return handler; + }(), batchSize: pull.batchSize, modifier: pull.modifier, stream$: pullStream$.asObservable() @@ -171,56 +189,84 @@ function syncGraphQL(_ref) { var replicationPrimitivesPush; if (push) { replicationPrimitivesPush = { - handler: function handler(rows) { - try { - return Promise.resolve(push.queryBuilder(rows)).then(function (pushObj) { - return Promise.resolve(graphqlReplicationState.graphQLRequest(pushObj)).then(function (result) { - if (result.errors) { + handler: function () { + var _handler2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rows) { + var pushObj, result, dataPath, data; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return push.queryBuilder(rows); + case 2: + pushObj = _context2.sent; + _context2.next = 5; + return graphqlReplicationState.graphQLRequest(pushObj); + case 5: + result = _context2.sent; + if (!result.errors) { + _context2.next = 8; + break; + } throw result.errors; - } - var dataPath = Object.keys(result.data)[0]; - var data = _objectPath["default"].get(result.data, dataPath); - return data; - }); - }); - } catch (e) { - return Promise.reject(e); + case 8: + dataPath = Object.keys(result.data)[0]; + data = _objectPath["default"].get(result.data, dataPath); + return _context2.abrupt("return", data); + case 11: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x2) { + return _handler2.apply(this, arguments); } - }, + return handler; + }(), batchSize: push.batchSize, modifier: push.modifier }; } - var graphqlReplicationState = new RxGraphQLReplicationState(url, mutateableClientState, _helper.GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX + (0, _util.fastUnsecureHash)(url.http ? url.http : url.ws), collection, deletedField, replicationPrimitivesPull, replicationPrimitivesPush, live, retryTime, autoStart); + var graphqlReplicationState = new RxGraphQLReplicationState(url, mutateableClientState, _helper.GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX + (0, _utils.fastUnsecureHash)(url.http ? url.http : url.ws), collection, deletedField, replicationPrimitivesPull, replicationPrimitivesPush, live, retryTime, autoStart); var mustUseSocket = url.ws && pull && pull.streamQueryBuilder && live; var startBefore = graphqlReplicationState.start.bind(graphqlReplicationState); graphqlReplicationState.start = function () { if (mustUseSocket) { - var wsClient = (0, _graphqlWebsocket.getGraphQLWebSocket)((0, _util.ensureNotFalsy)(url.ws)); + var wsClient = (0, _graphqlWebsocket.getGraphQLWebSocket)((0, _utils.ensureNotFalsy)(url.ws)); wsClient.on('connected', function () { pullStream$.next('RESYNC'); }); - var query = (0, _util.ensureNotFalsy)(pull.streamQueryBuilder)(mutateableClientState.headers); + var query = (0, _utils.ensureNotFalsy)(pull.streamQueryBuilder)(mutateableClientState.headers); wsClient.subscribe(query, { - next: function (streamResponse) { - try { - var _temp4 = function _temp4() { - pullStream$.next(_data); - }; - var firstField = Object.keys(streamResponse.data)[0]; - var _data = streamResponse.data[firstField]; - var _temp3 = function () { - if (pull.responseModifier) { - return Promise.resolve(pull.responseModifier(_data, 'stream')).then(function (_pull$responseModifie2) { - _data = _pull$responseModifie2; - }); + next: function () { + var _next = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(streamResponse) { + var firstField, data; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + firstField = Object.keys(streamResponse.data)[0]; + data = streamResponse.data[firstField]; + if (!pull.responseModifier) { + _context3.next = 6; + break; + } + _context3.next = 5; + return pull.responseModifier(data, 'stream'); + case 5: + data = _context3.sent; + case 6: + pullStream$.next(data); + case 7: + case "end": + return _context3.stop(); } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); + }, _callee3); + })); + function next(_x3) { + return _next.apply(this, arguments); } - }, + return next; + }(), error: function error(_error) { pullStream$.error(_error); }, @@ -235,24 +281,11 @@ function syncGraphQL(_ref) { graphqlReplicationState.cancel = function () { pullStream$.complete(); if (mustUseSocket) { - (0, _graphqlWebsocket.removeGraphQLWebSocketRef)((0, _util.ensureNotFalsy)(url.ws)); + (0, _graphqlWebsocket.removeGraphQLWebSocketRef)((0, _utils.ensureNotFalsy)(url.ws)); } return cancelBefore(); }; (0, _replication.startReplicationOnLeaderShip)(waitForLeadership, graphqlReplicationState); return graphqlReplicationState; } -var RxDBReplicationGraphQLPlugin = { - name: 'replication-graphql', - init: function init() { - (0, _index.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncGraphQL = syncGraphQL; - } - } -}; -exports.RxDBReplicationGraphQLPlugin = RxDBReplicationGraphQLPlugin; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/index.js.map b/dist/lib/plugins/replication-graphql/index.js.map index e7628a6b43a..930dd0342d6 100644 --- a/dist/lib/plugins/replication-graphql/index.js.map +++ b/dist/lib/plugins/replication-graphql/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["RxGraphQLReplicationState","url","clientState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","setHeaders","headers","setCredentials","credentials","graphQLRequest","queryParams","ensureNotFalsy","http","RxReplicationState","syncGraphQL","waitForLeadership","mutateableClientState","pullStream$","Subject","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","queryBuilder","pullGraphQL","graphqlReplicationState","result","docsData","data","documents","newCheckpoint","checkpoint","errors","dataPath","Object","keys","objectPath","get","responseModifier","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","fastUnsecureHash","ws","mustUseSocket","streamQueryBuilder","startBefore","start","bind","wsClient","getGraphQLWebSocket","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","removeGraphQLWebSocketRef","startReplicationOnLeaderShip","RxDBReplicationGraphQLPlugin","name","init","addRxPlugin","RxDBLeaderElectionPlugin","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport objectPath from 'object-path';\nimport {\n ensureNotFalsy,\n fastUnsecureHash\n} from '../../util';\n\nimport {\n graphQLRequest,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX\n} from './helper';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n RxPlugin,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean\n ) {\n super(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: { [k: string]: string; }): void {\n this.clientState.headers = headers;\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\n\nexport function syncGraphQL(\n this: RxCollection,\n {\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n const collection = this;\n\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = objectPath.get(result, dataPath);\n\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = Object.keys(result.data)[0];\n const data: any = objectPath.get(result.data, dataPath);\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(url.http ? url.http : url.ws as any),\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws));\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper';\nexport * from './graphql-schema-from-rx-schema';\nexport * from './query-builder-from-rx-schema';\nexport * from './graphql-websocket';\n\nexport const RxDBReplicationGraphQLPlugin: RxPlugin = {\n name: 'replication-graphql',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncGraphQL = syncGraphQL;\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAIA;AACA;AAKA;AA2OA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAtOA;AAYA;AAIA;AAMA;AAmNA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AA/MA;AA6MA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAvPA;AACA;AACA;AACA;AAHA,IA8CaA,yBAAyB;EAAA;EAClC,mCACoBC,GAAqB,EACrBC,WAA4C,EAC5CC,yBAAiC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AA;QACDiC,KAAK,EAAE,eAACA,MAAU,EAAK;UACnB7C,WAAW,CAAC6C,KAAK,CAACA,MAAK,CAAC;QAC5B,CAAC;QACDC,QAAQ,EAAE,oBAAM;UACZ9C,WAAW,CAAC8C,QAAQ,EAAE;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOZ,WAAW,EAAE;EACxB,CAAC;EAED,IAAMa,YAAY,GAAGtC,uBAAuB,CAACuC,MAAM,CAACZ,IAAI,CAAC3B,uBAAuB,CAAC;EACjFA,uBAAuB,CAACuC,MAAM,GAAG,YAAM;IACnChD,WAAW,CAAC8C,QAAQ,EAAE;IACtB,IAAId,aAAa,EAAE;MACf,IAAAiB,2CAAyB,EAAC,IAAAvD,oBAAc,EAAChB,GAAG,CAACqD,EAAE,CAAC,CAAC;IACrD;IACA,OAAOgB,YAAY,EAAE;EACzB,CAAC;EAED,IAAAG,yCAA4B,EAACpD,iBAAiB,EAAEW,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC;AAOO,IAAM0C,4BAAsC,GAAG;EAClDC,IAAI,EAAE,qBAAqB;EAC3BC,IAAI,kBAAG;IACH,IAAAC,kBAAW,EAACC,wCAAwB,CAAC;EACzC,CAAC;EACDC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAAC9D,WAAW,GAAGA,WAAW;IACnC;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["RxGraphQLReplicationState","url","clientState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","setHeaders","headers","setCredentials","credentials","graphQLRequest","queryParams","ensureNotFalsy","http","RxReplicationState","replicateGraphQL","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","mutateableClientState","pullStream$","Subject","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","queryBuilder","pullGraphQL","graphqlReplicationState","result","errors","dataPath","Object","keys","data","objectPath","get","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX","fastUnsecureHash","ws","mustUseSocket","streamQueryBuilder","startBefore","start","bind","wsClient","getGraphQLWebSocket","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","removeGraphQLWebSocketRef","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport objectPath from 'object-path';\nimport {\n ensureNotFalsy,\n fastUnsecureHash\n} from '../../plugins/utils';\n\nimport {\n graphQLRequest,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX\n} from './helper';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState\n} from '../../types';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean\n ) {\n super(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: { [k: string]: string; }): void {\n this.clientState.headers = headers;\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = objectPath.get(result, dataPath);\n\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = Object.keys(result.data)[0];\n const data: any = objectPath.get(result.data, dataPath);\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n GRAPHQL_REPLICATION_PLUGIN_IDENTITY_PREFIX + fastUnsecureHash(url.http ? url.http : url.ws as any),\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws));\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper';\nexport * from './graphql-schema-from-rx-schema';\nexport * from './query-builder-from-rx-schema';\nexport * from './graphql-websocket';\n"],"mappings":";;;;;;;;;;;;;;;AAIA;AACA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AAEa,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js b/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js index 67a74deb208..74b20829eaa 100644 --- a/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js +++ b/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js @@ -7,12 +7,12 @@ exports.pullQueryBuilderFromRxSchema = pullQueryBuilderFromRxSchema; exports.pullStreamBuilderFromRxSchema = pullStreamBuilderFromRxSchema; exports.pushQueryBuilderFromRxSchema = pushQueryBuilderFromRxSchema; var _graphqlSchemaFromRxSchema = require("./graphql-schema-from-rx-schema"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); function pullQueryBuilderFromRxSchema(collectionName, input) { input = (0, _graphqlSchemaFromRxSchema.fillUpOptionals)(input); var schema = input.schema; var prefixes = input.prefixes; - var ucCollectionName = (0, _util.ucfirst)(collectionName); + var ucCollectionName = (0, _utils.ucfirst)(collectionName); var queryName = prefixes.pull + ucCollectionName; var outputFields = Object.keys(schema.properties).filter(function (k) { return !input.ignoreOutputKeys.includes(k); @@ -21,7 +21,7 @@ function pullQueryBuilderFromRxSchema(collectionName, input) { var checkpointInputName = ucCollectionName + 'Input' + prefixes.checkpoint; var builder = function builder(checkpoint, limit) { - var query = 'query ' + (0, _util.ucfirst)(queryName) + '($checkpoint: ' + checkpointInputName + ', $limit: Int!) {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + queryName + '(checkpoint: $checkpoint, limit: $limit) {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'documents {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + outputFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'checkpoint {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + input.checkpointFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + '}'; + var query = 'query ' + (0, _utils.ucfirst)(queryName) + '($checkpoint: ' + checkpointInputName + ', $limit: Int!) {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + queryName + '(checkpoint: $checkpoint, limit: $limit) {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'documents {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + outputFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'checkpoint {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + input.checkpointFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + '}'; return { query: query, variables: { @@ -36,12 +36,12 @@ function pullStreamBuilderFromRxSchema(collectionName, input) { input = (0, _graphqlSchemaFromRxSchema.fillUpOptionals)(input); var schema = input.schema; var prefixes = input.prefixes; - var ucCollectionName = (0, _util.ucfirst)(collectionName); + var ucCollectionName = (0, _utils.ucfirst)(collectionName); var outputFields = Object.keys(schema.properties).filter(function (k) { return !input.ignoreOutputKeys.includes(k); }); var headersName = ucCollectionName + 'Input' + prefixes.headers; - var query = 'subscription on' + (0, _util.ucfirst)((0, _util.ensureNotFalsy)(prefixes.stream)) + '($headers: ' + headersName + ') {\n' + _graphqlSchemaFromRxSchema.SPACING + prefixes.stream + ucCollectionName + '(headers: $headers) {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'documents {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + outputFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'checkpoint {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + input.checkpointFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + '}' + '}'; + var query = 'subscription on' + (0, _utils.ucfirst)((0, _utils.ensureNotFalsy)(prefixes.stream)) + '($headers: ' + headersName + ') {\n' + _graphqlSchemaFromRxSchema.SPACING + prefixes.stream + ucCollectionName + '(headers: $headers) {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'documents {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + outputFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + 'checkpoint {\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + input.checkpointFields.join('\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING) + '\n' + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + _graphqlSchemaFromRxSchema.SPACING + '}\n' + _graphqlSchemaFromRxSchema.SPACING + '}' + '}'; var builder = function builder(headers) { return { query: query, @@ -55,7 +55,7 @@ function pullStreamBuilderFromRxSchema(collectionName, input) { function pushQueryBuilderFromRxSchema(collectionName, input) { input = (0, _graphqlSchemaFromRxSchema.fillUpOptionals)(input); var prefixes = input.prefixes; - var ucCollectionName = (0, _util.ucfirst)(collectionName); + var ucCollectionName = (0, _utils.ucfirst)(collectionName); var queryName = prefixes.push + ucCollectionName; var variableName = collectionName + prefixes.pushRow; var returnFields = Object.keys(input.schema.properties); diff --git a/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js.map b/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js.map index 2b0fc607a35..201dd2d290f 100644 --- a/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js.map +++ b/dist/lib/plugins/replication-graphql/query-builder-from-rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"query-builder-from-rx-schema.js","names":["pullQueryBuilderFromRxSchema","collectionName","input","fillUpOptionals","schema","prefixes","ucCollectionName","ucfirst","queryName","pull","outputFields","Object","keys","properties","filter","k","ignoreOutputKeys","includes","checkpointInputName","checkpoint","builder","limit","query","SPACING","join","checkpointFields","variables","pullStreamBuilderFromRxSchema","headersName","headers","ensureNotFalsy","stream","pushQueryBuilderFromRxSchema","push","variableName","pushRow","returnFields","pushRows","sendRows","transformPushDoc","doc","sendDoc","entries","forEach","v","ignoreInputKeys","newRow","newDocumentState","assumedMasterState","undefined"],"sources":["../../../../src/plugins/replication-graphql/query-builder-from-rx-schema.ts"],"sourcesContent":["import {\n GraphQLSchemaFromRxSchemaInputSingleCollection,\n fillUpOptionals,\n Prefixes,\n SPACING\n} from './graphql-schema-from-rx-schema';\nimport { ensureNotFalsy, ucfirst } from '../../util';\nimport type {\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLReplicationPullStreamQueryBuilder,\n RxGraphQLReplicationPushQueryBuilder,\n WithDeleted\n} from '../../types';\n\nexport function pullQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n): RxGraphQLReplicationPullQueryBuilder {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.pull + ucCollectionName;\n\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n // outputFields.push(input.deletedField);\n\n const checkpointInputName = ucCollectionName + 'Input' + prefixes.checkpoint;\n\n const builder: RxGraphQLReplicationPullQueryBuilder = (checkpoint: any, limit: number) => {\n const query = 'query ' + ucfirst(queryName) + '($checkpoint: ' + checkpointInputName + ', $limit: Int!) {\\n' +\n SPACING + SPACING + queryName + '(checkpoint: $checkpoint, limit: $limit) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + '}\\n' +\n '}';\n return {\n query,\n variables: {\n checkpoint,\n limit\n }\n };\n };\n\n return builder;\n}\n\nexport function pullStreamBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n) {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n\n const headersName = ucCollectionName + 'Input' + prefixes.headers;\n\n const query = 'subscription on' + ucfirst(ensureNotFalsy(prefixes.stream)) + '($headers: ' + headersName + ') {\\n' +\n SPACING + prefixes.stream + ucCollectionName + '(headers: $headers) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + '}' +\n '}';\n\n const builder: RxGraphQLReplicationPullStreamQueryBuilder = (headers: any) => {\n return {\n query,\n variables: {\n headers\n }\n };\n };\n return builder;\n}\n\n\nexport function pushQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): RxGraphQLReplicationPushQueryBuilder {\n input = fillUpOptionals(input);\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.push + ucCollectionName;\n\n const variableName = collectionName + prefixes.pushRow;\n\n\n const returnFields: string[] = Object.keys(input.schema.properties);\n\n const builder: RxGraphQLReplicationPushQueryBuilder = (pushRows) => {\n const query = '' +\n 'mutation ' + prefixes.push + ucCollectionName + '($' + variableName + ': [' + ucCollectionName + 'Input' + prefixes.pushRow + '!]) {\\n' +\n SPACING + queryName + '(' + variableName + ': $' + variableName + ') {\\n' +\n SPACING + SPACING + returnFields.join(',\\n' + SPACING + SPACING) + '\\n' +\n SPACING + '}\\n' +\n '}';\n\n const sendRows: typeof pushRows = [];\n function transformPushDoc(doc: WithDeleted) {\n const sendDoc: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (\n // skip if in ignoreInputKeys list\n !(input.ignoreInputKeys as string[]).includes(k) &&\n // only use properties that are in the schema\n input.schema.properties[k]\n ) {\n sendDoc[k] = v;\n }\n });\n return sendDoc;\n }\n pushRows.forEach(pushRow => {\n const newRow: typeof pushRow = {\n newDocumentState: transformPushDoc(pushRow.newDocumentState),\n assumedMasterState: pushRow.assumedMasterState ? transformPushDoc(pushRow.assumedMasterState) : undefined\n };\n sendRows.push(newRow);\n });\n const variables = {\n [variableName]: sendRows\n };\n return {\n query,\n variables\n };\n };\n\n return builder;\n}\n"],"mappings":";;;;;;;;AAAA;AAMA;AAQO,SAASA,4BAA4B,CACxCC,cAAsB,EACtBC,KAAqD,EACZ;EACzCA,KAAK,GAAG,IAAAC,0CAAe,EAACD,KAAK,CAAC;EAC9B,IAAME,MAAM,GAAGF,KAAK,CAACE,MAAM;EAC3B,IAAMC,QAAkB,GAAGH,KAAK,CAACG,QAAe;EAEhD,IAAMC,gBAAgB,GAAG,IAAAC,aAAO,EAACN,cAAc,CAAC;EAChD,IAAMO,SAAS,GAAGH,QAAQ,CAACI,IAAI,GAAGH,gBAAgB;EAElD,IAAMI,YAAY,GAAGC,MAAM,CAACC,IAAI,CAACR,MAAM,CAACS,UAAU,CAAC,CAACC,MAAM,CAAC,UAAAC,CAAC;IAAA,OAAI,CAAEb,KAAK,CAACc,gBAAgB,CAAcC,QAAQ,CAACF,CAAC,CAAC;EAAA,EAAC;EAClH;;EAEA,IAAMG,mBAAmB,GAAGZ,gBAAgB,GAAG,OAAO,GAAGD,QAAQ,CAACc,UAAU;EAE5E,IAAMC,OAAkD,GAAG,SAArDA,OAAkD,CAAID,UAAe,EAAEE,KAAa,EAAK;IAC3F,IAAMC,KAAK,GAAG,QAAQ,GAAG,IAAAf,aAAO,EAACC,SAAS,CAAC,GA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,CAAC;QAChD;QACAb,KAAK,CAACE,MAAM,CAACS,UAAU,CAACE,CAAC,CAAC,EAC5B;UACE0B,OAAO,CAAC1B,CAAC,CAAC,GAAG6B,CAAC;QAClB;MACJ,CAAC,CAAC;MACF,OAAOH,OAAO;IAClB;IACAJ,QAAQ,CAACM,OAAO,CAAC,UAAAR,OAAO,EAAI;MACxB,IAAMW,MAAsB,GAAG;QAC3BC,gBAAgB,EAAER,gBAAgB,CAACJ,OAAO,CAACY,gBAAgB,CAAC;QAC5DC,kBAAkB,EAAEb,OAAO,CAACa,kBAAkB,GAAGT,gBAAgB,CAACJ,OAAO,CAACa,kBAAkB,CAAC,GAAGC;MACpG,CAAC;MACDX,QAAQ,CAACL,IAAI,CAACa,MAAM,CAAC;IACzB,CAAC,CAAC;IACF,IAAMpB,SAAS,gCACVQ,YAAY,IAAGI,QAAQ,aAC3B;IACD,OAAO;MACHhB,KAAK,EAALA,KAAK;MACLI,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAED,OAAON,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"query-builder-from-rx-schema.js","names":["pullQueryBuilderFromRxSchema","collectionName","input","fillUpOptionals","schema","prefixes","ucCollectionName","ucfirst","queryName","pull","outputFields","Object","keys","properties","filter","k","ignoreOutputKeys","includes","checkpointInputName","checkpoint","builder","limit","query","SPACING","join","checkpointFields","variables","pullStreamBuilderFromRxSchema","headersName","headers","ensureNotFalsy","stream","pushQueryBuilderFromRxSchema","push","variableName","pushRow","returnFields","pushRows","sendRows","transformPushDoc","doc","sendDoc","entries","forEach","v","ignoreInputKeys","newRow","newDocumentState","assumedMasterState","undefined"],"sources":["../../../../src/plugins/replication-graphql/query-builder-from-rx-schema.ts"],"sourcesContent":["import {\n GraphQLSchemaFromRxSchemaInputSingleCollection,\n fillUpOptionals,\n Prefixes,\n SPACING\n} from './graphql-schema-from-rx-schema';\nimport { ensureNotFalsy, ucfirst } from '../../plugins/utils';\nimport type {\n RxGraphQLReplicationPullQueryBuilder,\n RxGraphQLReplicationPullStreamQueryBuilder,\n RxGraphQLReplicationPushQueryBuilder,\n WithDeleted\n} from '../../types';\n\nexport function pullQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n): RxGraphQLReplicationPullQueryBuilder {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.pull + ucCollectionName;\n\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n // outputFields.push(input.deletedField);\n\n const checkpointInputName = ucCollectionName + 'Input' + prefixes.checkpoint;\n\n const builder: RxGraphQLReplicationPullQueryBuilder = (checkpoint: any, limit: number) => {\n const query = 'query ' + ucfirst(queryName) + '($checkpoint: ' + checkpointInputName + ', $limit: Int!) {\\n' +\n SPACING + SPACING + queryName + '(checkpoint: $checkpoint, limit: $limit) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + '}\\n' +\n '}';\n return {\n query,\n variables: {\n checkpoint,\n limit\n }\n };\n };\n\n return builder;\n}\n\nexport function pullStreamBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection,\n) {\n input = fillUpOptionals(input);\n const schema = input.schema;\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const outputFields = Object.keys(schema.properties).filter(k => !(input.ignoreOutputKeys as string[]).includes(k));\n\n const headersName = ucCollectionName + 'Input' + prefixes.headers;\n\n const query = 'subscription on' + ucfirst(ensureNotFalsy(prefixes.stream)) + '($headers: ' + headersName + ') {\\n' +\n SPACING + prefixes.stream + ucCollectionName + '(headers: $headers) {\\n' +\n SPACING + SPACING + SPACING + 'documents {\\n' +\n SPACING + SPACING + SPACING + SPACING + outputFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + SPACING + SPACING + 'checkpoint {\\n' +\n SPACING + SPACING + SPACING + SPACING + input.checkpointFields.join('\\n' + SPACING + SPACING + SPACING + SPACING) + '\\n' +\n SPACING + SPACING + SPACING + '}\\n' +\n SPACING + '}' +\n '}';\n\n const builder: RxGraphQLReplicationPullStreamQueryBuilder = (headers: any) => {\n return {\n query,\n variables: {\n headers\n }\n };\n };\n return builder;\n}\n\n\nexport function pushQueryBuilderFromRxSchema(\n collectionName: string,\n input: GraphQLSchemaFromRxSchemaInputSingleCollection\n): RxGraphQLReplicationPushQueryBuilder {\n input = fillUpOptionals(input);\n const prefixes: Prefixes = input.prefixes as any;\n\n const ucCollectionName = ucfirst(collectionName);\n const queryName = prefixes.push + ucCollectionName;\n\n const variableName = collectionName + prefixes.pushRow;\n\n\n const returnFields: string[] = Object.keys(input.schema.properties);\n\n const builder: RxGraphQLReplicationPushQueryBuilder = (pushRows) => {\n const query = '' +\n 'mutation ' + prefixes.push + ucCollectionName + '($' + variableName + ': [' + ucCollectionName + 'Input' + prefixes.pushRow + '!]) {\\n' +\n SPACING + queryName + '(' + variableName + ': $' + variableName + ') {\\n' +\n SPACING + SPACING + returnFields.join(',\\n' + SPACING + SPACING) + '\\n' +\n SPACING + '}\\n' +\n '}';\n\n const sendRows: typeof pushRows = [];\n function transformPushDoc(doc: WithDeleted) {\n const sendDoc: any = {};\n Object.entries(doc).forEach(([k, v]) => {\n if (\n // skip if in ignoreInputKeys list\n !(input.ignoreInputKeys as string[]).includes(k) &&\n // only use properties that are in the schema\n input.schema.properties[k]\n ) {\n sendDoc[k] = v;\n }\n });\n return sendDoc;\n }\n pushRows.forEach(pushRow => {\n const newRow: typeof pushRow = {\n newDocumentState: transformPushDoc(pushRow.newDocumentState),\n assumedMasterState: pushRow.assumedMasterState ? transformPushDoc(pushRow.assumedMasterState) : undefined\n };\n sendRows.push(newRow);\n });\n const variables = {\n [variableName]: sendRows\n };\n return {\n query,\n variables\n };\n };\n\n return builder;\n}\n"],"mappings":";;;;;;;;AAAA;AAMA;AAQO,SAASA,4BAA4B,CACxCC,cAAsB,EACtBC,KAAqD,EACZ;EACzCA,KAAK,GAAG,IAAAC,0CAAe,EAACD,KAAK,CAAC;EAC9B,IAAME,MAAM,GAAGF,KAAK,CAACE,MAAM;EAC3B,IAAMC,QAAkB,GAAGH,KAAK,CAACG,QAAe;EAEhD,IAAMC,gBAAgB,GAAG,IAAAC,cAAO,EAACN,cAAc,CAAC;EAChD,IAAMO,SAAS,GAAGH,QAAQ,CAACI,IAAI,GAAGH,gBAAgB;EAElD,IAAMI,YAAY,GAAGC,MAAM,CAACC,IAAI,CAACR,MAAM,CAACS,UAAU,CAAC,CAACC,MAAM,CAAC,UAAAC,CAAC;IAAA,OAAI,CAAEb,KAAK,CAACc,gBAAgB,CAAcC,QAAQ,CAACF,CAAC,CAAC;EAAA,EAAC;EAClH;;EAEA,IAAMG,mBAAmB,GAAGZ,gBAAgB,GAAG,OAAO,GAAGD,QAAQ,CAACc,UAAU;EAE5E,IAAMC,OAAkD,GAAG,SAArDA,OAAkD,CAAID,UAAe,EAAEE,KAAa,EAAK;IAC3F,IAAMC,KAAK,GAAG,QAAQ,GAAG,IAAAf,cAAO,EAACC,SAAS,CAAC,GAAG,gBAAgB,GAAGU,mBAAmB,GAAG,qBAAqB,GACxGK,kCAAO,GAAGA,kCAAO,GAAGf,SAAS,GAAG,8CAA8C,GAC9Ee,kCAAO,GAAGA,kCAAO,GAAGA,kCAAO,GAAG,eAAe,GAC7CA,kCAAO,GAAGA,kCAAO,GAAGA,kCAAO,GA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UAAAR,OAAO,EAAI;MACxB,IAAMW,MAAsB,GAAG;QAC3BC,gBAAgB,EAAER,gBAAgB,CAACJ,OAAO,CAACY,gBAAgB,CAAC;QAC5DC,kBAAkB,EAAEb,OAAO,CAACa,kBAAkB,GAAGT,gBAAgB,CAACJ,OAAO,CAACa,kBAAkB,CAAC,GAAGC;MACpG,CAAC;MACDX,QAAQ,CAACL,IAAI,CAACa,MAAM,CAAC;IACzB,CAAC,CAAC;IACF,IAAMpB,SAAS,gCACVQ,YAAY,IAAGI,QAAQ,aAC3B;IACD,OAAO;MACHhB,KAAK,EAALA,KAAK;MACLI,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAED,OAAON,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js b/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js index bfc7fb628d3..d1b81a23440 100644 --- a/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js +++ b/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js @@ -5,8 +5,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.getConnectionHandlerSimplePeer = getConnectionHandlerSimplePeer; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _simplePeer = _interopRequireDefault(require("simple-peer")); var _rxError = require("../../rx-error"); /** @@ -16,7 +18,7 @@ function getConnectionHandlerSimplePeer(serverUrl, wrtc) { var io = require('socket.io-client'); var creator = function creator(options) { var socket = io(serverUrl); - var peerId = (0, _util.randomCouchString)(10); + var peerId = (0, _utils.randomCouchString)(10); socket.emit('join', { room: options.topic, peerId: peerId @@ -75,7 +77,7 @@ function getConnectionHandlerSimplePeer(serverUrl, wrtc) { }); socket.on('signal', function (data) { // console.log('got signal(' + peerId + ') ' + data.from + ' -> ' + data.to); - var peer = (0, _util.getFromMapOrThrow)(peers, data.from); + var peer = (0, _utils.getFromMapOrThrow)(peers, data.from); peer.signal(data.signal); }); var handler = { @@ -84,13 +86,24 @@ function getConnectionHandlerSimplePeer(serverUrl, wrtc) { disconnect$: disconnect$, message$: message$, response$: response$, - send: function send(peer, message) { - try { - return Promise.resolve(peer.send(JSON.stringify(message))).then(function () {}); - } catch (e) { - return Promise.reject(e); + send: function () { + var _send = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(peer, message) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return peer.send(JSON.stringify(message)); + case 2: + case "end": + return _context.stop(); + } + }, _callee); + })); + function send(_x, _x2) { + return _send.apply(this, arguments); } - }, + return send; + }(), destroy: function destroy() { socket.close(); error$.complete(); @@ -98,7 +111,7 @@ function getConnectionHandlerSimplePeer(serverUrl, wrtc) { disconnect$.complete(); message$.complete(); response$.complete(); - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } }; return handler; diff --git a/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js.map b/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js.map index 3dc1b331e2b..9bcacec1c1f 100644 --- a/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js.map +++ b/dist/lib/plugins/replication-p2p/connection-handler-simple-peer.js.map @@ -1 +1 @@ -{"version":3,"file":"connection-handler-simple-peer.js","names":["getConnectionHandlerSimplePeer","serverUrl","wrtc","io","require","creator","options","socket","peerId","randomCouchString","emit","room","topic","connect$","Subject","disconnect$","message$","response$","error$","peers","Map","on","roomPeerIds","forEach","remotePeerId","has","newPeer","Peer","initiator","trickle","set","messageOrResponse","JSON","parse","toString","result","next","peer","response","message","signal","from","to","error","newRxError","data","getFromMapOrThrow","handler","send","stringify","destroy","close","complete","PROMISE_RESOLVE_VOID"],"sources":["../../../../src/plugins/replication-p2p/connection-handler-simple-peer.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport { getFromMapOrThrow, PROMISE_RESOLVE_VOID, randomCouchString } from '../../util';\nimport type {\n P2PConnectionHandler,\n P2PConnectionHandlerCreator,\n P2PMessage,\n P2PPeer,\n PeerWithMessage,\n PeerWithResponse\n} from './p2p-types';\n\nimport {\n Instance as SimplePeer,\n default as Peer\n} from 'simple-peer';\nimport { RxError, RxTypeError } from '../../types';\nimport { newRxError } from '../../rx-error';\n\n/**\n * Returns a connection handler that uses simple-peer and the signaling server.\n */\nexport function getConnectionHandlerSimplePeer(\n serverUrl: string,\n wrtc?: any\n): P2PConnectionHandlerCreator {\n const io = require('socket.io-client');\n\n\n const creator: P2PConnectionHandlerCreator = (options) => {\n const socket = io(serverUrl);\n\n const peerId = randomCouchString(10);\n socket.emit('join', {\n room: options.topic,\n peerId\n });\n\n const connect$ = new Subject();\n const disconnect$ = new Subject();\n const message$ = new Subject();\n const response$ = new Subject();\n const error$ = new Subject();\n\n const peers = new Map();\n\n socket.on('joined', (roomPeerIds: string[]) => {\n roomPeerIds.forEach(remotePeerId => {\n if (\n remotePeerId === peerId ||\n peers.has(remotePeerId)\n ) {\n return;\n }\n // console.log('other user joined room ' + remotePeerId);\n const newPeer: SimplePeer = new Peer({\n initiator: remotePeerId > peerId,\n wrtc,\n trickle: true\n }) as any;\n peers.set(remotePeerId, newPeer);\n\n\n newPeer.on('data', (messageOrResponse: any) => {\n messageOrResponse = JSON.parse(messageOrResponse.toString());\n // console.log('got a message from peer3: ' + messageOrResponse)\n if (messageOrResponse.result) {\n response$.next({\n peer: newPeer as any,\n response: messageOrResponse\n });\n } else {\n message$.next({\n peer: newPeer as any,\n message: messageOrResponse\n });\n }\n });\n\n newPeer.on('signal', (signal: any) => {\n // console.log('emit signal from ' + peerId + ' to ' + remotePeerId);\n socket.emit('signal', {\n from: peerId,\n to: remotePeerId,\n room: options.topic,\n signal\n });\n });\n\n newPeer.on('error', (error) => {\n error$.next(newRxError('RC_P2P_PEER', {\n error\n }));\n });\n\n newPeer.on('connect', () => {\n connect$.next(newPeer as any);\n });\n\n });\n });\n\n socket.on('signal', (data: any) => {\n // console.log('got signal(' + peerId + ') ' + data.from + ' -> ' + data.to);\n const peer = getFromMapOrThrow(peers, data.from);\n peer.signal(data.signal);\n });\n\n const handler: P2PConnectionHandler = {\n error$,\n connect$,\n disconnect$,\n message$,\n response$,\n async send(peer: P2PPeer, message: P2PMessage) {\n await (peer as any).send(JSON.stringify(message));\n },\n destroy() {\n socket.close();\n error$.complete();\n connect$.complete();\n disconnect$.complete();\n message$.complete();\n response$.complete();\n return PROMISE_RESOLVE_VOID;\n }\n };\n return handler;\n };\n return creator;\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAUA;AAKA;AAEA;AACA;AACA;AACO,SAASA,8BAA8B,CAC1CC,SAAiB,EACjBC,IAAU,EACiB;EAC3B,IAAMC,EAAE,GAAGC,OAAO,CAAC,kBAAkB,CAAC;EAGtC,IAAMC,OAAoC,GAAG,SAAvCA,OAAoC,CAAIC,OAAO,EAAK;IACtD,IAAMC,MAAM,GAAGJ,EAAE,CAACF,SAAS,CAAC;IAE5B,IAAMO,MAAM,GAAG,IAAAC,uBAAiB,EAAC,EAAE,CAAC;IACpCF,MAAM,CAACG,IAAI,CAAC,MAAM,EAAE;MAChBC,IAAI,EAAEL,OAAO,CAACM,KAAK;MACnBJ,MAAM,EAANA;IACJ,CAAC,CAAC;IAEF,IAAMK,QAAQ,GAAG,IAAIC,aAAO,EAAW;IACvC,IAAMC,WAAW,GAAG,IAAID,aAAO,EAAW;IAC1C,IAAME,QAAQ,GAAG,IAAIF,aAAO,EAAmB;IAC/C,IAAMG,SAAS,GAAG,IAAIH,aAAO,EAAoB;IACjD,IAAMI,MAAM,GAAG,IAAIJ,aAAO,EAAyB;IAEnD,IAAMK,KAAK,GAAG,IAAIC,GAAG,EAAsB;IAE3Cb,MAAM,CAACc,EAAE,CAAC,QAAQ,EAAE,UAACC,WAAqB,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AC,CAAC;QAEFjB,OAAO,CAACL,EAAE,CAAC,SAAS,EAAE,YAAM;UACxBR,QAAQ,CAACuB,IAAI,CAACV,OAAO,CAAQ;QACjC,CAAC,CAAC;MAEN,CAAC,CAAC;IACN,CAAC,CAAC;IAEFnB,MAAM,CAACc,EAAE,CAAC,QAAQ,EAAE,UAACwB,IAAS,EAAK;MAC/B;MACA,IAAMR,IAAI,GAAG,IAAAS,uBAAiB,EAAC3B,KAAK,EAAE0B,IAAI,CAACJ,IAAI,CAAC;MAChDJ,IAAI,CAACG,MAAM,CAACK,IAAI,CAACL,MAAM,CAAC;IAC5B,CAAC,CAAC;IAEF,IAAMO,OAA6B,GAAG;MAClC7B,MAAM,EAANA,MAAM;MACNL,QAAQ,EAARA,QAAQ;MACRE,WAAW,EAAXA,WAAW;MACXC,QAAQ,EAARA,QAAQ;MACRC,SAAS,EAATA,SAAS;MACH+B,IAAI,gBAACX,IAAa,EAAEE,OAAmB;QAAA,IAAE;UAAA,uBACpCF,IAAI,CAASW,IAAI,CAAChB,IAAI,CAACiB,SAAS,CAACV,OAAO,CAAC,CAAC;QACrD,CAAC;UAAA;QAAA;MAAA;MACDW,OAAO,qBAAG;QACN3C,MAAM,CAAC4C,KAAK,EAAE;QACdjC,MAAM,CAACkC,QAAQ,EAAE;QACjBvC,QAAQ,CAACuC,QAAQ,EAAE;QACnBrC,WAAW,CAACqC,QAAQ,EAAE;QACtBpC,QAAQ,CAACoC,QAAQ,EAAE;QACnBnC,SAAS,CAACmC,QAAQ,EAAE;QACpB,OAAOC,0BAAoB;MAC/B;IACJ,CAAC;IACD,OAAON,OAAO;EAClB,CAAC;EACD,OAAO1C,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"connection-handler-simple-peer.js","names":["getConnectionHandlerSimplePeer","serverUrl","wrtc","io","require","creator","options","socket","peerId","randomCouchString","emit","room","topic","connect$","Subject","disconnect$","message$","response$","error$","peers","Map","on","roomPeerIds","forEach","remotePeerId","has","newPeer","Peer","initiator","trickle","set","messageOrResponse","JSON","parse","toString","result","next","peer","response","message","signal","from","to","error","newRxError","data","getFromMapOrThrow","handler","send","stringify","destroy","close","complete","PROMISE_RESOLVE_VOID"],"sources":["../../../../src/plugins/replication-p2p/connection-handler-simple-peer.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport { getFromMapOrThrow, PROMISE_RESOLVE_VOID, randomCouchString } from '../../plugins/utils';\nimport type {\n P2PConnectionHandler,\n P2PConnectionHandlerCreator,\n P2PMessage,\n P2PPeer,\n PeerWithMessage,\n PeerWithResponse\n} from './p2p-types';\n\nimport {\n Instance as SimplePeer,\n default as Peer\n} from 'simple-peer';\nimport { RxError, RxTypeError } from '../../types';\nimport { newRxError } from '../../rx-error';\n\n/**\n * Returns a connection handler that uses simple-peer and the signaling server.\n */\nexport function getConnectionHandlerSimplePeer(\n serverUrl: string,\n wrtc?: any\n): P2PConnectionHandlerCreator {\n const io = require('socket.io-client');\n\n\n const creator: P2PConnectionHandlerCreator = (options) => {\n const socket = io(serverUrl);\n\n const peerId = randomCouchString(10);\n socket.emit('join', {\n room: options.topic,\n peerId\n });\n\n const connect$ = new Subject();\n const disconnect$ = new Subject();\n const message$ = new Subject();\n const response$ = new Subject();\n const error$ = new Subject();\n\n const peers = new Map();\n\n socket.on('joined', (roomPeerIds: string[]) => {\n roomPeerIds.forEach(remotePeerId => {\n if (\n remotePeerId === peerId ||\n peers.has(remotePeerId)\n ) {\n return;\n }\n // console.log('other user joined room ' + remotePeerId);\n const newPeer: SimplePeer = new Peer({\n initiator: remotePeerId > peerId,\n wrtc,\n trickle: true\n }) as any;\n peers.set(remotePeerId, newPeer);\n\n\n newPeer.on('data', (messageOrResponse: any) => {\n messageOrResponse = JSON.parse(messageOrResponse.toString());\n // console.log('got a message from peer3: ' + messageOrResponse)\n if (messageOrResponse.result) {\n response$.next({\n peer: newPeer as any,\n response: messageOrResponse\n });\n } else {\n message$.next({\n peer: newPeer as any,\n message: messageOrResponse\n });\n }\n });\n\n newPeer.on('signal', (signal: any) => {\n // console.log('emit signal from ' + peerId + ' to ' + remotePeerId);\n socket.emit('signal', {\n from: peerId,\n to: remotePeerId,\n room: options.topic,\n signal\n });\n });\n\n newPeer.on('error', (error) => {\n error$.next(newRxError('RC_P2P_PEER', {\n error\n }));\n });\n\n newPeer.on('connect', () => {\n connect$.next(newPeer as any);\n });\n\n });\n });\n\n socket.on('signal', (data: any) => {\n // console.log('got signal(' + peerId + ') ' + data.from + ' -> ' + data.to);\n const peer = getFromMapOrThrow(peers, data.from);\n peer.signal(data.signal);\n });\n\n const handler: P2PConnectionHandler = {\n error$,\n connect$,\n disconnect$,\n message$,\n response$,\n async send(peer: P2PPeer, message: P2PMessage) {\n await (peer as any).send(JSON.stringify(message));\n },\n destroy() {\n socket.close();\n error$.complete();\n connect$.complete();\n disconnect$.complete();\n message$.complete();\n response$.complete();\n return PROMISE_RESOLVE_VOID;\n }\n };\n return handler;\n };\n return creator;\n}\n"],"mappings":";;;;;;;;;AAAA;AACA;AAUA;AAKA;AAEA;AACA;AACA;AACO,SAASA,8BAA8B,CAC1CC,SAAiB,EACjBC,IAAU,EACiB;EAC3B,IAAMC,EAAE,GAAGC,OAAO,CAAC,kBAAkB,CAAC;EAGtC,IAAMC,OAAoC,GAAG,SAAvCA,OAAoC,CAAIC,OAAO,EAAK;IACtD,IAAMC,MAAM,GAAGJ,EAAE,CAACF,SAAS,CAAC;IAE5B,IAAMO,MAAM,GAAG,IAAAC,wBAAiB,EAAC,EAAE,CAAC;IACpCF,MAAM,CAACG,IAAI,CAAC,MAAM,EAAE;MAChBC,IAAI,EAAEL,OAAO,CAACM,KAAK;MACnBJ,MAAM,EAANA;IACJ,CAAC,CAAC;IAEF,IAAMK,QAAQ,GAAG,IAAIC,aAAO,EAAW;IACvC,IAAMC,WAAW,GAAG,IAAID,aAAO,EAAW;IAC1C,IAAME,QAAQ,GAAG,IAAIF,aAAO,EAAmB;IAC/C,IAAMG,SAAS,GAAG,IAAIH,aAAO,EAA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ACD,OAAO1C,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-p2p/index.js b/dist/lib/plugins/replication-p2p/index.js index 63198c2407e..8c34345142d 100644 --- a/dist/lib/plugins/replication-p2p/index.js +++ b/dist/lib/plugins/replication-p2p/index.js @@ -1,18 +1,21 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { - syncP2P: true, - RxP2PReplicationPool: true, - RxDBReplicationP2PPlugin: true + replicateP2P: true, + RxP2PReplicationPool: true }; -exports.syncP2P = exports.RxP2PReplicationPool = exports.RxDBReplicationP2PPlugin = void 0; +exports.RxP2PReplicationPool = void 0; +exports.replicateP2P = replicateP2P; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _plugin = require("../../plugin"); var _replicationProtocol = require("../../replication-protocol"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _leaderElection = require("../leader-election"); var _replication = require("../replication"); var _p2pHelper = require("./p2p-helper"); @@ -51,178 +54,233 @@ Object.keys(_connectionHandlerSimplePeer).forEach(function (key) { } }); }); -var syncP2P = function syncP2P(options) { - try { - var _temp2 = function _temp2() { - // used to easier debug stuff - var requestCounter = 0; - function getRequestId() { - var count = requestCounter++; - return _collection.database.token + '|' + requestFlag + '|' + count; - } - var requestFlag = (0, _util.randomCouchString)(10); - return Promise.resolve(_this.database.storageToken).then(function (storageToken) { - var pool = new RxP2PReplicationPool(_this, options, options.connectionHandlerCreator(options)); - pool.subs.push(pool.connectionHandler.error$.subscribe(function (err) { - return pool.error$.next(err); - }), pool.connectionHandler.disconnect$.subscribe(function (peer) { - return pool.removePeer(peer); - })); +function replicateP2P(_x) { + return _replicateP2P.apply(this, arguments); +} +/** + * Because the P2P replication runs between many instances, + * we use a Pool instead of returning a single replication state. + */ +function _replicateP2P() { + _replicateP2P = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(options) { + var collection, requestCounter, requestFlag, getRequestId, storageToken, pool, connectSub; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + getRequestId = function _getRequestId() { + var count = requestCounter++; + return collection.database.token + '|' + requestFlag + '|' + count; + }; + collection = options.collection; + (0, _plugin.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); - /** - * Answer if someone requests our storage token - */ - pool.subs.push(pool.connectionHandler.message$.pipe((0, _rxjs.filter)(function (data) { - return data.message.method === 'token'; - })).subscribe(function (data) { - pool.connectionHandler.send(data.peer, { - id: data.message.id, - result: storageToken - }); - })); - var connectSub = pool.connectionHandler.connect$.pipe((0, _rxjs.filter)(function () { - return !pool.canceled; - })).subscribe(function (peer) { - try { - /** - * TODO ensure both know the correct secret - */ - return Promise.resolve((0, _p2pHelper.sendMessageAndAwaitAnswer)(pool.connectionHandler, peer, { - id: getRequestId(), - method: 'token', - params: [] - })).then(function (tokenResponse) { - var peerToken = tokenResponse.result; - var isMaster = (0, _p2pHelper.isMasterInP2PReplication)(_this.database.hashFunction, storageToken, peerToken); - var replicationState; - if (isMaster) { - var masterHandler = pool.masterReplicationHandler; - var masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(function (ev) { - var streamResponse = { - id: 'masterChangeStream$', - result: ev - }; - pool.connectionHandler.send(peer, streamResponse); - }); + // fill defaults + if (options.pull) { + if (!options.pull.batchSize) { + options.pull.batchSize = 20; + } + } + if (options.push) { + if (!options.push.batchSize) { + options.push.batchSize = 20; + } + } + if (!collection.database.multiInstance) { + _context6.next = 8; + break; + } + _context6.next = 8; + return collection.database.waitForLeadership(); + case 8: + // used to easier debug stuff + requestCounter = 0; + requestFlag = (0, _utils.randomCouchString)(10); + _context6.next = 12; + return collection.database.storageToken; + case 12: + storageToken = _context6.sent; + pool = new RxP2PReplicationPool(collection, options, options.connectionHandlerCreator(options)); + pool.subs.push(pool.connectionHandler.error$.subscribe(function (err) { + return pool.error$.next(err); + }), pool.connectionHandler.disconnect$.subscribe(function (peer) { + return pool.removePeer(peer); + })); - // clean up the subscription - pool.subs.push(masterChangeStreamSub, pool.connectionHandler.disconnect$.pipe((0, _rxjs.filter)(function (p) { - return p.id === peer.id; - })).subscribe(function () { - return masterChangeStreamSub.unsubscribe(); - })); - var messageSub = pool.connectionHandler.message$.pipe((0, _rxjs.filter)(function (data) { - return data.peer.id === peer.id; - }), (0, _rxjs.filter)(function (data) { - return data.message.method !== 'token'; - })).subscribe(function (data) { - try { - var msgPeer = data.peer, - message = data.message; - /** - * If it is not a function, - * it means that the client requested the masterChangeStream$ - */ - var method = masterHandler[message.method].bind(masterHandler); - return Promise.resolve(method.apply(void 0, message.params)).then(function (result) { - var response = { - id: message.id, - result: result - }; - pool.connectionHandler.send(msgPeer, response); + /** + * Answer if someone requests our storage token + */ + pool.subs.push(pool.connectionHandler.message$.pipe((0, _rxjs.filter)(function (data) { + return data.message.method === 'token'; + })).subscribe(function (data) { + pool.connectionHandler.send(data.peer, { + id: data.message.id, + result: storageToken + }); + })); + connectSub = pool.connectionHandler.connect$.pipe((0, _rxjs.filter)(function () { + return !pool.canceled; + })).subscribe( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(peer) { + var tokenResponse, peerToken, isMaster, replicationState, masterHandler, masterChangeStreamSub, messageSub; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return (0, _p2pHelper.sendMessageAndAwaitAnswer)(pool.connectionHandler, peer, { + id: getRequestId(), + method: 'token', + params: [] }); - } catch (e) { - return Promise.reject(e); - } - }); - pool.subs.push(messageSub); - } else { - replicationState = (0, _replication.replicateRxCollection)({ - replicationIdentifier: [_this.name, options.topic, peerToken].join('||'), - collection: _this, - autoStart: true, - deletedField: '_deleted', - live: true, - retryTime: options.retryTime, - waitForLeadership: false, - pull: options.pull ? Object.assign({}, options.pull, { - handler: function handler(lastPulledCheckpoint) { - try { - return Promise.resolve((0, _p2pHelper.sendMessageAndAwaitAnswer)(pool.connectionHandler, peer, { - method: 'masterChangesSince', - params: [lastPulledCheckpoint, (0, _util.ensureNotFalsy)(options.pull).batchSize], - id: getRequestId() - })).then(function (answer) { - return answer.result; - }); - } catch (e) { - return Promise.reject(e); - } - }, - stream$: pool.connectionHandler.response$.pipe((0, _rxjs.filter)(function (m) { - return m.response.id === 'masterChangeStream$'; - }), (0, _rxjs.map)(function (m) { - return m.response.result; - })) - }) : undefined, - push: options.push ? Object.assign({}, options.push, { - handler: function handler(docs) { - try { - return Promise.resolve((0, _p2pHelper.sendMessageAndAwaitAnswer)(pool.connectionHandler, peer, { - method: 'masterWrite', - params: [docs], - id: getRequestId() - })).then(function (answer) { - return answer.result; - }); - } catch (e) { - return Promise.reject(e); - } + case 2: + tokenResponse = _context5.sent; + peerToken = tokenResponse.result; + isMaster = (0, _p2pHelper.isMasterInP2PReplication)(collection.database.hashFunction, storageToken, peerToken); + if (isMaster) { + masterHandler = pool.masterReplicationHandler; + masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(function (ev) { + var streamResponse = { + id: 'masterChangeStream$', + result: ev + }; + pool.connectionHandler.send(peer, streamResponse); + }); // clean up the subscription + pool.subs.push(masterChangeStreamSub, pool.connectionHandler.disconnect$.pipe((0, _rxjs.filter)(function (p) { + return p.id === peer.id; + })).subscribe(function () { + return masterChangeStreamSub.unsubscribe(); + })); + messageSub = pool.connectionHandler.message$.pipe((0, _rxjs.filter)(function (data) { + return data.peer.id === peer.id; + }), (0, _rxjs.filter)(function (data) { + return data.message.method !== 'token'; + })).subscribe( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(data) { + var msgPeer, message, method, result, response; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + msgPeer = data.peer, message = data.message; + /** + * If it is not a function, + * it means that the client requested the masterChangeStream$ + */ + method = masterHandler[message.method].bind(masterHandler); + _context2.next = 4; + return method.apply(void 0, message.params); + case 4: + result = _context2.sent; + response = { + id: message.id, + result: result + }; + pool.connectionHandler.send(msgPeer, response); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }()); + pool.subs.push(messageSub); + } else { + replicationState = (0, _replication.replicateRxCollection)({ + replicationIdentifier: [collection.name, options.topic, peerToken].join('||'), + collection: collection, + autoStart: true, + deletedField: '_deleted', + live: true, + retryTime: options.retryTime, + waitForLeadership: false, + pull: options.pull ? Object.assign({}, options.pull, { + handler: function () { + var _handler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(lastPulledCheckpoint) { + var answer; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _p2pHelper.sendMessageAndAwaitAnswer)(pool.connectionHandler, peer, { + method: 'masterChangesSince', + params: [lastPulledCheckpoint, (0, _utils.ensureNotFalsy)(options.pull).batchSize], + id: getRequestId() + }); + case 2: + answer = _context3.sent; + return _context3.abrupt("return", answer.result); + case 4: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function handler(_x4) { + return _handler.apply(this, arguments); + } + return handler; + }(), + stream$: pool.connectionHandler.response$.pipe((0, _rxjs.filter)(function (m) { + return m.response.id === 'masterChangeStream$'; + }), (0, _rxjs.map)(function (m) { + return m.response.result; + })) + }) : undefined, + push: options.push ? Object.assign({}, options.push, { + handler: function () { + var _handler2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(docs) { + var answer; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return (0, _p2pHelper.sendMessageAndAwaitAnswer)(pool.connectionHandler, peer, { + method: 'masterWrite', + params: [docs], + id: getRequestId() + }); + case 2: + answer = _context4.sent; + return _context4.abrupt("return", answer.result); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + function handler(_x5) { + return _handler2.apply(this, arguments); + } + return handler; + }() + }) : undefined + }); } - }) : undefined - }); - } - pool.addPeer(peer, replicationState); - }); - } catch (e) { - return Promise.reject(e); - } - }); - pool.subs.push(connectSub); - return pool; - }); - }; - var _this = this; - // fill defaults - if (options.pull) { - if (!options.pull.batchSize) { - options.pull.batchSize = 20; - } - } - if (options.push) { - if (!options.push.batchSize) { - options.push.batchSize = 20; - } - } - var _collection = _this; - var _temp = function () { - if (_this.database.multiInstance) { - return Promise.resolve(_this.database.waitForLeadership()).then(function () {}); + pool.addPeer(peer, replicationState); + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x2) { + return _ref.apply(this, arguments); + }; + }()); + pool.subs.push(connectSub); + return _context6.abrupt("return", pool); + case 19: + case "end": + return _context6.stop(); } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp)); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Because the P2P replication runs between many instances, - * we use a Pool instead of returning a single replication state. - */ -exports.syncP2P = syncP2P; + }, _callee6); + })); + return _replicateP2P.apply(this, arguments); +} var RxP2PReplicationPool = /*#__PURE__*/function () { function RxP2PReplicationPool(collection, options, connectionHandler) { - var _this2 = this; + var _this = this; this.peerStates$ = new _rxjs.BehaviorSubject(new Map()); this.canceled = false; this.subs = []; @@ -231,13 +289,13 @@ var RxP2PReplicationPool = /*#__PURE__*/function () { this.options = options; this.connectionHandler = connectionHandler; this.collection.onDestroy.push(function () { - return _this2.cancel(); + return _this.cancel(); }); - this.masterReplicationHandler = (0, _replicationProtocol.rxStorageInstanceToReplicationHandler)(collection.storageInstance, collection.conflictHandler, collection.database.hashFunction); + this.masterReplicationHandler = (0, _replicationProtocol.rxStorageInstanceToReplicationHandler)(collection.storageInstance, collection.conflictHandler, collection.database.token); } var _proto = RxP2PReplicationPool.prototype; _proto.addPeer = function addPeer(peer, replicationState) { - var _this3 = this; + var _this2 = this; var peerState = { peer: peer, replicationState: replicationState, @@ -246,12 +304,12 @@ var RxP2PReplicationPool = /*#__PURE__*/function () { this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState)); if (replicationState) { peerState.subs.push(replicationState.error$.subscribe(function (ev) { - return _this3.error$.next(ev); + return _this2.error$.next(ev); })); } }; _proto.removePeer = function removePeer(peer) { - var peerState = (0, _util.getFromMapOrThrow)(this.peerStates$.getValue(), peer); + var peerState = (0, _utils.getFromMapOrThrow)(this.peerStates$.getValue(), peer); this.peerStates$.getValue()["delete"](peer); this.peerStates$.next(this.peerStates$.getValue()); peerState.subs.forEach(function (sub) { @@ -269,38 +327,39 @@ var RxP2PReplicationPool = /*#__PURE__*/function () { return peerStates.size > 0; }))); }; - _proto.cancel = function cancel() { - try { - var _this4 = this; - if (_this4.canceled) { - return Promise.resolve(); - } - _this4.canceled = true; - _this4.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - Array.from(_this4.peerStates$.getValue().keys()).forEach(function (peer) { - _this4.removePeer(peer); - }); - return Promise.resolve(_this4.connectionHandler.destroy()).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto.cancel = /*#__PURE__*/function () { + var _cancel = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _this3 = this; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!this.canceled) { + _context.next = 2; + break; + } + return _context.abrupt("return"); + case 2: + this.canceled = true; + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + Array.from(this.peerStates$.getValue().keys()).forEach(function (peer) { + _this3.removePeer(peer); + }); + _context.next = 7; + return this.connectionHandler.destroy(); + case 7: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function cancel() { + return _cancel.apply(this, arguments); } - }; + return cancel; + }(); return RxP2PReplicationPool; }(); exports.RxP2PReplicationPool = RxP2PReplicationPool; -var RxDBReplicationP2PPlugin = { - name: 'replication-p2p', - init: function init() { - (0, _plugin.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); - }, - rxdb: true, - prototypes: { - RxCollection: function RxCollection(proto) { - proto.syncP2P = syncP2P; - } - } -}; -exports.RxDBReplicationP2PPlugin = RxDBReplicationP2PPlugin; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-p2p/index.js.map b/dist/lib/plugins/replication-p2p/index.js.map index 5afd33d9d21..65719058e48 100644 --- a/dist/lib/plugins/replication-p2p/index.js.map +++ b/dist/lib/plugins/replication-p2p/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["syncP2P","options","requestCounter","getRequestId","count","collection","database","token","requestFlag","randomCouchString","storageToken","pool","RxP2PReplicationPool","connectionHandlerCreator","subs","push","connectionHandler","error$","subscribe","err","next","disconnect$","peer","removePeer","message$","pipe","filter","data","message","method","send","id","result","connectSub","connect$","canceled","sendMessageAndAwaitAnswer","params","tokenResponse","peerToken","isMaster","isMasterInP2PReplication","hashFunction","replicationState","masterHandler","masterReplicationHandler","masterChangeStreamSub","masterChangeStream$","ev","streamResponse","p","unsubscribe","messageSub","msgPeer","bind","response","replicateRxCollection","replicationIdentifier","name","topic","join","autoStart","deletedField","live","retryTime","waitForLeadership","pull","Object","assign","handler","lastPulledCheckpoint","ensureNotFalsy","batchSize","answer","stream$","response$","m","map","undefined","docs","addPeer","multiInstance","peerStates$","BehaviorSubject","Map","Subject","onDestroy","cancel","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","peerState","getValue","set","getFromMapOrThrow","forEach","sub","awaitFirstPeer","firstValueFrom","peerStates","size","Array","from","keys","destroy","RxDBReplicationP2PPlugin","init","addRxPlugin","RxDBLeaderElectionPlugin","rxdb","prototypes","RxCollection","proto"],"sources":["../../../../src/plugins/replication-p2p/index.ts"],"sourcesContent":["import { BehaviorSubject, filter, firstValueFrom, map, Subject, Subscription } from 'rxjs';\nimport { addRxPlugin } from '../../plugin';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport type {\n RxCollection,\n RxError,\n RxPlugin,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxTypeError\n} from '../../types';\nimport { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../util';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport { replicateRxCollection } from '../replication';\nimport { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper';\nimport type {\n P2PConnectionHandler,\n P2PPeer,\n P2PPeerState,\n P2PReplicationCheckpoint,\n P2PResponse,\n RxP2PReplicationState,\n SyncOptionsP2P\n} from './p2p-types';\n\n\nexport async function syncP2P(\n this: RxCollection,\n options: SyncOptionsP2P\n): Promise> {\n\n // fill defaults\n if (options.pull) {\n if (!options.pull.batchSize) {\n options.pull.batchSize = 20;\n }\n }\n if (options.push) {\n if (!options.push.batchSize) {\n options.push.batchSize = 20;\n }\n }\n\n const collection = this;\n if (this.database.multiInstance) {\n await this.database.waitForLeadership();\n }\n\n // used to easier debug stuff\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return collection.database.token + '|' + requestFlag + '|' + count;\n }\n\n const storageToken = await this.database.storageToken;\n const pool = new RxP2PReplicationPool(\n this,\n options,\n options.connectionHandlerCreator(options)\n );\n\n\n pool.subs.push(\n pool.connectionHandler.error$.subscribe(err => pool.error$.next(err)),\n pool.connectionHandler.disconnect$.subscribe(peer => pool.removePeer(peer))\n );\n\n /**\n * Answer if someone requests our storage token\n */\n pool.subs.push(\n pool.connectionHandler.message$.pipe(\n filter(data => data.message.method === 'token')\n ).subscribe(data => {\n pool.connectionHandler.send(data.peer, {\n id: data.message.id,\n result: storageToken\n });\n })\n );\n\n const connectSub = pool.connectionHandler.connect$\n .pipe(\n filter(() => !pool.canceled)\n )\n .subscribe(async (peer) => {\n /**\n * TODO ensure both know the correct secret\n */\n const tokenResponse = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n id: getRequestId(),\n method: 'token',\n params: []\n }\n );\n const peerToken: string = tokenResponse.result;\n const isMaster = isMasterInP2PReplication(this.database.hashFunction, storageToken, peerToken);\n\n let replicationState: RxP2PReplicationState | undefined;\n if (isMaster) {\n const masterHandler = pool.masterReplicationHandler;\n const masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(ev => {\n const streamResponse: P2PResponse = {\n id: 'masterChangeStream$',\n result: ev\n };\n pool.connectionHandler.send(peer, streamResponse);\n });\n\n // clean up the subscription\n pool.subs.push(\n masterChangeStreamSub,\n pool.connectionHandler.disconnect$.pipe(\n filter(p => p.id === peer.id)\n ).subscribe(() => masterChangeStreamSub.unsubscribe())\n );\n\n const messageSub = pool.connectionHandler.message$\n .pipe(\n filter(data => data.peer.id === peer.id),\n filter(data => data.message.method !== 'token')\n )\n .subscribe(async (data) => {\n const { peer: msgPeer, message } = data;\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n const method = (masterHandler as any)[message.method].bind(masterHandler);\n const result = await (method as any)(...message.params);\n const response: P2PResponse = {\n id: message.id,\n result\n };\n pool.connectionHandler.send(msgPeer, response);\n });\n pool.subs.push(messageSub);\n } else {\n replicationState = replicateRxCollection({\n replicationIdentifier: [this.name, options.topic, peerToken].join('||'),\n collection: this,\n autoStart: true,\n deletedField: '_deleted',\n live: true,\n retryTime: options.retryTime,\n waitForLeadership: false,\n pull: options.pull ? Object.assign({}, options.pull, {\n async handler(lastPulledCheckpoint: P2PReplicationCheckpoint) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterChangesSince',\n params: [\n lastPulledCheckpoint,\n ensureNotFalsy(options.pull).batchSize\n ],\n id: getRequestId()\n }\n );\n return answer.result;\n },\n stream$: pool.connectionHandler.response$.pipe(\n filter(m => m.response.id === 'masterChangeStream$'),\n map(m => m.response.result)\n )\n\n }) : undefined,\n push: options.push ? Object.assign({}, options.push, {\n async handler(docs: RxReplicationWriteToMasterRow[]) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterWrite',\n params: [docs],\n id: getRequestId()\n }\n );\n return answer.result;\n }\n }) : undefined\n });\n }\n pool.addPeer(peer, replicationState);\n });\n pool.subs.push(connectSub);\n return pool;\n}\n\n\n/**\n * Because the P2P replication runs between many instances,\n * we use a Pool instead of returning a single replication state.\n */\nexport class RxP2PReplicationPool {\n\n peerStates$: BehaviorSubject>> = new BehaviorSubject(new Map());\n canceled: boolean = false;\n masterReplicationHandler: RxReplicationHandler;\n subs: Subscription[] = [];\n\n public error$ = new Subject();\n\n constructor(\n public readonly collection: RxCollection,\n public readonly options: SyncOptionsP2P,\n public readonly connectionHandler: P2PConnectionHandler\n ) {\n this.collection.onDestroy.push(() => this.cancel());\n this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n collection.database.hashFunction\n );\n }\n\n addPeer(\n peer: P2PPeer,\n replicationState?: RxP2PReplicationState\n ) {\n const peerState: P2PPeerState = {\n peer,\n replicationState,\n subs: []\n };\n this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState));\n if (replicationState) {\n peerState.subs.push(\n replicationState.error$.subscribe(ev => this.error$.next(ev))\n );\n }\n }\n removePeer(peer: P2PPeer) {\n const peerState = getFromMapOrThrow(this.peerStates$.getValue(), peer);\n this.peerStates$.getValue().delete(peer);\n this.peerStates$.next(this.peerStates$.getValue());\n peerState.subs.forEach(sub => sub.unsubscribe());\n if (peerState.replicationState) {\n peerState.replicationState.cancel();\n }\n }\n\n // often used in unit tests\n awaitFirstPeer() {\n return firstValueFrom(\n this.peerStates$.pipe(\n filter(peerStates => peerStates.size > 0)\n )\n );\n }\n\n public async cancel() {\n if (this.canceled) {\n return;\n }\n this.canceled = true;\n this.subs.forEach(sub => sub.unsubscribe());\n Array.from(this.peerStates$.getValue().keys()).forEach(peer => {\n this.removePeer(peer);\n });\n await this.connectionHandler.destroy();\n }\n}\n\n\nexport const RxDBReplicationP2PPlugin: RxPlugin = {\n name: 'replication-p2p',\n init() {\n addRxPlugin(RxDBLeaderElectionPlugin);\n },\n rxdb: true,\n prototypes: {\n RxCollection: (proto: any) => {\n proto.syncP2P = syncP2P;\n }\n }\n};\n\n\nexport * from './p2p-helper';\nexport * from './p2p-types';\n// export * from './connection-handler-webtorrent';\n// export * from './connection-handler-p2pcf';\nexport * from './connection-handler-simple-peer';\n"],"mappings":";;;;;;;;;;;AAAA;AACA;AACA;AASA;AACA;AACA;AACA;AA+QA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAGA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAAiD,IAvQ3BA,OAAO,YAAPA,OAAO,CAEzBC,OAAkC;EAAA,IACM;IAAA;MAmBxC;MACA,IAAIC,cAAc,GAAG,CAAC;MAEtB,SAASC,YAAY,GAAG;QACpB,IAAMC,KAAK,GAAGF,cAAc,EAAE;QAC9B,OAAOG,WAAU,CAACC,QAAQ,CAACC,KAAK,GAAG,GAAG,GAAGC,WAAW,GAAG,GAAG,GAAGJ,KAAK;MACtE;MAJA,IAAMI,WAAW,GAAG,IAAAC,uBAAiB,EAAC,EAAE,CAAC;MAAC,uBAMf,MAAKH,QAAQ,CAACI,YAAY,iBAA/CA,YAAY;QAClB,IAAMC,IAAI,GAAG,IAAIC,oBAAoB,QAEjCX,OAAO,EACPA,OAAO,CAACY,wBAAwB,CAACZ,OAAO,CAAC,CAC5C;QAGDU,IAAI,CAACG,IAAI,CAACC,IAAI,CACVJ,IAAI,CAACK,iBAAiB,CAACC,MA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IAAI;MACpB,OAAKrB,IAAI,CAACiF,OAAO,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAAC7C,WAAW,EAAE;MAAA,EAAC;MAC3CkD,KAAK,CAACC,IAAI,CAAC,OAAKpB,WAAW,CAACU,QAAQ,EAAE,CAACW,IAAI,EAAE,CAAC,CAACR,OAAO,CAAC,UAAAzE,IAAI,EAAI;QAC3D,OAAKC,UAAU,CAACD,IAAI,CAAC;MACzB,CAAC,CAAC;MAAC,uBACG,OAAKN,iBAAiB,CAACwF,OAAO,EAAE;IAC1C,CAAC;MAAA;IAAA;EAAA;EAAA;AAAA;AAAA;AAIE,IAAMC,wBAAkC,GAAG;EAC9C/C,IAAI,EAAE,iBAAiB;EACvBgD,IAAI,kBAAG;IACH,IAAAC,mBAAW,EAACC,wCAAwB,CAAC;EACzC,CAAC;EACDC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,YAAY,EAAE,sBAACC,KAAU,EAAK;MAC1BA,KAAK,CAAChH,OAAO,GAAGA,OAAO;IAC3B;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["replicateP2P","options","getRequestId","count","requestCounter","collection","database","token","requestFlag","addRxPlugin","RxDBLeaderElectionPlugin","pull","batchSize","push","multiInstance","waitForLeadership","randomCouchString","storageToken","pool","RxP2PReplicationPool","connectionHandlerCreator","subs","connectionHandler","error$","subscribe","err","next","disconnect$","peer","removePeer","message$","pipe","filter","data","message","method","send","id","result","connectSub","connect$","canceled","sendMessageAndAwaitAnswer","params","tokenResponse","peerToken","isMaster","isMasterInP2PReplication","hashFunction","masterHandler","masterReplicationHandler","masterChangeStreamSub","masterChangeStream$","ev","streamResponse","p","unsubscribe","messageSub","msgPeer","bind","response","replicationState","replicateRxCollection","replicationIdentifier","name","topic","join","autoStart","deletedField","live","retryTime","Object","assign","handler","lastPulledCheckpoint","ensureNotFalsy","answer","stream$","response$","m","map","undefined","docs","addPeer","peerStates$","BehaviorSubject","Map","Subject","onDestroy","cancel","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","peerState","getValue","set","getFromMapOrThrow","forEach","sub","awaitFirstPeer","firstValueFrom","peerStates","size","Array","from","keys","destroy"],"sources":["../../../../src/plugins/replication-p2p/index.ts"],"sourcesContent":["import {\n BehaviorSubject,\n filter,\n firstValueFrom,\n map,\n Subject,\n Subscription\n} from 'rxjs';\nimport { addRxPlugin } from '../../plugin';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport type {\n RxCollection,\n RxError,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxTypeError\n} from '../../types';\nimport { ensureNotFalsy, getFromMapOrThrow, randomCouchString } from '../../plugins/utils';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport { replicateRxCollection } from '../replication';\nimport { isMasterInP2PReplication, sendMessageAndAwaitAnswer } from './p2p-helper';\nimport type {\n P2PConnectionHandler,\n P2PPeer,\n P2PPeerState,\n P2PReplicationCheckpoint,\n P2PResponse,\n RxP2PReplicationState,\n SyncOptionsP2P\n} from './p2p-types';\n\n\nexport async function replicateP2P(\n options: SyncOptionsP2P\n): Promise> {\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n // fill defaults\n if (options.pull) {\n if (!options.pull.batchSize) {\n options.pull.batchSize = 20;\n }\n }\n if (options.push) {\n if (!options.push.batchSize) {\n options.push.batchSize = 20;\n }\n }\n\n if (collection.database.multiInstance) {\n await collection.database.waitForLeadership();\n }\n\n // used to easier debug stuff\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return collection.database.token + '|' + requestFlag + '|' + count;\n }\n\n const storageToken = await collection.database.storageToken;\n const pool = new RxP2PReplicationPool(\n collection,\n options,\n options.connectionHandlerCreator(options)\n );\n\n\n pool.subs.push(\n pool.connectionHandler.error$.subscribe(err => pool.error$.next(err)),\n pool.connectionHandler.disconnect$.subscribe(peer => pool.removePeer(peer))\n );\n\n /**\n * Answer if someone requests our storage token\n */\n pool.subs.push(\n pool.connectionHandler.message$.pipe(\n filter(data => data.message.method === 'token')\n ).subscribe(data => {\n pool.connectionHandler.send(data.peer, {\n id: data.message.id,\n result: storageToken\n });\n })\n );\n\n const connectSub = pool.connectionHandler.connect$\n .pipe(\n filter(() => !pool.canceled)\n )\n .subscribe(async (peer) => {\n /**\n * TODO ensure both know the correct secret\n */\n const tokenResponse = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n id: getRequestId(),\n method: 'token',\n params: []\n }\n );\n const peerToken: string = tokenResponse.result;\n const isMaster = isMasterInP2PReplication(collection.database.hashFunction, storageToken, peerToken);\n\n let replicationState: RxP2PReplicationState | undefined;\n if (isMaster) {\n const masterHandler = pool.masterReplicationHandler;\n const masterChangeStreamSub = masterHandler.masterChangeStream$.subscribe(ev => {\n const streamResponse: P2PResponse = {\n id: 'masterChangeStream$',\n result: ev\n };\n pool.connectionHandler.send(peer, streamResponse);\n });\n\n // clean up the subscription\n pool.subs.push(\n masterChangeStreamSub,\n pool.connectionHandler.disconnect$.pipe(\n filter(p => p.id === peer.id)\n ).subscribe(() => masterChangeStreamSub.unsubscribe())\n );\n\n const messageSub = pool.connectionHandler.message$\n .pipe(\n filter(data => data.peer.id === peer.id),\n filter(data => data.message.method !== 'token')\n )\n .subscribe(async (data) => {\n const { peer: msgPeer, message } = data;\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n const method = (masterHandler as any)[message.method].bind(masterHandler);\n const result = await (method as any)(...message.params);\n const response: P2PResponse = {\n id: message.id,\n result\n };\n pool.connectionHandler.send(msgPeer, response);\n });\n pool.subs.push(messageSub);\n } else {\n replicationState = replicateRxCollection({\n replicationIdentifier: [collection.name, options.topic, peerToken].join('||'),\n collection: collection,\n autoStart: true,\n deletedField: '_deleted',\n live: true,\n retryTime: options.retryTime,\n waitForLeadership: false,\n pull: options.pull ? Object.assign({}, options.pull, {\n async handler(lastPulledCheckpoint: P2PReplicationCheckpoint) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterChangesSince',\n params: [\n lastPulledCheckpoint,\n ensureNotFalsy(options.pull).batchSize\n ],\n id: getRequestId()\n }\n );\n return answer.result;\n },\n stream$: pool.connectionHandler.response$.pipe(\n filter(m => m.response.id === 'masterChangeStream$'),\n map(m => m.response.result)\n )\n\n }) : undefined,\n push: options.push ? Object.assign({}, options.push, {\n async handler(docs: RxReplicationWriteToMasterRow[]) {\n const answer = await sendMessageAndAwaitAnswer(\n pool.connectionHandler,\n peer,\n {\n method: 'masterWrite',\n params: [docs],\n id: getRequestId()\n }\n );\n return answer.result;\n }\n }) : undefined\n });\n }\n pool.addPeer(peer, replicationState);\n });\n pool.subs.push(connectSub);\n return pool;\n}\n\n\n/**\n * Because the P2P replication runs between many instances,\n * we use a Pool instead of returning a single replication state.\n */\nexport class RxP2PReplicationPool {\n\n peerStates$: BehaviorSubject>> = new BehaviorSubject(new Map());\n canceled: boolean = false;\n masterReplicationHandler: RxReplicationHandler;\n subs: Subscription[] = [];\n\n public error$ = new Subject();\n\n constructor(\n public readonly collection: RxCollection,\n public readonly options: SyncOptionsP2P,\n public readonly connectionHandler: P2PConnectionHandler\n ) {\n this.collection.onDestroy.push(() => this.cancel());\n this.masterReplicationHandler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n collection.database.token,\n );\n }\n\n addPeer(\n peer: P2PPeer,\n replicationState?: RxP2PReplicationState\n ) {\n const peerState: P2PPeerState = {\n peer,\n replicationState,\n subs: []\n };\n this.peerStates$.next(this.peerStates$.getValue().set(peer, peerState));\n if (replicationState) {\n peerState.subs.push(\n replicationState.error$.subscribe(ev => this.error$.next(ev))\n );\n }\n }\n removePeer(peer: P2PPeer) {\n const peerState = getFromMapOrThrow(this.peerStates$.getValue(), peer);\n this.peerStates$.getValue().delete(peer);\n this.peerStates$.next(this.peerStates$.getValue());\n peerState.subs.forEach(sub => sub.unsubscribe());\n if (peerState.replicationState) {\n peerState.replicationState.cancel();\n }\n }\n\n // often used in unit tests\n awaitFirstPeer() {\n return firstValueFrom(\n this.peerStates$.pipe(\n filter(peerStates => peerStates.size > 0)\n )\n );\n }\n\n public async cancel() {\n if (this.canceled) {\n return;\n }\n this.canceled = true;\n this.subs.forEach(sub => sub.unsubscribe());\n Array.from(this.peerStates$.getValue().keys()).forEach(peer => {\n this.removePeer(peer);\n });\n await this.connectionHandler.destroy();\n }\n}\n\nexport * from './p2p-helper';\nexport * from './p2p-types';\n// export * from './connection-handler-webtorrent';\n// export * from './connection-handler-p2pcf';\nexport * from './connection-handler-simple-peer';\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAQA;AACA;AAQA;AACA;AACA;AACA;AAgQA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAGA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAAiD,SAxP3BA,YAAY;EAAA;AAAA;AA0KlC;AACA;AACA;AACA;AAHA;EAAA,8FA1KO,kBACHC,OAAkC;IAAA,6CAwBzBC,YAAY;IAAA;MAAA;QAAA;UAAZA,YAAY,4BAAG;YACpB,IAAMC,KAAK,GAAGC,cAAc,EAAE;YAC9B,OAAOC,UAAU,CAACC,QAAQ,CAACC,KAAK,GAAG,GAAG,GAAGC,WAAW,GAAG,GAAG,GAAGL,KAAK;UACtE,CAAC;UAzBKE,UAAU,GAAGJ,OAAO,CAACI,UAAU;UACrC,IAAAI,mBAAW,EAACC,wCAAwB,CAAC;;UAErC;UACA,IAAIT,OAAO,CAACU,IAAI,EAAE;YACd,IAAI,CAACV,OAAO,CAACU,IAAI,CAACC,SAAS,EAAE;cACzBX,OAAO,CAACU,IAAI,CAACC,SAAS,GAAG,EAAE;YAC/B;U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MAAM,EAAE;IACvC;EACJ;;EAEA;EAAA;EAAA,OACAU,cAAc,GAAd,0BAAiB;IACb,OAAO,IAAAC,oBAAc,EACjB,IAAI,CAAChB,WAAW,CAACrD,IAAI,CACjB,IAAAC,YAAM,EAAC,UAAAqE,UAAU;MAAA,OAAIA,UAAU,CAACC,IAAI,GAAG,CAAC;IAAA,EAAC,CAC5C,CACJ;EACL,CAAC;EAAA,OAEYb,MAAM;IAAA,4FAAnB;MAAA;MAAA;QAAA;UAAA;YAAA,KACQ,IAAI,CAAChD,QAAQ;cAAA;cAAA;YAAA;YAAA;UAAA;YAGjB,IAAI,CAACA,QAAQ,GAAG,IAAI;YACpB,IAAI,CAACpB,IAAI,CAAC4E,OAAO,CAAC,UAAAC,GAAG;cAAA,OAAIA,GAAG,CAAC1C,WAAW,EAAE;YAAA,EAAC;YAC3C+C,KAAK,CAACC,IAAI,CAAC,IAAI,CAACpB,WAAW,CAACU,QAAQ,EAAE,CAACW,IAAI,EAAE,CAAC,CAACR,OAAO,CAAC,UAAArE,IAAI,EAAI;cAC3D,MAAI,CAACC,UAAU,CAACD,IAAI,CAAC;YACzB,CAAC,CAAC;YAAC;YAAA,OACG,IAAI,CAACN,iBAAiB,CAACoF,OAAO,EAAE;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACzC;IAAA;MAAA;IAAA;IAAA;EAAA;EAAA;AAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-p2p/p2p-types.js.map b/dist/lib/plugins/replication-p2p/p2p-types.js.map index 19e141004e2..bf9948a6b0a 100644 --- a/dist/lib/plugins/replication-p2p/p2p-types.js.map +++ b/dist/lib/plugins/replication-p2p/p2p-types.js.map @@ -1 +1 @@ -{"version":3,"file":"p2p-types.js","names":[],"sources":["../../../../src/plugins/replication-p2p/p2p-types.ts"],"sourcesContent":["import { Observable, Subscription } from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxError,\n RxReplicationHandler,\n RxStorageDefaultCheckpoint,\n RxTypeError,\n StringKeys\n} from '../../types';\nimport { RxReplicationState } from '../replication';\nimport { WebsocketMessageResponseType, WebsocketMessageType } from '../replication-websocket';\n\nexport type P2PPeer = {\n id: string;\n};\nexport type P2PReplicationCheckpoint = RxStorageDefaultCheckpoint;\n\n\nexport type P2PMessage = Omit & {\n method: StringKeys> | 'token';\n};\nexport type P2PResponse = Omit;\nexport type PeerWithMessage = {\n peer: P2PPeer;\n message: P2PMessage;\n};\nexport type PeerWithResponse = {\n peer: P2PPeer;\n response: P2PResponse;\n};\n\nexport type P2PConnectionHandler = {\n connect$: Observable;\n disconnect$: Observable;\n message$: Observable;\n response$: Observable;\n error$: Observable;\n send(peer: P2PPeer, message: P2PMessage | P2PResponse): Promise;\n destroy(): Promise;\n};\n\nexport type P2PConnectionHandlerCreator = (\n opts: SyncOptionsP2P\n) => P2PConnectionHandler;\n\nexport type P2PSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {};\n\nexport type P2PSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {};\n\nexport type SyncOptionsP2P = Omit<\nReplicationOptions,\n'pull' |\n'push' |\n'replicationIdentifier' |\n'collection' |\n'deletedField' |\n'live' |\n'autostart' |\n'waitForLeadership'\n> & {\n /**\n * It will only replicate with other instances\n * that use the same topic and\n * are able to prove that they know the secret.\n */\n topic: string;\n secret: string;\n connectionHandlerCreator: P2PConnectionHandlerCreator;\n pull?: P2PSyncPullOptions;\n push?: P2PSyncPushOptions;\n};\n\nexport type RxP2PReplicationState = RxReplicationState;\n\n\nexport type P2PPeerState = {\n peer: P2PPeer;\n // only exists when the peer was picked as master and the own client was picked as fork.\n replicationState?: RxP2PReplicationState;\n // clean this up when removing the peer\n subs: Subscription[];\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"p2p-types.js","names":[],"sources":["../../../../src/plugins/replication-p2p/p2p-types.ts"],"sourcesContent":["import { Observable, Subscription } from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxError,\n RxReplicationHandler,\n RxStorageDefaultCheckpoint,\n RxTypeError,\n StringKeys\n} from '../../types';\nimport { RxReplicationState } from '../replication';\nimport { WebsocketMessageResponseType, WebsocketMessageType } from '../replication-websocket';\n\nexport type P2PPeer = {\n id: string;\n};\nexport type P2PReplicationCheckpoint = RxStorageDefaultCheckpoint;\n\n\nexport type P2PMessage = Omit & {\n method: StringKeys> | 'token';\n};\nexport type P2PResponse = Omit;\nexport type PeerWithMessage = {\n peer: P2PPeer;\n message: P2PMessage;\n};\nexport type PeerWithResponse = {\n peer: P2PPeer;\n response: P2PResponse;\n};\n\nexport type P2PConnectionHandler = {\n connect$: Observable;\n disconnect$: Observable;\n message$: Observable;\n response$: Observable;\n error$: Observable;\n send(peer: P2PPeer, message: P2PMessage | P2PResponse): Promise;\n destroy(): Promise;\n};\n\nexport type P2PConnectionHandlerCreator = (\n opts: SyncOptionsP2P\n) => P2PConnectionHandler;\n\nexport type P2PSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {};\n\nexport type P2PSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {};\n\nexport type SyncOptionsP2P = Omit<\nReplicationOptions,\n'pull' |\n'push' |\n'replicationIdentifier' |\n'deletedField' |\n'live' |\n'autostart' |\n'waitForLeadership'\n> & {\n /**\n * It will only replicate with other instances\n * that use the same topic and\n * are able to prove that they know the secret.\n */\n topic: string;\n secret: string;\n connectionHandlerCreator: P2PConnectionHandlerCreator;\n pull?: P2PSyncPullOptions;\n push?: P2PSyncPushOptions;\n};\n\nexport type RxP2PReplicationState = RxReplicationState;\n\n\nexport type P2PPeerState = {\n peer: P2PPeer;\n // only exists when the peer was picked as master and the own client was picked as fork.\n replicationState?: RxP2PReplicationState;\n // clean this up when removing the peer\n subs: Subscription[];\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/replication-websocket/websocket-client.js b/dist/lib/plugins/replication-websocket/websocket-client.js index 7b610bcd490..4d8cb03914d 100644 --- a/dist/lib/plugins/replication-websocket/websocket-client.js +++ b/dist/lib/plugins/replication-websocket/websocket-client.js @@ -4,13 +4,16 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.getWebSocket = exports.WEBSOCKET_BY_CACHE_KEY = void 0; +exports.WEBSOCKET_BY_CACHE_KEY = void 0; +exports.getWebSocket = getWebSocket; exports.removeWebSocketRef = removeWebSocketRef; -exports.replicateWithWebsocketServer = void 0; +exports.replicateWithWebsocketServer = replicateWithWebsocketServer; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _replication = require("../replication"); var _reconnectingWebsocket = _interopRequireDefault(require("reconnecting-websocket")); var _isomorphicWs = _interopRequireDefault(require("isomorphic-ws")); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _rxjs = require("rxjs"); var _rxError = require("../../rx-error"); /** @@ -31,169 +34,86 @@ function ensureIsWebsocket(w) { * Reuse the same socket even when multiple * collection replicate with the same server at once. */ -var replicateWithWebsocketServer = function replicateWithWebsocketServer(options) { - try { - return Promise.resolve(getWebSocket(options.url, options.collection.database.token)).then(function (socketState) { - var wsClient = socketState.socket; - var messages$ = socketState.message$; - var requestCounter = 0; - function getRequestId() { - var count = requestCounter++; - return options.collection.database.token + '|' + requestFlag + '|' + count; - } - var requestFlag = (0, _util.randomCouchString)(10); - var replicationState = (0, _replication.replicateRxCollection)({ - collection: options.collection, - replicationIdentifier: 'websocket-' + options.url, - pull: { - batchSize: options.batchSize, - stream$: messages$.pipe((0, _rxjs.filter)(function (msg) { - return msg.id === 'stream' && msg.collection === options.collection.name; - }), (0, _rxjs.map)(function (msg) { - return msg.result; - })), - handler: function handler(lastPulledCheckpoint, batchSize) { - try { - var requestId = getRequestId(); - var request = { - id: requestId, - collection: options.collection.name, - method: 'masterChangesSince', - params: [lastPulledCheckpoint, batchSize] +var WEBSOCKET_BY_CACHE_KEY = new Map(); +exports.WEBSOCKET_BY_CACHE_KEY = WEBSOCKET_BY_CACHE_KEY; +function getWebSocket(_x, _x2) { + return _getWebSocket.apply(this, arguments); +} +function _getWebSocket() { + _getWebSocket = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(url, + /** + * The value of RxDatabase.token. + */ + databaseToken) { + var cacheKey, has, wsClient, connected$, openPromise, message$, error$; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * Also use the database token as cache-key + * to make it easier to test and debug + * multi-instance setups. + */ + cacheKey = url + '|||' + databaseToken; + has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey); + if (!has) { + ensureIsWebsocket(_isomorphicWs["default"]); + wsClient = new _reconnectingWebsocket["default"](url, [], { + WebSocket: _isomorphicWs["default"] + }); + connected$ = new _rxjs.BehaviorSubject(false); + openPromise = new Promise(function (res) { + wsClient.onopen = function () { + connected$.next(true); + res(); }; - wsClient.send(JSON.stringify(request)); - return Promise.resolve((0, _rxjs.firstValueFrom)(messages$.pipe((0, _rxjs.filter)(function (msg) { - return msg.id === requestId; - }), (0, _rxjs.map)(function (msg) { - return msg.result; - })))); - } catch (e) { - return Promise.reject(e); - } - } - }, - push: { - batchSize: options.batchSize, - handler: function handler(docs) { - var requestId = getRequestId(); - var request = { - id: requestId, - collection: options.collection.name, - method: 'masterWrite', - params: [docs] + }); + wsClient.onclose = function () { + connected$.next(false); + }; + message$ = new _rxjs.Subject(); + wsClient.onmessage = function (messageObj) { + var message = JSON.parse(messageObj.data); + message$.next(message); }; - wsClient.send(JSON.stringify(request)); - return (0, _rxjs.firstValueFrom)(messages$.pipe((0, _rxjs.filter)(function (msg) { - return msg.id === requestId; - }), (0, _rxjs.map)(function (msg) { - return msg.result; - }))); + error$ = new _rxjs.Subject(); + wsClient.onerror = function (err) { + var emitError = (0, _rxError.newRxError)('RC_STREAM', { + errors: (0, _utils.toArray)(err).map(function (er) { + return (0, _utils.errorToPlainJson)(er); + }), + direction: 'pull' + }); + error$.next(emitError); + }; + has = { + url: url, + socket: wsClient, + openPromise: openPromise, + refCount: 1, + connected$: connected$, + message$: message$, + error$: error$ + }; + WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has); + } else { + has.refCount = has.refCount + 1; } - } - }); - socketState.error$.subscribe(function (err) { - return replicationState.subjects.error.next(err); - }); - socketState.connected$.subscribe(function (isConnected) { - if (isConnected) { - /** - * When the client goes offline and online again, - * we have to send a 'RESYNC' signal because the client - * might have missed out events while being offline. - */ - replicationState.reSync(); - - /** - * Because reconnecting creates a new websocket-instance, - * we have to start the changestream from the remote again - * each time. - */ - var streamRequest = { - id: 'stream', - collection: options.collection.name, - method: 'masterChangeStream$', - params: [] - }; - wsClient.send(JSON.stringify(streamRequest)); - } - }); - options.collection.onDestroy.push(function () { - return removeWebSocketRef(options.url, options.collection.database); - }); - return replicationState; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.replicateWithWebsocketServer = replicateWithWebsocketServer; -var getWebSocket = function getWebSocket(url, -/** - * The value of RxDatabase.token. - */ -databaseToken) { - try { - /** - * Also use the database token as cache-key - * to make it easier to test and debug - * multi-instance setups. - */ - var cacheKey = url + '|||' + databaseToken; - var has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey); - if (!has) { - ensureIsWebsocket(_isomorphicWs["default"]); - var wsClient = new _reconnectingWebsocket["default"](url, [], { - WebSocket: _isomorphicWs["default"] - }); - var connected$ = new _rxjs.BehaviorSubject(false); - var openPromise = new Promise(function (res) { - wsClient.onopen = function () { - connected$.next(true); - res(); - }; - }); - wsClient.onclose = function () { - connected$.next(false); - }; - var message$ = new _rxjs.Subject(); - wsClient.onmessage = function (messageObj) { - var message = JSON.parse(messageObj.data); - message$.next(message); - }; - var error$ = new _rxjs.Subject(); - wsClient.onerror = function (err) { - var emitError = (0, _rxError.newRxError)('RC_STREAM', { - errors: Array.isArray(err) ? err : [err], - direction: 'pull' - }); - error$.next(emitError); - }; - has = { - url: url, - socket: wsClient, - openPromise: openPromise, - refCount: 1, - connected$: connected$, - message$: message$, - error$: error$ - }; - WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has); - } else { - has.refCount = has.refCount + 1; - } - return Promise.resolve(has.openPromise).then(function () { - return has; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.getWebSocket = getWebSocket; -var WEBSOCKET_BY_CACHE_KEY = new Map(); -exports.WEBSOCKET_BY_CACHE_KEY = WEBSOCKET_BY_CACHE_KEY; + _context.next = 5; + return has.openPromise; + case 5: + return _context.abrupt("return", has); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getWebSocket.apply(this, arguments); +} function removeWebSocketRef(url, database) { var cacheKey = url + '|||' + database.token; - var obj = (0, _util.getFromMapOrThrow)(WEBSOCKET_BY_CACHE_KEY, cacheKey); + var obj = (0, _utils.getFromMapOrThrow)(WEBSOCKET_BY_CACHE_KEY, cacheKey); obj.refCount = obj.refCount - 1; if (obj.refCount === 0) { WEBSOCKET_BY_CACHE_KEY["delete"](cacheKey); @@ -201,4 +121,128 @@ function removeWebSocketRef(url, database) { obj.socket.close(); } } +function replicateWithWebsocketServer(_x3) { + return _replicateWithWebsocketServer.apply(this, arguments); +} +function _replicateWithWebsocketServer() { + _replicateWithWebsocketServer = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(options) { + var socketState, wsClient, messages$, requestCounter, requestFlag, getRequestId, replicationState; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + getRequestId = function _getRequestId() { + var count = requestCounter++; + return options.collection.database.token + '|' + requestFlag + '|' + count; + }; + _context3.next = 3; + return getWebSocket(options.url, options.collection.database.token); + case 3: + socketState = _context3.sent; + wsClient = socketState.socket; + messages$ = socketState.message$; + requestCounter = 0; + requestFlag = (0, _utils.randomCouchString)(10); + replicationState = (0, _replication.replicateRxCollection)({ + collection: options.collection, + replicationIdentifier: 'websocket-' + options.url, + live: options.live, + pull: { + batchSize: options.batchSize, + stream$: messages$.pipe((0, _rxjs.filter)(function (msg) { + return msg.id === 'stream' && msg.collection === options.collection.name; + }), (0, _rxjs.map)(function (msg) { + return msg.result; + })), + handler: function () { + var _handler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(lastPulledCheckpoint, batchSize) { + var requestId, request, result; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + requestId = getRequestId(); + request = { + id: requestId, + collection: options.collection.name, + method: 'masterChangesSince', + params: [lastPulledCheckpoint, batchSize] + }; + wsClient.send(JSON.stringify(request)); + _context2.next = 5; + return (0, _rxjs.firstValueFrom)(messages$.pipe((0, _rxjs.filter)(function (msg) { + return msg.id === requestId; + }), (0, _rxjs.map)(function (msg) { + return msg.result; + }))); + case 5: + result = _context2.sent; + return _context2.abrupt("return", result); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function handler(_x4, _x5) { + return _handler.apply(this, arguments); + } + return handler; + }() + }, + push: { + batchSize: options.batchSize, + handler: function handler(docs) { + var requestId = getRequestId(); + var request = { + id: requestId, + collection: options.collection.name, + method: 'masterWrite', + params: [docs] + }; + wsClient.send(JSON.stringify(request)); + return (0, _rxjs.firstValueFrom)(messages$.pipe((0, _rxjs.filter)(function (msg) { + return msg.id === requestId; + }), (0, _rxjs.map)(function (msg) { + return msg.result; + }))); + } + } + }); + socketState.error$.subscribe(function (err) { + return replicationState.subjects.error.next(err); + }); + socketState.connected$.subscribe(function (isConnected) { + if (isConnected) { + /** + * When the client goes offline and online again, + * we have to send a 'RESYNC' signal because the client + * might have missed out events while being offline. + */ + replicationState.reSync(); + + /** + * Because reconnecting creates a new websocket-instance, + * we have to start the changestream from the remote again + * each time. + */ + var streamRequest = { + id: 'stream', + collection: options.collection.name, + method: 'masterChangeStream$', + params: [] + }; + wsClient.send(JSON.stringify(streamRequest)); + } + }); + options.collection.onDestroy.push(function () { + return removeWebSocketRef(options.url, options.collection.database); + }); + return _context3.abrupt("return", replicationState); + case 13: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _replicateWithWebsocketServer.apply(this, arguments); +} //# sourceMappingURL=websocket-client.js.map \ No newline at end of file diff --git a/dist/lib/plugins/replication-websocket/websocket-client.js.map b/dist/lib/plugins/replication-websocket/websocket-client.js.map index 2ee70e8915a..24d07c3b94b 100644 --- a/dist/lib/plugins/replication-websocket/websocket-client.js.map +++ b/dist/lib/plugins/replication-websocket/websocket-client.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-client.js","names":["ensureIsWebsocket","w","is","CLOSING","console","dir","Error","replicateWithWebsocketServer","options","getWebSocket","url","collection","database","token","socketState","wsClient","socket","messages$","message$","requestCounter","getRequestId","count","requestFlag","randomCouchString","replicationState","replicateRxCollection","replicationIdentifier","pull","batchSize","stream$","pipe","filter","msg","id","name","map","result","handler","lastPulledCheckpoint","requestId","request","method","params","send","JSON","stringify","firstValueFrom","push","docs","error$","subscribe","err","subjects","error","next","connected$","isConnected","reSync","streamRequest","onDestroy","removeWebSocketRef","databaseToken","cacheKey","has","WEBSOCKET_BY_CACHE_KEY","get","IsomorphicWebSocket","ReconnectingWebSocket","WebSocket","BehaviorSubject","openPromise","Promise","res","onopen","onclose","Subject","onmessage","messageObj","message","parse","data","onerror","emitError","newRxError","errors","Array","isArray","direction","refCount","set","Map","obj","getFromMapOrThrow","complete","close"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import { replicateRxCollection, RxReplicationState } from '../replication';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n getFromMapOrThrow,\n randomCouchString\n} from '../../util';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport {\n RxDatabase,\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types';\nimport { newRxError } from '../../rx-error';\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: ReconnectingWebSocket;\n refCount: number;\n openPromise: Promise;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapter from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nfunction ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n/**\n * Reuse the same socket even when multiple\n * collection replicate with the same server at once.\n */\nexport const WEBSOCKET_BY_CACHE_KEY: Map = new Map();\nexport async function getWebSocket(\n url: string,\n /**\n * The value of RxDatabase.token.\n */\n databaseToken: string\n): Promise {\n /**\n * Also use the database token as cache-key\n * to make it easier to test and debug\n * multi-instance setups.\n */\n const cacheKey = url + '|||' + databaseToken;\n\n let has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey);\n if (!has) {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n\n const connected$ = new BehaviorSubject(false);\n const openPromise = new Promise(res => {\n wsClient.onopen = () => {\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n const message$ = new Subject();\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n const emitError = newRxError('RC_STREAM', {\n errors: Array.isArray(err) ? err as any : [err],\n direction: 'pull'\n });\n error$.next(emitError);\n };\n\n\n has = {\n url,\n socket: wsClient,\n openPromise,\n refCount: 1,\n connected$,\n message$,\n error$\n };\n WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n\n\n await has.openPromise;\n return has;\n}\n\nexport function removeWebSocketRef(\n url: string,\n database: RxDatabase\n) {\n const cacheKey = url + '|||' + database.token;\n const obj = getFromMapOrThrow(WEBSOCKET_BY_CACHE_KEY, cacheKey);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n WEBSOCKET_BY_CACHE_KEY.delete(cacheKey);\n obj.connected$.complete();\n obj.socket.close();\n }\n}\n\n\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const socketState = await getWebSocket(options.url, options.collection.database.token);\n const wsClient = socketState.socket;\n\n const messages$ = socketState.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: 'websocket-' + options.url,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n socketState.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n socketState.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => removeWebSocketRef(options.url, options.collection.database));\n return replicationState;\n}\n"],"mappings":";;;;;;;;;AAAA;AAMA;AACA;AACA;AAIA;AAYA;AAaA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,iBAAiB,CAACC,CAA6B,EAAE;EACtD,IAAMC,EAAE,GAAG,OAAOD,CAAC,KAAK,WAAW,IAAI,CAAC,CAACA,CAAC,IAAIA,CAAC,CAACE,OAAO,KAAK,CAAC;EAC7D,IAAI,CAACD,EAAE,EAAE;IACLE,OAAO,CAACC,GAAG,CAACJ,CAAC,CAAC;IACd,MAAM,IAAIK,KAAK,CAAC,qBAAqB,CAAC;EAC1C;AACJ;;AAEA;AACA;AACA;AACA;AAHA,IA4FsBC,4BAA4B,YAA5BA,4BAA4B,CAC9CC,OAA0C;EAAA,IACY;IAAA,uBAC5BC,YAAY,CAACD,OAAO,CAACE,GAAG,EAAEF,OAAO,CAACG,UAAU,CAACC,QAAQ,CAACC,KAAK,CAAC,iBAAhFC,WAAW;MACjB,IAAMC,QAAQ,GAAGD,WAAW,CAACE,MAAM;MAEnC,IAAMC,SAAS,GAAGH,WAAW,CAACI,QAAQ;MAEtC,IAAIC,cAAc,GAAG,CAAC;MAEtB,SAASC,YAAY,GAAG;QACpB,IAAMC,KAAK,GAAGF,cAAc,EAAE;QAC9B,OAAOX,OAAO,CAACG,UAAU,CAAC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,GAAG,CAAC;EAC/B,IAAIG,GAAG,CAACH,QAAQ,KAAK,CAAC,EAAE;IACpBxB,sBAAsB,UAAO,CAACF,QAAQ,CAAC;IACvC6B,GAAG,CAACpC,UAAU,CAACsC,QAAQ,EAAE;IACzBF,GAAG,CAAC3E,MAAM,CAAC8E,KAAK,EAAE;EACtB;AACJ"} \ No newline at end of file +{"version":3,"file":"websocket-client.js","names":["ensureIsWebsocket","w","is","CLOSING","console","dir","Error","WEBSOCKET_BY_CACHE_KEY","Map","getWebSocket","url","databaseToken","cacheKey","has","get","IsomorphicWebSocket","wsClient","ReconnectingWebSocket","WebSocket","connected$","BehaviorSubject","openPromise","Promise","res","onopen","next","onclose","message$","Subject","onmessage","messageObj","message","JSON","parse","data","error$","onerror","err","emitError","newRxError","errors","toArray","map","er","errorToPlainJson","direction","socket","refCount","set","removeWebSocketRef","database","token","obj","getFromMapOrThrow","complete","close","replicateWithWebsocketServer","options","getRequestId","count","requestCounter","collection","requestFlag","socketState","messages$","randomCouchString","replicationState","replicateRxCollection","replicationIdentifier","live","pull","batchSize","stream$","pipe","filter","msg","id","name","result","handler","lastPulledCheckpoint","requestId","request","method","params","send","stringify","firstValueFrom","push","docs","subscribe","subjects","error","isConnected","reSync","streamRequest","onDestroy"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import { replicateRxCollection, RxReplicationState } from '../replication';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n errorToPlainJson,\n getFromMapOrThrow,\n randomCouchString,\n toArray\n} from '../../plugins/utils';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport {\n RxDatabase,\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types';\nimport { newRxError } from '../../rx-error';\n\nexport type WebsocketWithRefCount = {\n url: string;\n socket: ReconnectingWebSocket;\n refCount: number;\n openPromise: Promise;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapter from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nfunction ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n/**\n * Reuse the same socket even when multiple\n * collection replicate with the same server at once.\n */\nexport const WEBSOCKET_BY_CACHE_KEY: Map = new Map();\nexport async function getWebSocket(\n url: string,\n /**\n * The value of RxDatabase.token.\n */\n databaseToken: string\n): Promise {\n /**\n * Also use the database token as cache-key\n * to make it easier to test and debug\n * multi-instance setups.\n */\n const cacheKey = url + '|||' + databaseToken;\n\n let has = WEBSOCKET_BY_CACHE_KEY.get(cacheKey);\n if (!has) {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n\n const connected$ = new BehaviorSubject(false);\n const openPromise = new Promise(res => {\n wsClient.onopen = () => {\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n const message$ = new Subject();\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n const emitError = newRxError('RC_STREAM', {\n errors: toArray(err).map((er: any) => errorToPlainJson(er)),\n direction: 'pull'\n });\n error$.next(emitError);\n };\n\n\n has = {\n url,\n socket: wsClient,\n openPromise,\n refCount: 1,\n connected$,\n message$,\n error$\n };\n WEBSOCKET_BY_CACHE_KEY.set(cacheKey, has);\n } else {\n has.refCount = has.refCount + 1;\n }\n\n\n await has.openPromise;\n return has;\n}\n\nexport function removeWebSocketRef(\n url: string,\n database: RxDatabase\n) {\n const cacheKey = url + '|||' + database.token;\n const obj = getFromMapOrThrow(WEBSOCKET_BY_CACHE_KEY, cacheKey);\n obj.refCount = obj.refCount - 1;\n if (obj.refCount === 0) {\n WEBSOCKET_BY_CACHE_KEY.delete(cacheKey);\n obj.connected$.complete();\n obj.socket.close();\n }\n}\n\n\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const socketState = await getWebSocket(options.url, options.collection.database.token);\n const wsClient = socketState.socket;\n\n const messages$ = socketState.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: 'websocket-' + options.url,\n live: options.live,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n socketState.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n socketState.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => removeWebSocketRef(options.url, options.collection.database));\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAMA;AACA;AACA;AAMA;AAYA;AAaA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,iBAAiB,CAACC,CAA6B,EAAE;EACtD,IAAMC,EAAE,GAAG,OAAOD,CAAC,KAAK,WAAW,IAAI,CAAC,CAACA,CAAC,IAAIA,CAAC,CAACE,OAAO,KAAK,CAAC;EAC7D,IAAI,CAACD,EAAE,EAAE;IACLE,OAAO,CAACC,GAAG,CAACJ,CAAC,CAAC;IACd,MAAM,IAAIK,KAAK,CAAC,qBAAqB,CAAC;EAC1C;AACJ;;AAEA;AACA;AACA;AACA;AACO,IAAMC,sBAA0D,GAAG,IAAIC,GAAG,EAAE;AAAC;AAAA,SAC9DC,YAAY;EAAA;AAAA;AAAA;EAAA,8FAA3B,iBACHC,GAAW;EACX;AACJ;AACA;EACIC,aAAqB;IAAA;IAAA;MAAA;QAAA;UAErB;AACJ;AACA;AACA;AACA;UACUC,QAAQ,GAAGF,GAAG,GAAG,KAAK,GAAGC,aAAa;UAExCE,GAAG,GAAGN,sBAAsB,CAACO,GAAG,CAACF,QAAQ,CAAC;UAC9C,IAAI,CAACC,GAAG,EAAE;YACNb,iBAAiB,CAACe,wBAAmB,CAAC;YAChCC,QAAQ,GAAG,IAAIC,iCAAqB,CACtCP,GAAG,EACH,EAAE,EACF;cACIQ,SAAS,EAAEH;YACf,CAAC,CACJ;YAEKI,UAAU,GAAG,IAAIC,qBAAe,CAAU,KAAK,CAAC;YAChDC,WAAW,GAAG,IAAIC,OAAO,CAAO,UAAA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,IAAI,CAACsD,SAAS,CAACS,aAAa,CAAC,CAAC;YAChD;UACJ,CAAC,CAAC;UAEFtC,OAAO,CAACI,UAAU,CAACmC,SAAS,CAACR,IAAI,CAAC;YAAA,OAAMvC,kBAAkB,CAACQ,OAAO,CAAC/C,GAAG,EAAE+C,OAAO,CAACI,UAAU,CAACX,QAAQ,CAAC;UAAA,EAAC;UAAC,kCAC/FgB,gBAAgB;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAC1B;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-websocket/websocket-server.js b/dist/lib/plugins/replication-websocket/websocket-server.js index e3c7c65fb4d..411ee9eeccc 100644 --- a/dist/lib/plugins/replication-websocket/websocket-server.js +++ b/dist/lib/plugins/replication-websocket/websocket-server.js @@ -1,12 +1,15 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.startSocketServer = startSocketServer; exports.startWebsocketServer = startWebsocketServer; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _replicationProtocol = require("../../replication-protocol"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _rxjs = require("rxjs"); function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } @@ -21,7 +24,7 @@ function startSocketServer(options) { var closed = false; function closeServer() { if (closed) { - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } closed = true; onConnection$.complete(); @@ -70,7 +73,7 @@ function startWebsocketServer(options) { var handler = replicationHandlerByCollection.get(collectionName); if (!handler) { var collection = database.collections[collectionName]; - handler = (0, _replicationProtocol.rxStorageInstanceToReplicationHandler)(collection.storageInstance, collection.conflictHandler, database.hashFunction); + handler = (0, _replicationProtocol.rxStorageInstanceToReplicationHandler)(collection.storageInstance, collection.conflictHandler, database.token); replicationHandlerByCollection.set(collectionName, handler); } return handler; @@ -82,42 +85,56 @@ function startWebsocketServer(options) { return fn(); }); }; - ws.on('message', function (messageString) { - try { - var message = JSON.parse(messageString); - var handler = getReplicationHandler(message.collection); - var method = handler[message.method]; - - /** - * If it is not a function, - * it means that the client requested the masterChangeStream$ - */ - if (typeof method !== 'function') { - var changeStreamSub = handler.masterChangeStream$.subscribe(function (ev) { - var streamResponse = { - id: 'stream', - collection: message.collection, - result: ev - }; - ws.send(JSON.stringify(streamResponse)); - }); - onCloseHandlers.push(function () { - return changeStreamSub.unsubscribe(); - }); - return Promise.resolve(); - } - return Promise.resolve(method.apply(void 0, message.params)).then(function (result) { - var response = { - id: message.id, - collection: message.collection, - result: result - }; - ws.send(JSON.stringify(response)); - }); - } catch (e) { - return Promise.reject(e); - } - }); + ws.on('message', /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(messageString) { + var message, handler, method, changeStreamSub, result, response; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + message = JSON.parse(messageString); + handler = getReplicationHandler(message.collection); + method = handler[message.method]; + /** + * If it is not a function, + * it means that the client requested the masterChangeStream$ + */ + if (!(typeof method !== 'function')) { + _context.next = 7; + break; + } + changeStreamSub = handler.masterChangeStream$.subscribe(function (ev) { + var streamResponse = { + id: 'stream', + collection: message.collection, + result: ev + }; + ws.send(JSON.stringify(streamResponse)); + }); + onCloseHandlers.push(function () { + return changeStreamSub.unsubscribe(); + }); + return _context.abrupt("return"); + case 7: + _context.next = 9; + return method.apply(void 0, message.params); + case 9: + result = _context.sent; + response = { + id: message.id, + collection: message.collection, + result: result + }; + ws.send(JSON.stringify(response)); + case 12: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); }); return serverState; } diff --git a/dist/lib/plugins/replication-websocket/websocket-server.js.map b/dist/lib/plugins/replication-websocket/websocket-server.js.map index 1a14dee5c86..48a000d4af5 100644 --- a/dist/lib/plugins/replication-websocket/websocket-server.js.map +++ b/dist/lib/plugins/replication-websocket/websocket-server.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-server.js","names":["startSocketServer","options","require","WebSocketServer","wss","port","path","closed","closeServer","PROMISE_RESOLVE_VOID","onConnection$","complete","Promise","res","rej","clients","ws","close","err","Subject","on","next","server","asObservable","startWebsocketServer","serverState","database","onDestroy","push","replicationHandlerByCollection","Map","getReplicationHandler","collectionName","collections","Error","handler","get","collection","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","hashFunction","set","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxReplicationHandler\n} from '../../types';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport {\n PROMISE_RESOLVE_VOID\n} from '../../util';\nimport { Subject } from 'rxjs';\n\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const { WebSocketServer } = require('isomorphic-ws' + '');\n const wss = new WebSocketServer({\n port: options.port,\n path: options.path\n });\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const serverState = startSocketServer(options);\n\n const database = options.database;\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n const replicationHandlerByCollection: Map> = new Map();\n function getReplicationHandler(collectionName: string): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n let handler = replicationHandlerByCollection.get(collectionName);\n if (!handler) {\n const collection = database.collections[collectionName];\n handler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.hashFunction\n );\n replicationHandlerByCollection.set(collectionName, handler);\n }\n return handler;\n }\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandler(message.collection);\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":";;;;;;;AAcA;AACA;AAGA;AAA+B;AAAA;AAAA;AAGxB,SAASA,iBAAiB,CAACC,OAAsB,EAAwB;EAC5E,eAA4BC,OAAO,CAAC,eAAe,GAAG,EAAE,CAAC;IAAjDC,eAAe,YAAfA,eAAe;EACvB,IAAMC,GAAG,GAAG,IAAID,eAAe,CAAC;IAC5BE,IAAI,EAAEJ,OAAO,CAACI,IAAI;IAClBC,IAAI,EAAEL,OAAO,CAACK;EAClB,CAAC,CAAC;EACF,IAAIC,MAAM,GAAG,KAAK;EAClB,SAASC,WAAW,GAAG;IACnB,IAAID,MAAM,EAAE;MACR,OAAOE,0BAAoB;IAC/B;IACAF,MAAM,GAAG,IAAI;IACbG,aAAa,CAACC,QAAQ,EAAE;IACxB,OAAO,IAAIC,OAAO,CAAO,UAACC,GAAG,EAAEC,GAAG,EAAK;MACnC;AACZ;AACA;AACA;AACA;MACY,qDAAiBV,GAAG,CAACW,OAAO,wCAAE;QAAA,IAAnBC,EAAE;QACTA,EAAE,CAACC,KAAK,EAAE;MACd;MACAb,GAAG,CAACa,KAAK,CAAC,UAACC,GAAQ,EAAK;QACpB,IAAIA,GAAG,EAAE;UACLJ,GAAG,CAACI,GAAG,CAAC;QACZ,CAAC,MAAM;UACHL,GAAG,EAAE;QACT;MACJ,CAAC,CAAC;IACN,CAAC,CAAC;EACN;EAEA,IAAMH,aAAa,GAAG,IAAIS,aAAO,EAAa;EAC9Cf,GAAG,CAACgB,EAAE,CAAC,YAAY,EAAE,UAACJ,EAAO;I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E;MAAA,EAAC;IACnC,CAAC;IACD/B,EAAE,CAACI,EAAE,CAAC,SAAS,YAAS4B,aAAqB;MAAA,IAAK;QAC9C,IAAMC,OAA6B,GAAGC,IAAI,CAACC,KAAK,CAACH,aAAa,CAAC;QAC/D,IAAMb,OAAO,GAAGJ,qBAAqB,CAACkB,OAAO,CAACZ,UAAU,CAAC;QACzD,IAAMe,MAAM,GAAGjB,OAAO,CAACc,OAAO,CAACG,MAAM,CAAC;;QAEtC;AACZ;AACA;AACA;QACY,IAAI,OAAOA,MAAM,KAAK,UAAU,EAAE;UAC9B,IAAMC,eAAe,GAAGlB,OAAO,CAACmB,mBAAmB,CAACX,SAAS,CAAC,UAAAY,EAAE,EAAI;YAChE,IAAMC,cAA4C,GAAG;cACjDC,EAAE,EAAE,QAAQ;cACZpB,UAAU,EAAEY,OAAO,CAACZ,UAAU;cAC9BqB,MAAM,EAAEH;YACZ,CAAC;YACDvC,EAAE,CAAC2C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACJ,cAAc,CAAC,CAAC;UAC3C,CAAC,CAAC;UACFZ,eAAe,CAAChB,IAAI,CAAC;YAAA,OAAMyB,eAAe,CAACQ,WAAW,EAAE;UAAA,EAAC;UACzD;QACJ;QAAC,uBACqBT,MAAM,eAAYH,OAAO,CAACa,MAAM,CAAC,iBAAjDJ,MAAM;UACZ,IAAMK,QAAsC,GAAG;YAC3CN,EAAE,EAAER,OAAO,CAACQ,EAAE;YACdpB,UAAU,EAAEY,OAAO,CAACZ,UAAU;YAC9BqB,MAAM,EAANA;UACJ,CAAC;UACD1C,EAAE,CAAC2C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;QAAC;MACtC,CAAC;QAAA;MAAA;IAAA,EAAC;EACN,CAAC,CAAC;EAGF,OAAOtC,WAAW;AACtB"} \ No newline at end of file +{"version":3,"file":"websocket-server.js","names":["startSocketServer","options","require","WebSocketServer","wss","port","path","closed","closeServer","PROMISE_RESOLVE_VOID","onConnection$","complete","Promise","res","rej","clients","ws","close","err","Subject","on","next","server","asObservable","startWebsocketServer","serverState","database","onDestroy","push","replicationHandlerByCollection","Map","getReplicationHandler","collectionName","collections","Error","handler","get","collection","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","token","set","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxReplicationHandler\n} from '../../types';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol';\nimport {\n PROMISE_RESOLVE_VOID\n} from '../../plugins/utils';\nimport { Subject } from 'rxjs';\n\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const { WebSocketServer } = require('isomorphic-ws' + '');\n const wss = new WebSocketServer({\n port: options.port,\n path: options.path\n });\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const serverState = startSocketServer(options);\n\n const database = options.database;\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n const replicationHandlerByCollection: Map> = new Map();\n function getReplicationHandler(collectionName: string): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n let handler = replicationHandlerByCollection.get(collectionName);\n if (!handler) {\n const collection = database.collections[collectionName];\n handler = rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.token\n );\n replicationHandlerByCollection.set(collectionName, handler);\n }\n return handler;\n }\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandler(message.collection);\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":";;;;;;;;;;AAcA;AACA;AAGA;AAA+B;AAAA;AAAA;AAGxB,SAASA,iBAAiB,CAACC,OAAsB,EAAwB;EAC5E,eAA4BC,OAAO,CAAC,eAAe,GAAG,EAAE,CAAC;IAAjDC,eAAe,YAAfA,eAAe;EACvB,IAAMC,GAAG,GAAG,IAAID,eAAe,CAAC;IAC5BE,IAAI,EAAEJ,OAAO,CAACI,IAAI;IAClBC,IAAI,EAAEL,OAAO,CAACK;EAClB,CAAC,CAAC;EACF,IAAIC,MAAM,GAAG,KAAK;EAClB,SAASC,WAAW,GAAG;IACnB,IAAID,MAAM,EAAE;MACR,OAAOE,2BAAoB;IAC/B;IACA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ChB,IAAI,CAAC;gBAAA,OAAMyB,eAAe,CAACQ,WAAW,EAAE;cAAA,EAAC;cAAC;YAAA;cAAA;cAAA,OAGxCT,MAAM,eAAYH,OAAO,CAACa,MAAM,CAAC;YAAA;cAAjDJ,MAAM;cACNK,QAAsC,GAAG;gBAC3CN,EAAE,EAAER,OAAO,CAACQ,EAAE;gBACdpB,UAAU,EAAEY,OAAO,CAACZ,UAAU;gBAC9BqB,MAAM,EAANA;cACJ,CAAC;cACD1C,EAAE,CAAC2C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;YAAC;YAAA;cAAA;UAAA;QAAA;MAAA,CACrC;MAAA;QAAA;MAAA;IAAA,IAAC;EACN,CAAC,CAAC;EAGF,OAAOtC,WAAW;AACtB"} \ No newline at end of file diff --git a/dist/lib/plugins/replication-websocket/websocket-types.js.map b/dist/lib/plugins/replication-websocket/websocket-types.js.map index e463e41a496..4125dc4e21f 100644 --- a/dist/lib/plugins/replication-websocket/websocket-types.js.map +++ b/dist/lib/plugins/replication-websocket/websocket-types.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n collection: RxCollection;\n url: string;\n batchSize?: number;\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys>;\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n collection: RxCollection;\n url: string;\n batchSize?: number;\n live?: boolean;\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys>;\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/replication/index.js b/dist/lib/plugins/replication/index.js index e3f65f7147f..975ed634b4c 100644 --- a/dist/lib/plugins/replication/index.js +++ b/dist/lib/plugins/replication/index.js @@ -1,177 +1,22 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RxReplicationState = exports.REPLICATION_STATE_BY_COLLECTION = void 0; exports.replicateRxCollection = replicateRxCollection; exports.startReplicationOnLeaderShip = startReplicationOnLeaderShip; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); -var _util = require("../../util"); +var _leaderElection = require("../leader-election"); +var _utils = require("../../plugins/utils"); var _replicationProtocol = require("../../replication-protocol"); var _rxError = require("../../rx-error"); var _replicationHelper = require("./replication-helper"); var _rxDatabaseInternalStore = require("../../rx-database-internal-store"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} +var _plugin = require("../../plugin"); /** * This plugin contains the primitives to create * a RxDB client-server replication. @@ -244,179 +89,233 @@ var RxReplicationState = /*#__PURE__*/function () { this.startPromise = startPromise; } var _proto = RxReplicationState.prototype; - _proto.start = function start() { - try { + _proto.start = /*#__PURE__*/function () { + var _start = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5() { var _this2 = this; - if (_this2.isStopped()) { - return Promise.resolve(); - } - - // fill in defaults for pull & push - var pullModifier = _this2.pull && _this2.pull.modifier ? _this2.pull.modifier : _replicationHelper.DEFAULT_MODIFIER; - var pushModifier = _this2.push && _this2.push.modifier ? _this2.push.modifier : _replicationHelper.DEFAULT_MODIFIER; - var database = _this2.collection.database; - var metaInstanceCollectionName = _this2.collection.name + '-rx-replication-' + _this2.replicationIdentifierHash; - return Promise.resolve(Promise.all([_this2.collection.database.storage.createStorageInstance({ - databaseName: database.name, - collectionName: metaInstanceCollectionName, - databaseInstanceToken: database.token, - multiInstance: database.multiInstance, - // TODO is this always false? - options: {}, - schema: _replicationProtocol.RX_REPLICATION_META_INSTANCE_SCHEMA - }), (0, _rxDatabaseInternalStore.addConnectedStorageToCollection)(_this2.collection, metaInstanceCollectionName, _replicationProtocol.RX_REPLICATION_META_INSTANCE_SCHEMA)])).then(function (_ref) { - var metaInstance = _ref[0]; - function _temp2() { - _this2.callOnStart(); - } - _this2.metaInstance = metaInstance; - _this2.internalReplicationState = (0, _replicationProtocol.replicateRxStorageInstance)({ - pushBatchSize: _this2.push && _this2.push.batchSize ? _this2.push.batchSize : 100, - pullBatchSize: _this2.pull && _this2.pull.batchSize ? _this2.pull.batchSize : 100, - forkInstance: _this2.collection.storageInstance, - metaInstance: _this2.metaInstance, - hashFunction: database.hashFunction, - identifier: 'rx-replication-' + _this2.replicationIdentifierHash, - conflictHandler: _this2.collection.conflictHandler, - replicationHandler: { - masterChangeStream$: _this2.remoteEvents$.asObservable().pipe((0, _rxjs.mergeMap)(function (ev) { - try { - if (ev === 'RESYNC') { - return Promise.resolve(ev); - } - var useEv = (0, _util.flatClone)(ev); - if (_this2.deletedField !== '_deleted') { - useEv.documents = useEv.documents.map(function (doc) { - return (0, _replicationHelper.swapdeletedFieldToDefaultDeleted)(_this2.deletedField, doc); - }); - } - return Promise.resolve(Promise.all(useEv.documents.map(function (d) { - return pullModifier(d); - }))).then(function (_Promise$all) { - useEv.documents = _Promise$all; - return useEv; - }); - } catch (e) { - return Promise.reject(e); - } - })), - masterChangesSince: function (checkpoint, batchSize) { - try { - var _temp5 = function _temp5() { - if (_this2.isStopped()) { - return { - checkpoint: null, - documents: [] - }; - } - var useResult = (0, _util.flatClone)(result); - if (_this2.deletedField !== '_deleted') { - useResult.documents = useResult.documents.map(function (doc) { - return (0, _replicationHelper.swapdeletedFieldToDefaultDeleted)(_this2.deletedField, doc); - }); - } - return Promise.resolve(Promise.all(useResult.documents.map(function (d) { - return pullModifier(d); - }))).then(function (_Promise$all2) { - useResult.documents = _Promise$all2; - return useResult; - }); - }; - if (!_this2.pull) { - return Promise.resolve({ - checkpoint: null, - documents: [] - }); - } - - /** - * Retries must be done here in the replication primitives plugin, - * because the replication protocol itself has no - * error handling. - */ - var done = false; - var result = {}; - var _temp4 = _for(function () { - return !done && !_this2.isStopped(); - }, void 0, function () { - var _temp3 = _catch(function () { - return Promise.resolve(_this2.pull.handler(checkpoint, batchSize)).then(function (_this2$pull$handler) { - result = _this2$pull$handler; - done = true; - }); - }, function (err) { - var emitError = (0, _rxError.newRxError)('RC_PULL', { - checkpoint: checkpoint, - errors: Array.isArray(err) ? err : [err], - direction: 'pull' - }); - _this2.subjects.error.next(emitError); - return Promise.resolve((0, _replicationHelper.awaitRetry)(_this2.collection, (0, _util.ensureNotFalsy)(_this2.retryTime))).then(function () {}); - }); - if (_temp3 && _temp3.then) return _temp3.then(function () {}); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }, - masterWrite: function (rows) { - try { - if (!_this2.push) { - return Promise.resolve([]); - } - var done = false; - return Promise.resolve(Promise.all(rows.map(function (row) { - try { - return Promise.resolve(pushModifier(row.newDocumentState)).then(function (_pushModifier) { - function _temp9() { - if (_this2.deletedField !== '_deleted') { - row.newDocumentState = (0, _replicationHelper.swapDefaultDeletedTodeletedField)(_this2.deletedField, row.newDocumentState); - if (row.assumedMasterState) { - row.assumedMasterState = (0, _replicationHelper.swapDefaultDeletedTodeletedField)(_this2.deletedField, row.assumedMasterState); + var pullModifier, pushModifier, database, metaInstanceCollectionName, _yield$Promise$all, metaInstance; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!this.isStopped()) { + _context5.next = 2; + break; + } + return _context5.abrupt("return"); + case 2: + // fill in defaults for pull & push + pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : _replicationHelper.DEFAULT_MODIFIER; + pushModifier = this.push && this.push.modifier ? this.push.modifier : _replicationHelper.DEFAULT_MODIFIER; + database = this.collection.database; + metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash; + _context5.next = 8; + return Promise.all([this.collection.database.storage.createStorageInstance({ + databaseName: database.name, + collectionName: metaInstanceCollectionName, + databaseInstanceToken: database.token, + multiInstance: database.multiInstance, + // TODO is this always false? + options: {}, + schema: _replicationProtocol.RX_REPLICATION_META_INSTANCE_SCHEMA + }), (0, _rxDatabaseInternalStore.addConnectedStorageToCollection)(this.collection, metaInstanceCollectionName, _replicationProtocol.RX_REPLICATION_META_INSTANCE_SCHEMA)]); + case 8: + _yield$Promise$all = _context5.sent; + metaInstance = _yield$Promise$all[0]; + this.metaInstance = metaInstance; + this.internalReplicationState = (0, _replicationProtocol.replicateRxStorageInstance)({ + pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100, + pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100, + forkInstance: this.collection.storageInstance, + metaInstance: this.metaInstance, + hashFunction: database.hashFunction, + identifier: 'rx-replication-' + this.replicationIdentifierHash, + conflictHandler: this.collection.conflictHandler, + replicationHandler: { + masterChangeStream$: this.remoteEvents$.asObservable().pipe((0, _rxjs.mergeMap)( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(ev) { + var useEv; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(ev === 'RESYNC')) { + _context.next = 2; + break; + } + return _context.abrupt("return", ev); + case 2: + useEv = (0, _utils.flatClone)(ev); + if (_this2.deletedField !== '_deleted') { + useEv.documents = useEv.documents.map(function (doc) { + return (0, _replicationHelper.swapdeletedFieldToDefaultDeleted)(_this2.deletedField, doc); + }); } - } - return row; + _context.next = 6; + return Promise.all(useEv.documents.map(function (d) { + return pullModifier(d); + })); + case 6: + useEv.documents = _context.sent; + return _context.abrupt("return", useEv); + case 8: + case "end": + return _context.stop(); } - row.newDocumentState = _pushModifier; - var _temp8 = function () { - if (row.assumedMasterState) { - return Promise.resolve(pushModifier(row.assumedMasterState)).then(function (_pushModifier2) { - row.assumedMasterState = _pushModifier2; + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }())), + masterChangesSince: function () { + var _masterChangesSince = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(checkpoint, batchSize) { + var done, result, emitError, useResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (_this2.pull) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", { + checkpoint: null, + documents: [] }); - } - }(); - return _temp8 && _temp8.then ? _temp8.then(_temp9) : _temp9(_temp8); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function (useRows) { - var _exit = false; - function _temp7(_result2) { - if (_exit) return _result2; - if (_this2.isStopped()) { - return []; - } - var conflicts = (0, _util.ensureNotFalsy)(result).map(function (doc) { - return (0, _replicationHelper.swapdeletedFieldToDefaultDeleted)(_this2.deletedField, doc); - }); - return conflicts; + case 2: + /** + * Retries must be done here in the replication primitives plugin, + * because the replication protocol itself has no + * error handling. + */ + done = false; + result = {}; + case 4: + if (!(!done && !_this2.isStopped())) { + _context2.next = 20; + break; + } + _context2.prev = 5; + _context2.next = 8; + return _this2.pull.handler(checkpoint, batchSize); + case 8: + result = _context2.sent; + done = true; + _context2.next = 18; + break; + case 12: + _context2.prev = 12; + _context2.t0 = _context2["catch"](5); + emitError = (0, _rxError.newRxError)('RC_PULL', { + checkpoint: checkpoint, + errors: (0, _utils.toArray)(_context2.t0).map(function (er) { + return (0, _utils.errorToPlainJson)(er); + }), + direction: 'pull' + }); + _this2.subjects.error.next(emitError); + _context2.next = 18; + return (0, _replicationHelper.awaitRetry)(_this2.collection, (0, _utils.ensureNotFalsy)(_this2.retryTime)); + case 18: + _context2.next = 4; + break; + case 20: + if (!_this2.isStopped()) { + _context2.next = 22; + break; + } + return _context2.abrupt("return", { + checkpoint: null, + documents: [] + }); + case 22: + useResult = (0, _utils.flatClone)(result); + if (_this2.deletedField !== '_deleted') { + useResult.documents = useResult.documents.map(function (doc) { + return (0, _replicationHelper.swapdeletedFieldToDefaultDeleted)(_this2.deletedField, doc); + }); + } + _context2.next = 26; + return Promise.all(useResult.documents.map(function (d) { + return pullModifier(d); + })); + case 26: + useResult.documents = _context2.sent; + return _context2.abrupt("return", useResult); + case 28: + case "end": + return _context2.stop(); + } + }, _callee2, null, [[5, 12]]); + })); + function masterChangesSince(_x2, _x3) { + return _masterChangesSince.apply(this, arguments); } - var result = null; - var _temp6 = _for(function () { - return !_exit && !done && !_this2.isStopped(); - }, void 0, function () { - return _catch(function () { - return Promise.resolve(_this2.push.handler(useRows)).then(function (_this2$push$handler) { - result = _this2$push$handler; - /** - * It is a common problem that people have wrongly behaving backend - * that do not return an array with the conflicts on push requests. - * So we run this check here to make it easier to debug. - * @link https://github.com/pubkey/rxdb/issues/4103 - */ - if (!Array.isArray(result)) { + return masterChangesSince; + }(), + masterWrite: function () { + var _masterWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(rows) { + var done, useRows, result, emitError, conflicts; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (_this2.push) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", []); + case 2: + done = false; + _context4.next = 5; + return Promise.all(rows.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(row) { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return pushModifier(row.newDocumentState); + case 2: + row.newDocumentState = _context3.sent; + if (!row.assumedMasterState) { + _context3.next = 7; + break; + } + _context3.next = 6; + return pushModifier(row.assumedMasterState); + case 6: + row.assumedMasterState = _context3.sent; + case 7: + if (_this2.deletedField !== '_deleted') { + row.newDocumentState = (0, _replicationHelper.swapDefaultDeletedTodeletedField)(_this2.deletedField, row.newDocumentState); + if (row.assumedMasterState) { + row.assumedMasterState = (0, _replicationHelper.swapDefaultDeletedTodeletedField)(_this2.deletedField, row.assumedMasterState); + } + } + return _context3.abrupt("return", row); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x5) { + return _ref2.apply(this, arguments); + }; + }())); + case 5: + useRows = _context4.sent; + result = null; + case 7: + if (!(!done && !_this2.isStopped())) { + _context4.next = 25; + break; + } + _context4.prev = 8; + _context4.next = 11; + return _this2.push.handler(useRows); + case 11: + result = _context4.sent; + if (Array.isArray(result)) { + _context4.next = 14; + break; + } throw (0, _rxError.newRxError)('RC_PUSH_NO_AR', { pushRows: rows, direction: 'push', @@ -424,85 +323,128 @@ var RxReplicationState = /*#__PURE__*/function () { result: result } }); - } - done = true; - }); - }, function (err) { - var emitError = err.rxdb ? err : (0, _rxError.newRxError)('RC_PUSH', { - pushRows: rows, - errors: Array.isArray(err) ? err : [err], - direction: 'push' - }); - _this2.subjects.error.next(emitError); - return Promise.resolve((0, _replicationHelper.awaitRetry)(_this2.collection, (0, _util.ensureNotFalsy)(_this2.retryTime))).then(function () {}); - }); - }); - return _temp6 && _temp6.then ? _temp6.then(_temp7) : _temp7(_temp6); - }); - } catch (e) { - return Promise.reject(e); + case 14: + done = true; + _context4.next = 23; + break; + case 17: + _context4.prev = 17; + _context4.t0 = _context4["catch"](8); + emitError = _context4.t0.rxdb ? _context4.t0 : (0, _rxError.newRxError)('RC_PUSH', { + pushRows: rows, + errors: (0, _utils.toArray)(_context4.t0).map(function (er) { + return (0, _utils.errorToPlainJson)(er); + }), + direction: 'push' + }); + _this2.subjects.error.next(emitError); + _context4.next = 23; + return (0, _replicationHelper.awaitRetry)(_this2.collection, (0, _utils.ensureNotFalsy)(_this2.retryTime)); + case 23: + _context4.next = 7; + break; + case 25: + if (!_this2.isStopped()) { + _context4.next = 27; + break; + } + return _context4.abrupt("return", []); + case 27: + conflicts = (0, _utils.ensureNotFalsy)(result).map(function (doc) { + return (0, _replicationHelper.swapdeletedFieldToDefaultDeleted)(_this2.deletedField, doc); + }); + return _context4.abrupt("return", conflicts); + case 29: + case "end": + return _context4.stop(); + } + }, _callee4, null, [[8, 17]]); + })); + function masterWrite(_x4) { + return _masterWrite.apply(this, arguments); + } + return masterWrite; + }() } - } - } - }); - _this2.subs.push(_this2.internalReplicationState.events.error.subscribe(function (err) { - _this2.subjects.error.next(err); - }), _this2.internalReplicationState.events.processed.down.subscribe(function (row) { - return _this2.subjects.received.next(row.document); - }), _this2.internalReplicationState.events.processed.up.subscribe(function (writeToMasterRow) { - _this2.subjects.send.next(writeToMasterRow.newDocumentState); - }), (0, _rxjs.combineLatest)([_this2.internalReplicationState.events.active.down, _this2.internalReplicationState.events.active.up]).subscribe(function (_ref2) { - var down = _ref2[0], - up = _ref2[1]; - var isActive = down || up; - _this2.subjects.active.next(isActive); - })); - if (_this2.pull && _this2.pull.stream$ && _this2.live) { - _this2.subs.push(_this2.pull.stream$.subscribe({ - next: function next(ev) { - _this2.remoteEvents$.next(ev); - }, - error: function error(err) { + }); + this.subs.push(this.internalReplicationState.events.error.subscribe(function (err) { _this2.subjects.error.next(err); + }), this.internalReplicationState.events.processed.down.subscribe(function (row) { + return _this2.subjects.received.next(row.document); + }), this.internalReplicationState.events.processed.up.subscribe(function (writeToMasterRow) { + _this2.subjects.send.next(writeToMasterRow.newDocumentState); + }), (0, _rxjs.combineLatest)([this.internalReplicationState.events.active.down, this.internalReplicationState.events.active.up]).subscribe(function (_ref3) { + var down = _ref3[0], + up = _ref3[1]; + var isActive = down || up; + _this2.subjects.active.next(isActive); + })); + if (this.pull && this.pull.stream$ && this.live) { + this.subs.push(this.pull.stream$.subscribe({ + next: function next(ev) { + _this2.remoteEvents$.next(ev); + }, + error: function error(err) { + _this2.subjects.error.next(err); + } + })); } - })); - } - /** - * Non-live replications run once - * and then automatically get canceled. - */ - var _temp = function () { - if (!_this2.live) { - return Promise.resolve((0, _replicationProtocol.awaitRxStorageReplicationFirstInSync)(_this2.internalReplicationState)).then(function () { - return Promise.resolve((0, _replicationProtocol.awaitRxStorageReplicationInSync)(_this2.internalReplicationState)).then(function () { - return Promise.resolve(_this2.cancel()).then(function () {}); - }); - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); + /** + * Non-live replications run once + * and then automatically get canceled. + */ + if (this.live) { + _context5.next = 21; + break; + } + _context5.next = 17; + return (0, _replicationProtocol.awaitRxStorageReplicationFirstInSync)(this.internalReplicationState); + case 17: + _context5.next = 19; + return (0, _replicationProtocol.awaitRxStorageReplicationInSync)(this.internalReplicationState); + case 19: + _context5.next = 21; + return this.cancel(); + case 21: + this.callOnStart(); + case 22: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function start() { + return _start.apply(this, arguments); } - }; + return start; + }(); _proto.isStopped = function isStopped() { if (this.subjects.canceled.getValue()) { return true; } return false; }; - _proto.awaitInitialReplication = function awaitInitialReplication() { - try { - var _this3 = this; - return Promise.resolve(_this3.startPromise).then(function () { - return (0, _replicationProtocol.awaitRxStorageReplicationFirstInSync)((0, _util.ensureNotFalsy)(_this3.internalReplicationState)); - }); - } catch (e) { - return Promise.reject(e); + _proto.awaitInitialReplication = /*#__PURE__*/function () { + var _awaitInitialReplication = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6() { + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return this.startPromise; + case 2: + return _context6.abrupt("return", (0, _replicationProtocol.awaitRxStorageReplicationFirstInSync)((0, _utils.ensureNotFalsy)(this.internalReplicationState))); + case 3: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function awaitInitialReplication() { + return _awaitInitialReplication.apply(this, arguments); } - } + return awaitInitialReplication; + }() /** * Returns a promise that resolves when: * - All local data is replicated with the remote @@ -514,28 +456,37 @@ var RxReplicationState = /*#__PURE__*/function () { * For multi-tab support you should set and observe a flag in a local document. */ ; - _proto.awaitInSync = function awaitInSync() { - try { - var _this4 = this; - return Promise.resolve(_this4.startPromise).then(function () { - return Promise.resolve((0, _replicationProtocol.awaitRxStorageReplicationFirstInSync)((0, _util.ensureNotFalsy)(_this4.internalReplicationState))).then(function () { - /** - * Often awaitInSync() is called directly after a document write, - * like in the unit tests. - * So we first have to await the idleness to ensure that all RxChangeEvents - * are processed already. - */ - return Promise.resolve(_this4.collection.database.requestIdlePromise()).then(function () { - return Promise.resolve((0, _replicationProtocol.awaitRxStorageReplicationInSync)((0, _util.ensureNotFalsy)(_this4.internalReplicationState))).then(function () { - return true; - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); + _proto.awaitInSync = + /*#__PURE__*/ + function () { + var _awaitInSync = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.startPromise; + case 2: + _context7.next = 4; + return (0, _replicationProtocol.awaitRxStorageReplicationFirstInSync)((0, _utils.ensureNotFalsy)(this.internalReplicationState)); + case 4: + _context7.next = 6; + return this.collection.database.requestIdlePromise(); + case 6: + _context7.next = 8; + return (0, _replicationProtocol.awaitRxStorageReplicationInSync)((0, _utils.ensureNotFalsy)(this.internalReplicationState)); + case 8: + return _context7.abrupt("return", true); + case 9: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function awaitInSync() { + return _awaitInSync.apply(this, arguments); } - }; + return awaitInSync; + }(); _proto.reSync = function reSync() { this.remoteEvents$.next('RESYNC'); }; @@ -543,17 +494,17 @@ var RxReplicationState = /*#__PURE__*/function () { this.remoteEvents$.next(ev); }; _proto.cancel = function cancel() { - var _this5 = this; + var _this3 = this; if (this.isStopped()) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } var promises = []; if (this.internalReplicationState) { (0, _replicationProtocol.cancelRxStorageReplication)(this.internalReplicationState); } if (this.metaInstance) { - promises.push((0, _util.ensureNotFalsy)(this.internalReplicationState).checkpointQueue.then(function () { - return (0, _util.ensureNotFalsy)(_this5.metaInstance).close(); + promises.push((0, _utils.ensureNotFalsy)(this.internalReplicationState).checkpointQueue.then(function () { + return (0, _utils.ensureNotFalsy)(_this3.metaInstance).close(); })); } this.subs.forEach(function (sub) { @@ -570,22 +521,23 @@ var RxReplicationState = /*#__PURE__*/function () { return RxReplicationState; }(); exports.RxReplicationState = RxReplicationState; -function replicateRxCollection(_ref3) { - var replicationIdentifier = _ref3.replicationIdentifier, - collection = _ref3.collection, - _ref3$deletedField = _ref3.deletedField, - deletedField = _ref3$deletedField === void 0 ? '_deleted' : _ref3$deletedField, - pull = _ref3.pull, - push = _ref3.push, - _ref3$live = _ref3.live, - live = _ref3$live === void 0 ? true : _ref3$live, - _ref3$retryTime = _ref3.retryTime, - retryTime = _ref3$retryTime === void 0 ? 1000 * 5 : _ref3$retryTime, - _ref3$waitForLeadersh = _ref3.waitForLeadership, - waitForLeadership = _ref3$waitForLeadersh === void 0 ? true : _ref3$waitForLeadersh, - _ref3$autoStart = _ref3.autoStart, - autoStart = _ref3$autoStart === void 0 ? true : _ref3$autoStart; - var replicationIdentifierHash = (0, _util.fastUnsecureHash)([collection.database.name, collection.name, replicationIdentifier].join('|')); +function replicateRxCollection(_ref4) { + var replicationIdentifier = _ref4.replicationIdentifier, + collection = _ref4.collection, + _ref4$deletedField = _ref4.deletedField, + deletedField = _ref4$deletedField === void 0 ? '_deleted' : _ref4$deletedField, + pull = _ref4.pull, + push = _ref4.push, + _ref4$live = _ref4.live, + live = _ref4$live === void 0 ? true : _ref4$live, + _ref4$retryTime = _ref4.retryTime, + retryTime = _ref4$retryTime === void 0 ? 1000 * 5 : _ref4$retryTime, + _ref4$waitForLeadersh = _ref4.waitForLeadership, + waitForLeadership = _ref4$waitForLeadersh === void 0 ? true : _ref4$waitForLeadersh, + _ref4$autoStart = _ref4.autoStart, + autoStart = _ref4$autoStart === void 0 ? true : _ref4$autoStart; + (0, _plugin.addRxPlugin)(_leaderElection.RxDBLeaderElectionPlugin); + var replicationIdentifierHash = (0, _utils.fastUnsecureHash)([collection.database.name, collection.name, replicationIdentifier].join('|')); var replicationState = new RxReplicationState(replicationIdentifierHash, collection, deletedField, pull, push, live, retryTime, autoStart); startReplicationOnLeaderShip(waitForLeadership, replicationState); return replicationState; @@ -596,7 +548,7 @@ function startReplicationOnLeaderShip(waitForLeadership, replicationState) { * is leader when waitForLeadership=true */ var mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance; - var waitTillRun = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : _util.PROMISE_RESOLVE_TRUE; + var waitTillRun = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : _utils.PROMISE_RESOLVE_TRUE; return waitTillRun.then(function () { if (replicationState.isStopped()) { return; diff --git a/dist/lib/plugins/replication/index.js.map b/dist/lib/plugins/replication/index.js.map index f6a174251c6..7af06526f49 100644 --- a/dist/lib/plugins/replication/index.js.map +++ b/dist/lib/plugins/replication/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","Subject","send","error","canceled","BehaviorSubject","active","initialReplicationComplete","received$","asObservable","send$","error$","canceled$","active$","callOnStart","undefined","remoteEvents$","replicationStates","get","set","onDestroy","cancel","Object","keys","forEach","key","defineProperty","startPromise","Promise","res","start","isStopped","pullModifier","modifier","DEFAULT_MODIFIER","pushModifier","database","metaInstanceCollectionName","name","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","schema","RX_REPLICATION_META_INSTANCE_SCHEMA","addConnectedStorageToCollection","metaInstance","internalReplicationState","replicateRxStorageInstance","pushBatchSize","batchSize","pullBatchSize","forkInstance","storageInstance","hashFunction","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","mergeMap","ev","useEv","flatClone","documents","map","doc","swapdeletedFieldToDefaultDeleted","d","masterChangesSince","checkpoint","useResult","done","handler","err","emitError","newRxError","errors","Array","isArray","direction","next","awaitRetry","ensureNotFalsy","masterWrite","rows","row","newDocumentState","swapDefaultDeletedTodeletedField","assumedMasterState","useRows","conflicts","pushRows","args","rxdb","events","subscribe","processed","down","document","up","writeToMasterRow","combineLatest","isActive","stream$","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","PROMISE_RESOLVE_FALSE","promises","cancelRxStorageReplication","checkpointQueue","close","sub","unsubscribe","complete","replicateRxCollection","replicationIdentifier","waitForLeadership","fastUnsecureHash","join","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types';\nimport {\n ensureNotFalsy,\n fastUnsecureHash,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE\n} from '../../util';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n replicateRxStorageInstance,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n} from '../../replication-protocol';\nimport { newRxError } from '../../rx-error';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n swapdeletedFieldToDefaultDeleted\n} from './replication-helper';\nimport { addConnectedStorageToCollection } from '../../rx-database-internal-store';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n send: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false), // true when something is running, false when not\n initialReplicationComplete: new BehaviorSubject(false) // true the initial replication-cycle is over\n };\n\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly send$: Observable> = this.subjects.send.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n private startPromise: Promise;\n constructor(\n /**\n * hash of the identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n let replicationStates = REPLICATION_STATE_BY_COLLECTION.get(collection);\n if (!replicationStates) {\n replicationStates = [];\n REPLICATION_STATE_BY_COLLECTION.set(collection, replicationStates);\n }\n replicationStates.push(this);\n\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n\n const metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash;\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: RX_REPLICATION_META_INSTANCE_SCHEMA\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n )\n ]);\n this.metaInstance = metaInstance;\n\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rx-replication-' + this.replicationIdentifierHash,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n if (this.deletedField !== '_deleted') {\n useEv.documents = useEv.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: Array.isArray(err) ? err : [err],\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n if (this.deletedField !== '_deleted') {\n useResult.documents = useResult.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n const useRows = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n\n return row;\n })\n );\n\n let result: WithDeleted[] = null as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: Array.isArray(err) ? err : [err],\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return [];\n }\n\n const conflicts = ensureNotFalsy(result).map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.send.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = [];\n\n if (this.internalReplicationState) {\n cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.send.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n const replicationIdentifierHash = fastUnsecureHash(\n [\n collection.database.name,\n collection.name,\n replicationIdentifier\n ].join('|')\n );\n const replicationState = new RxReplicationState(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;;;;;;;AAOA;AAwBA;AAOA;AAOA;AACA;AAMA;AA8fO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AArhBO,iBAAiBG,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACH,IAAI,EAAE;MACxBG,KAAK,CAACH,IAAI,CAAC,QAAQO,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAA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IAAI,EACJC,SAAS,EACTC,SAAS,CACZ;EAGDuI,4BAA4B,CAACJ,iBAAiB,EAAEG,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGO,SAASC,4BAA4B,CACxCJ,iBAA0B,EAC1BG,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGL,iBAAiB,IAAIG,gBAAgB,CAAC5I,UAAU,CAAC6C,QAAQ,CAACU,aAAa;EACrG,IAAMwF,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAAC5I,UAAU,CAAC6C,QAAQ,CAAC4F,iBAAiB,EAAE,GAAGO,0BAAoB;EACzI,OAAOD,WAAW,CAAC3K,IAAI,CAAC,YAAM;IAC1B,IAAIwK,gBAAgB,CAACpG,SAAS,EAAE,EAAE;MAC9B;IACJ;IACA,IAAIoG,gBAAgB,CAACtI,SAAS,EAAE;MAC5BsI,gBAAgB,CAACrG,KAAK,EAAE;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file +{"version":3,"file":"index.js","names":["REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifierHash","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","Subject","send","error","canceled","BehaviorSubject","active","initialReplicationComplete","received$","asObservable","send$","error$","canceled$","active$","callOnStart","undefined","remoteEvents$","replicationStates","get","set","onDestroy","cancel","Object","keys","forEach","key","defineProperty","startPromise","Promise","res","start","isStopped","pullModifier","modifier","DEFAULT_MODIFIER","pushModifier","database","metaInstanceCollectionName","name","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","schema","RX_REPLICATION_META_INSTANCE_SCHEMA","addConnectedStorageToCollection","metaInstance","internalReplicationState","replicateRxStorageInstance","pushBatchSize","batchSize","pullBatchSize","forkInstance","storageInstance","hashFunction","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","mergeMap","ev","useEv","flatClone","documents","map","doc","swapdeletedFieldToDefaultDeleted","d","masterChangesSince","checkpoint","done","result","handler","emitError","newRxError","errors","toArray","er","errorToPlainJson","direction","next","awaitRetry","ensureNotFalsy","useResult","masterWrite","rows","row","newDocumentState","assumedMasterState","swapDefaultDeletedTodeletedField","useRows","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","err","processed","down","document","up","writeToMasterRow","combineLatest","isActive","stream$","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","PROMISE_RESOLVE_FALSE","promises","cancelRxStorageReplication","checkpointQueue","then","close","sub","unsubscribe","complete","replicateRxCollection","replicationIdentifier","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","fastUnsecureHash","join","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types';\nimport { RxDBLeaderElectionPlugin } from '../leader-election';\nimport {\n ensureNotFalsy,\n errorToPlainJson,\n fastUnsecureHash,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray\n} from '../../plugins/utils';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n replicateRxStorageInstance,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n} from '../../replication-protocol';\nimport { newRxError } from '../../rx-error';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n swapdeletedFieldToDefaultDeleted\n} from './replication-helper';\nimport {\n addConnectedStorageToCollection\n} from '../../rx-database-internal-store';\nimport { addRxPlugin } from '../../plugin';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n send: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false), // true when something is running, false when not\n initialReplicationComplete: new BehaviorSubject(false) // true the initial replication-cycle is over\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly send$: Observable> = this.subjects.send.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n private startPromise: Promise;\n constructor(\n /**\n * hash of the identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifierHash: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n let replicationStates = REPLICATION_STATE_BY_COLLECTION.get(collection);\n if (!replicationStates) {\n replicationStates = [];\n REPLICATION_STATE_BY_COLLECTION.set(collection, replicationStates);\n }\n replicationStates.push(this);\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n const metaInstanceCollectionName = this.collection.name + '-rx-replication-' + this.replicationIdentifierHash;\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: RX_REPLICATION_META_INSTANCE_SCHEMA\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n RX_REPLICATION_META_INSTANCE_SCHEMA\n )\n ]);\n this.metaInstance = metaInstance;\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rx-replication-' + this.replicationIdentifierHash,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n if (this.deletedField !== '_deleted') {\n useEv.documents = useEv.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n if (this.deletedField !== '_deleted') {\n useResult.documents = useResult.documents.map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n }\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n const useRows = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n\n let result: WithDeleted[] = null as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n const conflicts = ensureNotFalsy(result).map(doc => swapdeletedFieldToDefaultDeleted(this.deletedField, doc));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.send.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = [];\n\n if (this.internalReplicationState) {\n cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.send.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n const replicationIdentifierHash = fastUnsecureHash(\n [\n collection.database.name,\n collection.name,\n replicationIdentifier\n ].join('|')\n );\n const replicationState = new RxReplicationState(\n replicationIdentifierHash,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;;;;;;;;;;AAOA;AAwBA;AACA;AASA;AAOA;AACA;AAMA;AAGA;AA1DA;AACA;AACA;AACA;AACA;AACA;;AAwDO,IAAMA,+BAAsF,GAAG,IAAIC,OAAO,EAAE;AAAC;AAAA,IAEvGC,kBAAkB;EAkB3B;EACI;AACR;AACA;AACA;EACwBC,yBAAiC,EACjCC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EAC5B;IAAA;IAAA,KA9BcC,IAAI,GAAmB,EAAE;IAAA,KACzBC,QAAQ,GAAG;MACvBC,QAAQ,EAAE,IAAIC,aAAO,EAA6B;MAAE;MACpDC,IAAI,EAAE,IAAID,aAAO,EAA0B;MAAE;MAC7CE,KAAK,EAAE,IAAIF,aAAO,EAAyB;MAAE;MAC7CG,QAAQ,EAAE,IAAIC,qBAAe,CAAU,KAAK,CAAC;MAAE;MAC/CC,MAAM,EAAE,IAAID,qBAAe,CAAU,KAAK,CAAC;MAAE;MAC7CE,0BAA0B,EAAE,IAAIF,qBAAe,CAAU,KAAK,CAAC,CAAC;IACpE,CAAC;IAAA,KAEQG,SAAS,GAA0C,IAAI,CAACT,QAAQ,CAACC,QAAQ,CAACS,YAAY,EAAE;IAAA,KACxFC,KAAK,GAAuC,IAAI,CAACX,QAAQ,CAACG,IAAI,CAACO,YAAY,EAAE;IAAA,KAC7EE,MAAM,GAAsC,IAAI,CAACZ,QAAQ,CAACI,KAAK,CAACM,YAAY,EAAE;IAAA,K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file diff --git a/dist/lib/plugins/replication/replication-helper.js b/dist/lib/plugins/replication/replication-helper.js index c4551796f20..8cc68206038 100644 --- a/dist/lib/plugins/replication/replication-helper.js +++ b/dist/lib/plugins/replication/replication-helper.js @@ -7,7 +7,7 @@ exports.DEFAULT_MODIFIER = void 0; exports.awaitRetry = awaitRetry; exports.swapDefaultDeletedTodeletedField = swapDefaultDeletedTodeletedField; exports.swapdeletedFieldToDefaultDeleted = swapdeletedFieldToDefaultDeleted; -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); // does nothing var DEFAULT_MODIFIER = function DEFAULT_MODIFIER(d) { return Promise.resolve(d); @@ -17,7 +17,7 @@ function swapDefaultDeletedTodeletedField(deletedField, doc) { if (deletedField === '_deleted') { return doc; } else { - doc = (0, _util.flatClone)(doc); + doc = (0, _utils.flatClone)(doc); var isDeleted = !!doc._deleted; doc[deletedField] = isDeleted; delete doc._deleted; @@ -28,7 +28,7 @@ function swapdeletedFieldToDefaultDeleted(deletedField, doc) { if (deletedField === '_deleted') { return doc; } else { - doc = (0, _util.flatClone)(doc); + doc = (0, _utils.flatClone)(doc); var isDeleted = !!doc[deletedField]; doc._deleted = isDeleted; delete doc[deletedField]; diff --git a/dist/lib/plugins/replication/replication-helper.js.map b/dist/lib/plugins/replication/replication-helper.js.map index 9a541de820f..6f715b3ed92 100644 --- a/dist/lib/plugins/replication/replication-helper.js.map +++ b/dist/lib/plugins/replication/replication-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"replication-helper.js","names":["DEFAULT_MODIFIER","d","Promise","resolve","swapDefaultDeletedTodeletedField","deletedField","doc","flatClone","isDeleted","_deleted","swapdeletedFieldToDefaultDeleted","awaitRetry","collection","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types';\nimport { flatClone } from '../../util';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n\nexport function swapdeletedFieldToDefaultDeleted(\n deletedField: string,\n doc: RxDocType\n): WithDeleted {\n if (deletedField === '_deleted') {\n return doc as any;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!(doc as any)[deletedField];\n (doc as any)._deleted = isDeleted;\n delete (doc as any)[deletedField];\n return doc as any;\n }\n}\n\n\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n"],"mappings":";;;;;;;;;AAIA;AAEA;AACO,IAAMA,gBAAgB,GAAG,SAAnBA,gBAAgB,CAAIC,CAAM;EAAA,OAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAAA;AAAC;AAGxD,SAASG,gCAAgC,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAG,IAAAC,eAAS,EAACD,GAAG,CAAC;IACpB,IAAME,SAAS,GAAG,CAAC,CAACF,GAAG,CAACG,QAAQ;IAC/BH,GAAG,CAASD,YAAY,CAAC,GAAGG,SAAS;IACtC,OAAQF,GAAG,CAASG,QAAQ;IAC5B,OAAOH,GAAG;EACd;AACJ;AAGO,SAASI,gCAAgC,CAC5CL,YAAoB,EACpBC,GAAc,EACQ;EACtB,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAG,IAAAC,eAAS,EAACD,GAAG,CAAC;IACpB,IAAME,SAAS,GAAG,CAAC,CAAEF,GAAG,CAASD,YAAY,CAAC;IAC7CC,GAAG,CAASG,QAAQ,GAAGD,SAAS;IACjC,OAAQF,GAAG,CAASD,YAAY,CAAC;IACjC,OAAOC,GAAG;EACd;AACJ;AAGO,SAASK,UAAU,CACtBC,UAAwB,EACxBC,SAAiB,EACnB;EACE,IACI,OAAOC,MAAM,KAAK,WAAW,IAC7B,OAAOA,MAAM,KAAK,QAAQ,IAC1B,OAAOA,MAAM,CAACC,gBAAgB,KAAK,WAAW,IAC9CC,SAAS,CAACC,MAAM,EAClB;IACE,OAAOL,UAAU,CAACM,WAAW,CAACL,SAAS,CAAC;EAC5C;EAEA,IAAIM,SAAa;EACjB,IAAMC,WAAW,GAAG,IAAIlB,OAAO,CAAO,UAAAmB,GAAG,EAAI;IACzCF,SAAQ,GAAG,oBAAM;MACbL,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,SAAQ,CAAC;MAC9CE,GAAG,EAAE;IACT,CAAC;IACDP,MAAM,CAACC,gBAAgB,CAAC,QAAQ,EAAEI,SAAQ,CAAC;EAC/C,CAAC,CAAC;EAEF,OAAOjB,OAAO,CAACqB,IAAI,CAAC,CAChBH,WAAW,EACXR,UAAU,CAACM,WAAW,CAACL,SAAS,CAAC,CACpC,CAAC,CAACW,IAAI,CAAC,YAAM;IACVV,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,SAAQ,CAAC;EAClD,CAAC,CAAC;AACN"} \ No newline at end of file +{"version":3,"file":"replication-helper.js","names":["DEFAULT_MODIFIER","d","Promise","resolve","swapDefaultDeletedTodeletedField","deletedField","doc","flatClone","isDeleted","_deleted","swapdeletedFieldToDefaultDeleted","awaitRetry","collection","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types';\nimport { flatClone } from '../../plugins/utils';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n\nexport function swapdeletedFieldToDefaultDeleted(\n deletedField: string,\n doc: RxDocType\n): WithDeleted {\n if (deletedField === '_deleted') {\n return doc as any;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!(doc as any)[deletedField];\n (doc as any)._deleted = isDeleted;\n delete (doc as any)[deletedField];\n return doc as any;\n }\n}\n\n\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n"],"mappings":";;;;;;;;;AAIA;AAEA;AACO,IAAMA,gBAAgB,GAAG,SAAnBA,gBAAgB,CAAIC,CAAM;EAAA,OAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAAA;AAAC;AAGxD,SAASG,gCAAgC,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;I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AAC,CACpC,CAAC,CAACW,IAAI,CAAC,YAAM;IACVV,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,SAAQ,CAAC;EAClD,CAAC,CAAC;AACN"} \ No newline at end of file diff --git a/dist/lib/plugins/server-couchdb/index.js b/dist/lib/plugins/server-couchdb/index.js deleted file mode 100644 index 3ec0a972f74..00000000000 --- a/dist/lib/plugins/server-couchdb/index.js +++ /dev/null @@ -1,425 +0,0 @@ -"use strict"; - -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxDBServerCouchDBPlugin = void 0; -exports.onDestroy = onDestroy; -exports.spawnServer = void 0; -var os = _interopRequireWildcard(require("os")); -var nodePath = _interopRequireWildcard(require("path")); -var _express = _interopRequireDefault(require("express")); -var _cors = _interopRequireDefault(require("cors")); -var _pouchdb = require("../../plugins/pouchdb"); -var _rxError = require("../../rx-error"); -var _replicationCouchdb = require("../replication-couchdb"); -var _pouchdbAdapterHttp = _interopRequireDefault(require("pouchdb-adapter-http")); -var _index = require("../../index"); -var _util = require("../../util"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } -var spawnServer = function spawnServer(_ref) { - try { - var _temp6 = function _temp6() { - return Promise.resolve(startupPromise).then(function () { - var response = { - app: app, - pouchApp: pouchApp, - server: server - }; - return response; - }); - }; - var _this = this; - var _ref$path = _ref.path, - path = _ref$path === void 0 ? '/db' : _ref$path, - _ref$port = _ref.port, - port = _ref$port === void 0 ? 3000 : _ref$port, - _ref$cors = _ref.cors, - cors = _ref$cors === void 0 ? false : _ref$cors, - _ref$startServer = _ref.startServer, - startServer = _ref$startServer === void 0 ? true : _ref$startServer, - _ref$pouchdbExpressOp = _ref.pouchdbExpressOptions, - pouchdbExpressOptions = _ref$pouchdbExpressOp === void 0 ? {} : _ref$pouchdbExpressOp; - var db = _this; - var collectionsPath = startServer ? path : '/'; - if (!SERVERS_OF_DB.has(db)) { - SERVERS_OF_DB.set(db, []); - } - var storage = db.storage; - if (!storage.adapter) { - throw new Error('The RxDB server plugin only works with pouchdb storage.'); - } - var adapterObj = (0, _index.adapterObject)(storage.adapter); - var pouchDBOptions = Object.assign({ - prefix: getPrefix(db), - log: false - }, adapterObj); - var pseudo = _pouchdb.PouchDB.defaults(pouchDBOptions); - var app = (0, _express["default"])(); - APP_OF_DB.set(db, app); - Object.keys(db.collections).forEach(function (colName) { - // tunnel requests so collection-names can be used as paths - tunnelCollectionPath(db, collectionsPath, app, colName); - }); - - // remember to throw error if collection is created after the server is already there - DBS_WITH_SERVER.add(db); - if (cors) { - app.use((0, _cors["default"])({ - 'origin': function origin(_origin, callback) { - var originToSend = _origin || '*'; - callback(null, originToSend); - }, - 'credentials': true, - 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT' - })); - } - - /** - * Overwrite the defaults of PouchDBExpressServerOptions. - * In RxDB the defaults should not pollute anything with folders so we store the config in memory - * and the logs in the tmp folder of the os. - */ - var usePouchExpressOptions = (0, _util.flatClone)(pouchdbExpressOptions); - if (typeof usePouchExpressOptions.inMemoryConfig === 'undefined') { - usePouchExpressOptions.inMemoryConfig = true; - } - if (typeof usePouchExpressOptions.logPath === 'undefined') { - usePouchExpressOptions.logPath = nodePath.join(os.tmpdir(), 'rxdb-server-log.txt'); - } - var pouchApp = ExpressPouchDB(pseudo, usePouchExpressOptions); - app.use(collectionsPath, pouchApp); - var server = null; - var startupPromise = _util.PROMISE_RESOLVE_VOID; - var _temp5 = function () { - if (startServer) { - /** - * Listen for errors on server startup. - * and properly handle the error instead of returning a startupPromise - */ - startupPromise = new Promise(function (res, rej) { - var answered = false; - server = app.listen(port, function () { - if (!answered) { - answered = true; - res(); - } - }); - server.on('error', function (err) { - if (!answered) { - answered = true; - rej(err); - } - }); - }); - SERVERS_OF_DB.get(db).push(server); - - /** - * When the database has no documents, there is no db file - * and so the replication would not work. - * This is a hack which ensures that the couchdb instance exists - * and we can replicate even if there is no document in the beginning. - */ - return Promise.resolve(Promise.all(Object.values(db.collections).map(function (collection) { - try { - var url = 'http://0.0.0.0:' + port + collectionsPath + '/' + collection.name; - var _temp7 = _catch(function () { - var pingDb = new _pouchdb.PouchDB(url); - pingDb.aaa = 'pingDB for ' + url; - return Promise.resolve(pingDb.info()).then(function () { - return Promise.resolve(pingDb.close()).then(function () {}); - }); - }, function () {}); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } - }(); - return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5)); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * when a server is created, no more collections can be spawned - */ -exports.spawnServer = spawnServer; -var ExpressPouchDB; -try { - ExpressPouchDB = require('express-pouchdb'); -} catch (error) { - console.error('Since version 8.4.0 the module \'express-pouchdb\' is not longer delivered with RxDB.\n' + 'You can install it with \'npm install express-pouchdb\''); -} - -// we have to clean up after tests so there is no stupid logging -// @link https://github.com/pouchdb/pouchdb-server/issues/226 -var PouchdbAllDbs = require('pouchdb-all-dbs'); -PouchdbAllDbs(_pouchdb.PouchDB); -var APP_OF_DB = new WeakMap(); -var SERVERS_OF_DB = new WeakMap(); -var DBS_WITH_SERVER = new WeakSet(); -var normalizeDbName = function normalizeDbName(db) { - var split = db.name.split('/').filter(function (str) { - return str !== ''; - }); - return split.pop(); -}; -var getPrefix = function getPrefix(db) { - var split = db.name.split('/').filter(function (str) { - return str !== ''; - }); - split.pop(); // last was the name - if (split.length === 0) { - return ''; - } - var ret = split.join('/') + '/'; - if (db.name.startsWith('/')) { - ret = '/' + ret; - } - return ret; -}; - -/** - * tunnel requests so collection-names can be used as paths - */ -function tunnelCollectionPath(db, path, app, colName) { - var pathWithSlash = path.endsWith('/') ? path : path + '/'; - var collectionPath = pathWithSlash + colName; - app.use(collectionPath, function (req, res, next) { - try { - var _temp4 = function _temp4() { - next(); - }; - var _temp3 = function () { - if (req.baseUrl.endsWith(collectionPath)) { - var _temp2 = function _temp2() { - var to = normalizeDbName(db) + '-rxdb-' + db[colName].schema.version + '-' + colName; - var toFull = req.originalUrl.replace(collectionPath, pathWithSlash + to); - req.originalUrl = toFull; - }; - var _temp = _for(function () { - return !db[colName]; - }, void 0, function () { - // if the collection is migrated, - // it can happen that it does not exist at this moment - return Promise.resolve(new Promise(function (res1) { - return setTimeout(res1, 50); - })).then(function () {}); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); - } - }); -} -function ensureNoMoreCollections(args) { - if (DBS_WITH_SERVER.has(args.database)) { - var err = (0, _rxError.newRxError)('S1', { - collection: args.name, - database: args.database.name - }); - throw err; - } -} - -/** - * runs when the database gets destroyed - */ -function onDestroy(db) { - if (SERVERS_OF_DB.has(db)) { - SERVERS_OF_DB.get(db).forEach(function (server) { - return server.close(); - }); - } -} -var RxDBServerCouchDBPlugin = { - name: 'server-couchdb', - rxdb: true, - init: function init() { - (0, _pouchdb.addPouchPlugin)(_pouchdbAdapterHttp["default"]); - (0, _index.addRxPlugin)(_replicationCouchdb.RxDBReplicationCouchDBPlugin); - }, - prototypes: { - RxDatabase: function RxDatabase(proto) { - proto.serverCouchDB = spawnServer; - } - }, - overwritable: {}, - hooks: { - preDestroyRxDatabase: { - after: onDestroy - }, - preCreateRxCollection: { - after: ensureNoMoreCollections - } - } -}; -exports.RxDBServerCouchDBPlugin = RxDBServerCouchDBPlugin; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/server-couchdb/index.js.map b/dist/lib/plugins/server-couchdb/index.js.map deleted file mode 100644 index 1791944c6e6..00000000000 --- a/dist/lib/plugins/server-couchdb/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","recover","spawnServer","startupPromise","response","app","pouchApp","server","path","port","cors","startServer","pouchdbExpressOptions","db","collectionsPath","SERVERS_OF_DB","has","set","storage","adapter","Error","adapterObj","adapterObject","pouchDBOptions","Object","assign","prefix","getPrefix","log","pseudo","PouchDB","defaults","express","APP_OF_DB","keys","collections","forEach","colName","tunnelCollectionPath","DBS_WITH_SERVER","add","use","corsFn","origin","originToSend","usePouchExpressOptions","flatClone","inMemoryConfig","logPath","nodePath","join","os","tmpdir","ExpressPouchDB","PROMISE_RESOLVE_VOID","Promise","res","rej","answered","listen","on","err","get","push","all","values","map","collection","url","name","pingDb","aaa","info","close","require","error","console","PouchdbAllDbs","WeakMap","WeakSet","normalizeDbName","split","filter","str","pop","length","ret","startsWith","pathWithSlash","endsWith","collectionPath","req","next","baseUrl","to","schema","version","toFull","originalUrl","replace","res1","setTimeout","ensureNoMoreCollections","args","database","newRxError","onDestroy","RxDBServerCouchDBPlugin","rxdb","init","addPouchPlugin","PouchAdapterHttp","addRxPlugin","RxDBReplicationCouchDBPlugin","prototypes","RxDatabase","proto","serverCouchDB","overwritable","hooks","preDestroyRxDatabase","after","preCreateRxCollection"],"sources":["../../../../src/plugins/server-couchdb/index.ts"],"sourcesContent":["import * as os from 'os';\nimport * as nodePath from 'path';\n\nimport express from 'express';\nimport type { Express } from 'express';\nimport corsFn from 'cors';\n\nimport {\n addPouchPlugin,\n PouchDB,\n RxStoragePouch\n} from '../../plugins/pouchdb';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n PouchDBExpressServerOptions,\n RxDatabase,\n RxPlugin,\n CouchDBServerResponse\n} from '../../types';\n\nimport { RxDBReplicationCouchDBPlugin } from '../replication-couchdb';\n\nimport PouchAdapterHttp from 'pouchdb-adapter-http';\nimport { adapterObject, addRxPlugin } from '../../index';\nimport {\n flatClone, PROMISE_RESOLVE_VOID\n} from '../../util';\n\nlet ExpressPouchDB: any;\ntry {\n ExpressPouchDB = require('express-pouchdb');\n} catch (error) {\n console.error(\n 'Since version 8.4.0 the module \\'express-pouchdb\\' is not longer delivered with RxDB.\\n' +\n 'You can install it with \\'npm install express-pouchdb\\''\n );\n}\n\n// we have to clean up after tests so there is no stupid logging\n// @link https://github.com/pouchdb/pouchdb-server/issues/226\nconst PouchdbAllDbs = require('pouchdb-all-dbs');\nPouchdbAllDbs(PouchDB);\n\nconst APP_OF_DB: WeakMap = new WeakMap();\nconst SERVERS_OF_DB = new WeakMap();\nconst DBS_WITH_SERVER = new WeakSet();\n\n\nconst normalizeDbName = function (db: RxDatabase) {\n const split = db.name.split('/').filter((str: string) => str !== '');\n return split.pop();\n};\n\nconst getPrefix = function (db: RxDatabase) {\n const split = db.name.split('/').filter((str: string) => str !== '');\n split.pop(); // last was the name\n if (split.length === 0) {\n return '';\n }\n let ret = split.join('/') + '/';\n if (db.name.startsWith('/')) {\n ret = '/' + ret;\n }\n return ret;\n};\n\n/**\n * tunnel requests so collection-names can be used as paths\n */\nfunction tunnelCollectionPath(\n db: RxDatabase,\n path: string,\n app: Express,\n colName: string\n) {\n const pathWithSlash = path.endsWith('/') ? path : path + '/';\n const collectionPath = pathWithSlash + colName;\n app.use(collectionPath, async function (req: any, res: any, next: any) {\n if (req.baseUrl.endsWith(collectionPath)) {\n\n while (!db[colName]) {\n // if the collection is migrated,\n // it can happen that it does not exist at this moment\n await new Promise(res1 => setTimeout(res1, 50));\n }\n const to = normalizeDbName(db) + '-rxdb-' + db[colName].schema.version + '-' + colName;\n const toFull = req.originalUrl.replace(collectionPath, pathWithSlash + to);\n req.originalUrl = toFull;\n }\n next();\n });\n}\n\nexport async function spawnServer(\n this: RxDatabase,\n {\n path = '/db',\n port = 3000,\n cors = false,\n startServer = true,\n pouchdbExpressOptions = {}\n }\n): Promise {\n const db: RxDatabase = this;\n const collectionsPath = startServer ? path : '/';\n if (!SERVERS_OF_DB.has(db)) {\n SERVERS_OF_DB.set(db, []);\n }\n\n const storage: RxStoragePouch = db.storage as any;\n if (!storage.adapter) {\n throw new Error('The RxDB server plugin only works with pouchdb storage.');\n }\n\n const adapterObj = adapterObject(storage.adapter);\n const pouchDBOptions = Object.assign(\n { prefix: getPrefix(db), log: false },\n adapterObj,\n );\n\n const pseudo = PouchDB.defaults(pouchDBOptions);\n const app = express();\n APP_OF_DB.set(db, app);\n\n Object.keys(db.collections).forEach(colName => {\n // tunnel requests so collection-names can be used as paths\n tunnelCollectionPath(db, collectionsPath, app, colName);\n });\n\n // remember to throw error if collection is created after the server is already there\n DBS_WITH_SERVER.add(db);\n\n if (cors) {\n app.use(corsFn({\n 'origin': function (origin, callback) {\n const originToSend: any = origin || '*';\n callback(null, originToSend);\n },\n 'credentials': true,\n 'methods': 'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT',\n }));\n }\n\n /**\n * Overwrite the defaults of PouchDBExpressServerOptions.\n * In RxDB the defaults should not pollute anything with folders so we store the config in memory\n * and the logs in the tmp folder of the os.\n */\n const usePouchExpressOptions: PouchDBExpressServerOptions = flatClone(pouchdbExpressOptions);\n if (typeof usePouchExpressOptions.inMemoryConfig === 'undefined') {\n usePouchExpressOptions.inMemoryConfig = true;\n }\n if (typeof usePouchExpressOptions.logPath === 'undefined') {\n usePouchExpressOptions.logPath = nodePath.join(\n os.tmpdir(),\n 'rxdb-server-log.txt'\n );\n }\n\n const pouchApp = ExpressPouchDB(pseudo, usePouchExpressOptions);\n app.use(collectionsPath, pouchApp);\n\n let server = null;\n let startupPromise: Promise = PROMISE_RESOLVE_VOID;\n if (startServer) {\n /**\n * Listen for errors on server startup.\n * and properly handle the error instead of returning a startupPromise\n */\n startupPromise = new Promise((res, rej) => {\n let answered = false;\n server = app.listen(port, () => {\n if (!answered) {\n answered = true;\n res();\n }\n });\n server.on('error', (err) => {\n if (!answered) {\n answered = true;\n rej(err);\n }\n });\n });\n SERVERS_OF_DB.get(db).push(server);\n\n /**\n * When the database has no documents, there is no db file\n * and so the replication would not work.\n * This is a hack which ensures that the couchdb instance exists\n * and we can replicate even if there is no document in the beginning.\n */\n await Promise.all(\n Object.values(db.collections).map(async (collection) => {\n const url = 'http://0.0.0.0:' + port + collectionsPath + '/' + collection.name;\n try {\n const pingDb = new PouchDB(url);\n pingDb.aaa = 'pingDB for ' + url;\n await pingDb.info();\n await pingDb.close();\n } catch (_err) { }\n })\n );\n }\n await startupPromise;\n\n const response: CouchDBServerResponse = {\n app,\n pouchApp,\n server\n };\n return response;\n}\n\n/**\n * when a server is created, no more collections can be spawned\n */\nfunction ensureNoMoreCollections(args: any) {\n if (DBS_WITH_SERVER.has(args.database)) {\n const err = newRxError(\n 'S1', {\n collection: args.name,\n database: args.database.name\n }\n );\n throw err;\n }\n}\n\n/**\n * runs when the database gets destroyed\n */\nexport function onDestroy(db: RxDatabase) {\n if (SERVERS_OF_DB.has(db)) {\n SERVERS_OF_DB.get(db).forEach((server: any) => server.close());\n }\n}\n\nexport const RxDBServerCouchDBPlugin: RxPlugin = {\n name: 'server-couchdb',\n rxdb: true,\n init() {\n addPouchPlugin(PouchAdapterHttp);\n addRxPlugin(RxDBReplicationCouchDBPlugin);\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.serverCouchDB = spawnServer;\n }\n },\n overwritable: {},\n hooks: {\n preDestroyRxDatabase: {\n after: onDestroy\n },\n preCreateRxCollection: {\n after: ensureNoMoreCollections\n }\n }\n};\n"],"mappings":";;;;;;;;;AAAA;AACA;AAEA;AAEA;AAEA;AAKA;AAUA;AAEA;AACA;AACA;AAaO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,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G,CAACjD,EAAE,CAAC,CAACuB,OAAO,CAAC,UAAC7B,MAAW;MAAA,OAAKA,MAAM,CAACkE,KAAK,EAAE;IAAA,EAAC;EAClE;AACJ;AAEO,IAAMkC,uBAAiC,GAAG;EAC7CtC,IAAI,EAAE,gBAAgB;EACtBuC,IAAI,EAAE,IAAI;EACVC,IAAI,kBAAG;IACH,IAAAC,uBAAc,EAACC,8BAAgB,CAAC;IAChC,IAAAC,kBAAW,EAACC,gDAA4B,CAAC;EAC7C,CAAC;EACDC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACC,aAAa,GAAGnH,WAAW;IACrC;EACJ,CAAC;EACDoH,YAAY,EAAE,CAAC,CAAC;EAChBC,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEf;IACX,CAAC;IACDgB,qBAAqB,EAAE;MACnBD,KAAK,EAAEnB;IACX;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/dexie-helper.js b/dist/lib/plugins/storage-dexie/dexie-helper.js similarity index 62% rename from dist/lib/plugins/dexie/dexie-helper.js rename to dist/lib/plugins/storage-dexie/dexie-helper.js index cccd3ad2825..2e43e2a674f 100644 --- a/dist/lib/plugins/dexie/dexie-helper.js +++ b/dist/lib/plugins/storage-dexie/dexie-helper.js @@ -1,9 +1,11 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.closeDexieDb = exports.RX_STORAGE_NAME_DEXIE = exports.DEXIE_PIPE_SUBSTITUTE = exports.DEXIE_DOCS_TABLE_NAME = exports.DEXIE_DELETED_DOCS_TABLE_NAME = exports.DEXIE_CHANGES_TABLE_NAME = void 0; +exports.RX_STORAGE_NAME_DEXIE = exports.DEXIE_PIPE_SUBSTITUTE = exports.DEXIE_DOCS_TABLE_NAME = exports.DEXIE_DELETED_DOCS_TABLE_NAME = exports.DEXIE_CHANGES_TABLE_NAME = void 0; +exports.closeDexieDb = closeDexieDb; exports.dexieReplaceIfStartsWithPipe = dexieReplaceIfStartsWithPipe; exports.dexieReplaceIfStartsWithPipeRevert = dexieReplaceIfStartsWithPipeRevert; exports.ensureNoBooleanIndex = ensureNoBooleanIndex; @@ -12,45 +14,14 @@ exports.fromStorageToDexie = fromStorageToDexie; exports.getDexieDbWithTables = getDexieDbWithTables; exports.getDexieSortComparator = getDexieSortComparator; exports.getDexieStoreSchema = getDexieStoreSchema; -exports.getDocsInDb = void 0; +exports.getDocsInDb = getDocsInDb; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _dexie = require("dexie"); -var _util = require("../../util"); +var _utils = require("../utils"); var _rxError = require("../../rx-error"); var _rxSchemaHelper = require("../../rx-schema-helper"); var _rxQueryMingo = require("../../rx-query-mingo"); -/** - * Returns all documents in the database. - * Non-deleted plus deleted ones. - */ -var getDocsInDb = function getDocsInDb(internals, docIds) { - return Promise.resolve(internals).then(function (state) { - return Promise.resolve(Promise.all([state.dexieTable.bulkGet(docIds), state.dexieDeletedTable.bulkGet(docIds)])).then(function (_ref3) { - var nonDeletedDocsInDb = _ref3[0], - deletedDocsInDb = _ref3[1]; - var docsInDb = deletedDocsInDb.slice(0); - nonDeletedDocsInDb.forEach(function (doc, idx) { - if (doc) { - docsInDb[idx] = doc; - } - }); - return docsInDb; - }); - }); -}; -exports.getDocsInDb = getDocsInDb; -var closeDexieDb = function closeDexieDb(statePromise) { - return Promise.resolve(statePromise).then(function (state) { - var prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise); - var newCount = prevCount - 1; - if (newCount === 0) { - state.dexieDb.close(); - REF_COUNT_PER_DEXIE_DB["delete"](statePromise); - } else { - REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount); - } - }); -}; -exports.closeDexieDb = closeDexieDb; var DEXIE_DOCS_TABLE_NAME = 'docs'; exports.DEXIE_DOCS_TABLE_NAME = DEXIE_DOCS_TABLE_NAME; var DEXIE_DELETED_DOCS_TABLE_NAME = 'deleted-docs'; @@ -66,35 +37,70 @@ function getDexieDbWithTables(databaseName, collectionName, settings, schema) { var dexieDbName = 'rxdb-dexie-' + databaseName + '--' + schema.version + '--' + collectionName; var state = DEXIE_STATE_DB_BY_NAME.get(dexieDbName); if (!state) { - state = function () { - try { - var _dexieStoresSettings; - /** - * IndexedDB was not designed for dynamically adding tables on the fly, - * so we create one dexie database per RxDB storage instance. - * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696 - */ - var useSettings = (0, _util.flatClone)(settings); - useSettings.autoOpen = false; - var dexieDb = new _dexie.Dexie(dexieDbName, useSettings); - var dexieStoresSettings = (_dexieStoresSettings = {}, _dexieStoresSettings[DEXIE_DOCS_TABLE_NAME] = getDexieStoreSchema(schema), _dexieStoresSettings[DEXIE_CHANGES_TABLE_NAME] = '++sequence, id', _dexieStoresSettings[DEXIE_DELETED_DOCS_TABLE_NAME] = primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']', _dexieStoresSettings); - dexieDb.version(1).stores(dexieStoresSettings); - return Promise.resolve(dexieDb.open()).then(function () { - return { - dexieDb: dexieDb, - dexieTable: dexieDb[DEXIE_DOCS_TABLE_NAME], - dexieDeletedTable: dexieDb[DEXIE_DELETED_DOCS_TABLE_NAME] - }; - }); - } catch (e) { - return Promise.reject(e); - } - }(); + state = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _dexieStoresSettings; + var useSettings, dexieDb, dexieStoresSettings; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * IndexedDB was not designed for dynamically adding tables on the fly, + * so we create one dexie database per RxDB storage instance. + * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696 + */ + useSettings = (0, _utils.flatClone)(settings); + useSettings.autoOpen = false; + dexieDb = new _dexie.Dexie(dexieDbName, useSettings); + dexieStoresSettings = (_dexieStoresSettings = {}, _dexieStoresSettings[DEXIE_DOCS_TABLE_NAME] = getDexieStoreSchema(schema), _dexieStoresSettings[DEXIE_CHANGES_TABLE_NAME] = '++sequence, id', _dexieStoresSettings[DEXIE_DELETED_DOCS_TABLE_NAME] = primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']', _dexieStoresSettings); + dexieDb.version(1).stores(dexieStoresSettings); + _context.next = 7; + return dexieDb.open(); + case 7: + return _context.abrupt("return", { + dexieDb: dexieDb, + dexieTable: dexieDb[DEXIE_DOCS_TABLE_NAME], + dexieDeletedTable: dexieDb[DEXIE_DELETED_DOCS_TABLE_NAME] + }); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + }))(); DEXIE_STATE_DB_BY_NAME.set(dexieDbName, state); REF_COUNT_PER_DEXIE_DB.set(state, 0); } return state; } +function closeDexieDb(_x) { + return _closeDexieDb.apply(this, arguments); +} +function _closeDexieDb() { + _closeDexieDb = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(statePromise) { + var state, prevCount, newCount; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return statePromise; + case 2: + state = _context2.sent; + prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise); + newCount = prevCount - 1; + if (newCount === 0) { + state.dexieDb.close(); + REF_COUNT_PER_DEXIE_DB["delete"](statePromise); + } else { + REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount); + } + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _closeDexieDb.apply(this, arguments); +} function sortDirectionToMingo(direction) { if (direction === 'asc') { return 1; @@ -136,7 +142,7 @@ function ensureNoBooleanIndex(schema) { } var checkedFields = new Set(); schema.indexes.forEach(function (index) { - var fields = Array.isArray(index) ? index : []; + var fields = (0, _utils.toArray)(index); fields.forEach(function (field) { if (checkedFields.has(field)) { return; @@ -202,9 +208,9 @@ function fromStorageToDexie(documentData) { }); } else if (typeof documentData === 'object') { var ret = {}; - Object.entries(documentData).forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; + Object.entries(documentData).forEach(function (_ref2) { + var key = _ref2[0], + value = _ref2[1]; if (typeof value === 'object') { value = fromStorageToDexie(value); } @@ -222,9 +228,9 @@ function fromDexieToStorage(documentData) { }); } else if (typeof documentData === 'object') { var ret = {}; - Object.entries(documentData).forEach(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; + Object.entries(documentData).forEach(function (_ref3) { + var key = _ref3[0], + value = _ref3[1]; if (typeof value === 'object' || Array.isArray(documentData)) { value = fromDexieToStorage(value); } @@ -251,7 +257,7 @@ function getDexieStoreSchema(rxJsonSchema) { // add other indexes if (rxJsonSchema.indexes) { rxJsonSchema.indexes.forEach(function (index) { - var arIndex = Array.isArray(index) ? index : [index]; + var arIndex = (0, _utils.toArray)(index); parts.push(arIndex); }); } @@ -277,4 +283,43 @@ function getDexieStoreSchema(rxJsonSchema) { } }).join(', '); } + +/** + * Returns all documents in the database. + * Non-deleted plus deleted ones. + */ +function getDocsInDb(_x2, _x3) { + return _getDocsInDb.apply(this, arguments); +} +function _getDocsInDb() { + _getDocsInDb = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(internals, docIds) { + var state, _yield$Promise$all, nonDeletedDocsInDb, deletedDocsInDb, docsInDb; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return internals; + case 2: + state = _context3.sent; + _context3.next = 5; + return Promise.all([state.dexieTable.bulkGet(docIds), state.dexieDeletedTable.bulkGet(docIds)]); + case 5: + _yield$Promise$all = _context3.sent; + nonDeletedDocsInDb = _yield$Promise$all[0]; + deletedDocsInDb = _yield$Promise$all[1]; + docsInDb = deletedDocsInDb.slice(0); + nonDeletedDocsInDb.forEach(function (doc, idx) { + if (doc) { + docsInDb[idx] = doc; + } + }); + return _context3.abrupt("return", docsInDb); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _getDocsInDb.apply(this, arguments); +} //# sourceMappingURL=dexie-helper.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-dexie/dexie-helper.js.map b/dist/lib/plugins/storage-dexie/dexie-helper.js.map new file mode 100644 index 00000000000..c9a66562b79 --- /dev/null +++ b/dist/lib/plugins/storage-dexie/dexie-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-helper.js","names":["DEXIE_DOCS_TABLE_NAME","DEXIE_DELETED_DOCS_TABLE_NAME","DEXIE_CHANGES_TABLE_NAME","RX_STORAGE_NAME_DEXIE","DEXIE_STATE_DB_BY_NAME","Map","REF_COUNT_PER_DEXIE_DB","getDexieDbWithTables","databaseName","collectionName","settings","schema","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","dexieDbName","version","state","get","useSettings","flatClone","autoOpen","dexieDb","Dexie","dexieStoresSettings","getDexieStoreSchema","stores","open","dexieTable","dexieDeletedTable","set","closeDexieDb","statePromise","prevCount","newCount","close","sortDirectionToMingo","direction","getDexieSortComparator","_schema","query","mingoSortObject","sort","newRxError","forEach","sortBlock","key","Object","keys","values","fun","a","b","sorted","getMingoQuery","find","first","next","ensureNoBooleanIndex","indexes","checkedFields","Set","index","fields","toArray","field","has","add","schemaObj","getSchemaByObjectPath","type","DEXIE_PIPE_SUBSTITUTE","dexieReplaceIfStartsWithPipe","str","split","length","map","part","join","startsWith","withoutFirst","substring","dexieReplaceIfStartsWithPipeRevert","fromStorageToDexie","documentData","Array","isArray","row","ret","entries","value","fromDexieToStorage","rxJsonSchema","parts","push","arIndex","getDocsInDb","internals","docIds","Promise","all","bulkGet","nonDeletedDocsInDb","deletedDocsInDb","docsInDb","slice","doc","idx"],"sources":["../../../../src/plugins/storage-dexie/dexie-helper.ts"],"sourcesContent":["import type {\n DeterministicSortComparator\n} from 'event-reduce-js';\nimport type {\n DexieStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { Dexie } from 'dexie';\nimport { DexieSettings } from '../../types';\nimport { flatClone, toArray } from '../utils';\nimport { newRxError } from '../../rx-error';\nimport {\n getPrimaryFieldOfPrimaryKey,\n getSchemaByObjectPath\n} from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const DEXIE_DOCS_TABLE_NAME = 'docs';\nexport const DEXIE_DELETED_DOCS_TABLE_NAME = 'deleted-docs';\nexport const DEXIE_CHANGES_TABLE_NAME = 'changes';\n\nexport const RX_STORAGE_NAME_DEXIE = 'dexie';\n\nconst DEXIE_STATE_DB_BY_NAME: Map = new Map();\nconst REF_COUNT_PER_DEXIE_DB: Map = new Map();\nexport function getDexieDbWithTables(\n databaseName: string,\n collectionName: string,\n settings: DexieSettings,\n schema: RxJsonSchema\n): DexieStorageInternals {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const dexieDbName = 'rxdb-dexie-' + databaseName + '--' + schema.version + '--' + collectionName;\n let state = DEXIE_STATE_DB_BY_NAME.get(dexieDbName);\n if (!state) {\n state = (async () => {\n /**\n * IndexedDB was not designed for dynamically adding tables on the fly,\n * so we create one dexie database per RxDB storage instance.\n * @link https://github.com/dexie/Dexie.js/issues/684#issuecomment-373224696\n */\n const useSettings = flatClone(settings);\n useSettings.autoOpen = false;\n const dexieDb = new Dexie(dexieDbName, useSettings);\n const dexieStoresSettings = {\n [DEXIE_DOCS_TABLE_NAME]: getDexieStoreSchema(schema),\n [DEXIE_CHANGES_TABLE_NAME]: '++sequence, id',\n /**\n * Instead of adding {deleted: false} to every query we run over the document store,\n * we move deleted documents into a separate store where they can only be queried\n * by primary key.\n * This increases performance because it is way easier for the query planner to select\n * a good index and we also do not have to add the _deleted field to every index.\n *\n * We also need the [_meta.lwt+' + primaryPath + '] index for getChangedDocumentsSince()\n */\n [DEXIE_DELETED_DOCS_TABLE_NAME]: primaryPath + ',_meta.lwt,[_meta.lwt+' + primaryPath + ']'\n };\n\n dexieDb.version(1).stores(dexieStoresSettings);\n await dexieDb.open();\n return {\n dexieDb,\n dexieTable: (dexieDb as any)[DEXIE_DOCS_TABLE_NAME],\n dexieDeletedTable: (dexieDb as any)[DEXIE_DELETED_DOCS_TABLE_NAME]\n };\n })();\n\n DEXIE_STATE_DB_BY_NAME.set(dexieDbName, state);\n REF_COUNT_PER_DEXIE_DB.set(state, 0);\n }\n\n return state;\n}\n\nexport async function closeDexieDb(statePromise: DexieStorageInternals) {\n const state = await statePromise;\n const prevCount = REF_COUNT_PER_DEXIE_DB.get(statePromise);\n const newCount = (prevCount as any) - 1;\n if (newCount === 0) {\n state.dexieDb.close();\n REF_COUNT_PER_DEXIE_DB.delete(statePromise);\n } else {\n REF_COUNT_PER_DEXIE_DB.set(statePromise, newCount);\n }\n}\n\n\nfunction sortDirectionToMingo(direction: 'asc' | 'desc'): 1 | -1 {\n if (direction === 'asc') {\n return 1;\n } else {\n return -1;\n }\n}\n\n/**\n * This function is at dexie-helper\n * because we need it in multiple places.\n */\nexport function getDexieSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n const mingoSortObject: {\n [fieldName: string]: 1 | -1;\n } = {};\n\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n\n query.sort.forEach(sortBlock => {\n const key = Object.keys(sortBlock)[0];\n const direction = Object.values(sortBlock)[0];\n mingoSortObject[key] = sortDirectionToMingo(direction);\n });\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n const sorted = getMingoQuery({}).find([a, b], {}).sort(mingoSortObject);\n const first = sorted.next();\n if (first === a) {\n return -1;\n } else {\n return 1;\n }\n };\n\n return fun;\n}\n\n\nexport function ensureNoBooleanIndex(schema: RxJsonSchema) {\n if (!schema.indexes) {\n return;\n }\n const checkedFields = new Set();\n schema.indexes.forEach(index => {\n const fields = toArray(index);\n fields.forEach(field => {\n if (checkedFields.has(field)) {\n return;\n }\n checkedFields.add(field);\n const schemaObj = getSchemaByObjectPath(schema, field);\n if (schemaObj.type === 'boolean') {\n throw newRxError('DXE1', {\n schema,\n index,\n field\n });\n }\n });\n });\n}\n\n\n\n/**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\nexport const DEXIE_PIPE_SUBSTITUTE = '__';\nexport function dexieReplaceIfStartsWithPipe(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipe(part)).join('.');\n }\n\n if (str.startsWith('|')) {\n const withoutFirst = str.substring(1);\n return DEXIE_PIPE_SUBSTITUTE + withoutFirst;\n } else {\n return str;\n }\n}\n\nexport function dexieReplaceIfStartsWithPipeRevert(str: string): string {\n const split = str.split('.');\n if (split.length > 1) {\n return split.map(part => dexieReplaceIfStartsWithPipeRevert(part)).join('.');\n }\n\n if (str.startsWith(DEXIE_PIPE_SUBSTITUTE)) {\n const withoutFirst = str.substring(DEXIE_PIPE_SUBSTITUTE.length);\n return '|' + withoutFirst;\n } else {\n return str;\n }\n}\n\n/**\n * @recursive\n */\nexport function fromStorageToDexie(documentData: RxDocumentData): any {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromStorageToDexie(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object') {\n value = fromStorageToDexie(value);\n }\n ret[dexieReplaceIfStartsWithPipe(key)] = value;\n });\n return ret;\n }\n}\n\nexport function fromDexieToStorage(documentData: any): RxDocumentData {\n if (!documentData || typeof documentData === 'string' || typeof documentData === 'number' || typeof documentData === 'boolean') {\n return documentData;\n } else if (Array.isArray(documentData)) {\n return documentData.map(row => fromDexieToStorage(row));\n } else if (typeof documentData === 'object') {\n const ret: any = {};\n Object.entries(documentData).forEach(([key, value]) => {\n if (typeof value === 'object' || Array.isArray(documentData)) {\n value = fromDexieToStorage(value);\n }\n ret[dexieReplaceIfStartsWithPipeRevert(key)] = value;\n });\n return ret;\n }\n}\n\n\n/**\n * Creates a string that can be used to create the dexie store.\n * @link https://dexie.org/docs/API-Reference#quick-reference\n */\nexport function getDexieStoreSchema(\n rxJsonSchema: RxJsonSchema\n): string {\n let parts: string[][] = [];\n\n /**\n * First part must be the primary key\n * @link https://github.com/dexie/Dexie.js/issues/1307#issuecomment-846590912\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n parts.push([primaryKey]);\n\n // add other indexes\n if (rxJsonSchema.indexes) {\n rxJsonSchema.indexes.forEach(index => {\n const arIndex = toArray(index);\n parts.push(arIndex);\n });\n }\n\n // we also need the _meta.lwt+primaryKey index for the getChangedDocumentsSince() method.\n parts.push(['_meta.lwt', primaryKey]);\n\n /**\n * It is not possible to set non-javascript-variable-syntax\n * keys as IndexedDB indexes. So we have to substitute the pipe-char\n * which comes from the key-compression plugin.\n */\n parts = parts.map(part => {\n return part.map(str => dexieReplaceIfStartsWithPipe(str));\n });\n\n return parts.map(part => {\n if (part.length === 1) {\n return part[0];\n } else {\n return '[' + part.join('+') + ']';\n }\n }).join(', ');\n}\n\n/**\n * Returns all documents in the database.\n * Non-deleted plus deleted ones.\n */\nexport async function getDocsInDb(\n internals: DexieStorageInternals,\n docIds: string[]\n): Promise[]> {\n const state = await internals;\n const [\n nonDeletedDocsInDb,\n deletedDocsInDb\n ] = await Promise.all([\n state.dexieTable.bulkGet(docIds),\n state.dexieDeletedTable.bulkGet(docIds)\n ]);\n const docsInDb = deletedDocsInDb.slice(0);\n nonDeletedDocsInDb.forEach((doc, idx) => {\n if (doc) {\n docsInDb[idx] = doc;\n }\n });\n return docsInDb;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AASA;AAEA;AACA;AACA;AAIA;AA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IA,IAAI,CAACF,MAAM,KAAK,CAAC,EAAE;MACnB,OAAOE,IAAI,CAAC,CAAC,CAAC;IAClB,CAAC,MAAM;MACH,OAAO,GAAG,GAAGA,IAAI,CAACC,IAAI,CAAC,GAAG,CAAC,GAAG,GAAG;IACrC;EACJ,CAAC,CAAC,CAACA,IAAI,CAAC,IAAI,CAAC;AACjB;;AAEA;AACA;AACA;AACA;AAHA,SAIsBkB,WAAW;EAAA;AAAA;AAAA;EAAA,6FAA1B,kBACHC,SAAgC,EAChCC,MAAgB;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEID,SAAS;QAAA;UAAvBhF,KAAK;UAAA;UAAA,OAIDkF,OAAO,CAACC,GAAG,CAAC,CAClBnF,KAAK,CAACW,UAAU,CAACyE,OAAO,CAACH,MAAM,CAAC,EAChCjF,KAAK,CAACY,iBAAiB,CAACwE,OAAO,CAACH,MAAM,CAAC,CAC1C,CAAC;QAAA;UAAA;UALEI,kBAAkB;UAClBC,eAAe;UAKbC,QAAQ,GAAGD,eAAe,CAACE,KAAK,CAAC,CAAC,CAAC;UACzCH,kBAAkB,CAAC1D,OAAO,CAAC,UAAC8D,GAAG,EAAEC,GAAG,EAAK;YACrC,IAAID,GAAG,EAAE;cACLF,QAAQ,CAACG,GAAG,CAAC,GAAGD,GAAG;YACvB;UACJ,CAAC,CAAC;UAAC,kCACIF,QAAQ;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAClB;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-dexie/dexie-query.js b/dist/lib/plugins/storage-dexie/dexie-query.js new file mode 100644 index 00000000000..06b15ee0aae --- /dev/null +++ b/dist/lib/plugins/storage-dexie/dexie-query.js @@ -0,0 +1,233 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.dexieCount = dexieCount; +exports.dexieQuery = dexieQuery; +exports.getKeyRangeByQueryPlan = getKeyRangeByQueryPlan; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _dexieHelper = require("./dexie-helper"); +var _dexieStatics = require("./dexie-statics"); +function getKeyRangeByQueryPlan(queryPlan, IDBKeyRange) { + if (!IDBKeyRange) { + if (typeof window === 'undefined') { + throw new Error('IDBKeyRange missing'); + } else { + IDBKeyRange = window.IDBKeyRange; + } + } + var ret; + /** + * If index has only one field, + * we have to pass the keys directly, not the key arrays. + */ + if (queryPlan.index.length === 1) { + ret = IDBKeyRange.bound(queryPlan.startKeys[0], queryPlan.endKeys[0], queryPlan.inclusiveStart, queryPlan.inclusiveEnd); + } else { + ret = IDBKeyRange.bound(queryPlan.startKeys, queryPlan.endKeys, queryPlan.inclusiveStart, queryPlan.inclusiveEnd); + } + return ret; +} + +/** + * Runs mango queries over the Dexie.js database. + */ +function dexieQuery(_x, _x2) { + return _dexieQuery.apply(this, arguments); +} +function _dexieQuery() { + _dexieQuery = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(instance, preparedQuery) { + var state, query, skip, limit, skipPlusLimit, queryPlan, queryMatcher, keyRange, queryPlanFields, rows, sortComparator; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return instance.internals; + case 2: + state = _context2.sent; + query = preparedQuery.query; + skip = query.skip ? query.skip : 0; + limit = query.limit ? query.limit : Infinity; + skipPlusLimit = skip + limit; + queryPlan = preparedQuery.queryPlan; + queryMatcher = false; + if (!queryPlan.selectorSatisfiedByIndex) { + queryMatcher = _dexieStatics.RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); + } + keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); + queryPlanFields = queryPlan.index; + rows = []; + _context2.next = 15; + return state.dexieDb.transaction('r', state.dexieTable, /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(dexieTx) { + var tx, store, index, indexName, cursorReq; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + /** + * TODO here we use the native IndexedDB transaction + * to get the cursor. + * Instead we should not leave Dexie.js API and find + * a way to create the cursor with Dexie.js. + */ + tx = dexieTx.idbtrans; // const nativeIndexedDB = state.dexieDb.backendDB(); + // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly'); + store = tx.objectStore(_dexieHelper.DEXIE_DOCS_TABLE_NAME); + if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { + index = store; + } else { + if (queryPlanFields.length === 1) { + indexName = (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(queryPlanFields[0]); + } else { + indexName = '[' + queryPlanFields.map(function (field) { + return (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(field); + }).join('+') + ']'; + } + index = store.index(indexName); + } + cursorReq = index.openCursor(keyRange); + _context.next = 6; + return new Promise(function (res) { + cursorReq.onsuccess = function (e) { + var cursor = e.target.result; + if (cursor) { + // We have a record in cursor.value + var docData = (0, _dexieHelper.fromDexieToStorage)(cursor.value); + if (!docData._deleted && (!queryMatcher || queryMatcher(docData))) { + rows.push(docData); + } + + /** + * If we do not have to manually sort + * and have enough documents, + * we can abort iterating over the cursor + * because we already have every relevant document. + */ + if (queryPlan.sortFieldsSameAsIndexFields && rows.length === skipPlusLimit) { + res(); + } else { + cursor["continue"](); + } + } else { + // Iteration complete + res(); + } + }; + }); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x5) { + return _ref.apply(this, arguments); + }; + }()); + case 15: + if (!queryPlan.sortFieldsSameAsIndexFields) { + sortComparator = _dexieStatics.RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); + rows = rows.sort(sortComparator); + } + + // apply skip and limit boundaries. + rows = rows.slice(skip, skipPlusLimit); + + /** + * Comment this in for debugging to check all fields in the database. + */ + // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray(); + // let documents = docsInDb + // .map(docData => stripDexieKey(docData)) + // .sort(sortComparator); + // if (preparedQuery.skip) { + // documents = documents.slice(preparedQuery.skip); + // } + // if (preparedQuery.limit && documents.length > preparedQuery.limit) { + // documents = documents.slice(0, preparedQuery.limit); + // } + return _context2.abrupt("return", { + documents: rows + }); + case 18: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _dexieQuery.apply(this, arguments); +} +function dexieCount(_x3, _x4) { + return _dexieCount.apply(this, arguments); +} +function _dexieCount() { + _dexieCount = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(instance, preparedQuery) { + var state, queryPlan, queryPlanFields, keyRange, count; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return instance.internals; + case 2: + state = _context4.sent; + queryPlan = preparedQuery.queryPlan; + queryPlanFields = queryPlan.index; + keyRange = getKeyRangeByQueryPlan(queryPlan, state.dexieDb._options.IDBKeyRange); + count = -1; + _context4.next = 9; + return state.dexieDb.transaction('r', state.dexieTable, /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(dexieTx) { + var tx, store, index, indexName, request; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + tx = dexieTx.idbtrans; + store = tx.objectStore(_dexieHelper.DEXIE_DOCS_TABLE_NAME); + if (queryPlanFields.length === 1 && queryPlanFields[0] === instance.primaryPath) { + index = store; + } else { + if (queryPlanFields.length === 1) { + indexName = (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(queryPlanFields[0]); + } else { + indexName = '[' + queryPlanFields.map(function (field) { + return (0, _dexieHelper.dexieReplaceIfStartsWithPipe)(field); + }).join('+') + ']'; + } + index = store.index(indexName); + } + request = index.count(keyRange); + _context3.next = 6; + return new Promise(function (res, rej) { + request.onsuccess = function () { + res(request.result); + }; + request.onerror = function (err) { + return rej(err); + }; + }); + case 6: + count = _context3.sent; + case 7: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function (_x6) { + return _ref2.apply(this, arguments); + }; + }()); + case 9: + return _context4.abrupt("return", count); + case 10: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _dexieCount.apply(this, arguments); +} +//# sourceMappingURL=dexie-query.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-dexie/dexie-query.js.map b/dist/lib/plugins/storage-dexie/dexie-query.js.map new file mode 100644 index 00000000000..bb48684f61b --- /dev/null +++ b/dist/lib/plugins/storage-dexie/dexie-query.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-query.js","names":["getKeyRangeByQueryPlan","queryPlan","IDBKeyRange","window","Error","ret","index","length","bound","startKeys","endKeys","inclusiveStart","inclusiveEnd","dexieQuery","instance","preparedQuery","internals","state","query","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","RxStorageDexieStatics","getQueryMatcher","schema","keyRange","dexieDb","_options","queryPlanFields","rows","transaction","dexieTable","dexieTx","tx","idbtrans","store","objectStore","DEXIE_DOCS_TABLE_NAME","primaryPath","indexName","dexieReplaceIfStartsWithPipe","map","field","join","cursorReq","openCursor","Promise","res","onsuccess","e","cursor","target","result","docData","fromDexieToStorage","value","_deleted","push","sortFieldsSameAsIndexFields","sortComparator","getSortComparator","sort","slice","documents","dexieCount","count","request","rej","onerror","err"],"sources":["../../../../src/plugins/storage-dexie/dexie-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport type {\n DexiePreparedQuery,\n RxDocumentData,\n RxQueryPlan,\n RxStorageQueryResult\n} from '../../types';\nimport {\n dexieReplaceIfStartsWithPipe,\n DEXIE_DOCS_TABLE_NAME,\n fromDexieToStorage\n} from './dexie-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\nimport type { RxStorageInstanceDexie } from './rx-storage-instance-dexie';\n\n\nexport function getKeyRangeByQueryPlan(\n queryPlan: RxQueryPlan,\n IDBKeyRange?: any\n) {\n if (!IDBKeyRange) {\n if (typeof window === 'undefined') {\n throw new Error('IDBKeyRange missing');\n } else {\n IDBKeyRange = window.IDBKeyRange;\n }\n }\n\n let ret: any;\n /**\n * If index has only one field,\n * we have to pass the keys directly, not the key arrays.\n */\n if (queryPlan.index.length === 1) {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys[0],\n queryPlan.endKeys[0],\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n } else {\n ret = IDBKeyRange.bound(\n queryPlan.startKeys,\n queryPlan.endKeys,\n queryPlan.inclusiveStart,\n queryPlan.inclusiveEnd\n );\n }\n return ret;\n}\n\n\n/**\n * Runs mango queries over the Dexie.js database.\n */\nexport async function dexieQuery(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise> {\n const state = await instance.internals;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlan = preparedQuery.queryPlan;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n\n const queryPlanFields: string[] = queryPlan.index;\n\n let rows: any[] = [];\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n /**\n * TODO here we use the native IndexedDB transaction\n * to get the cursor.\n * Instead we should not leave Dexie.js API and find\n * a way to create the cursor with Dexie.js.\n */\n const tx = (dexieTx as any).idbtrans;\n\n // const nativeIndexedDB = state.dexieDb.backendDB();\n // const trans = nativeIndexedDB.transaction([DEXIE_DOCS_TABLE_NAME], 'readonly');\n\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n const cursorReq = index.openCursor(keyRange);\n await new Promise(res => {\n cursorReq.onsuccess = function (e: any) {\n const cursor = e.target.result;\n if (cursor) {\n // We have a record in cursor.value\n const docData = fromDexieToStorage(cursor.value);\n if (\n !docData._deleted &&\n (!queryMatcher || queryMatcher(docData))\n ) {\n rows.push(docData);\n }\n\n /**\n * If we do not have to manually sort\n * and have enough documents,\n * we can abort iterating over the cursor\n * because we already have every relevant document.\n */\n if (\n queryPlan.sortFieldsSameAsIndexFields &&\n rows.length === skipPlusLimit\n ) {\n res();\n } else {\n cursor.continue();\n }\n } else {\n // Iteration complete\n res();\n }\n };\n });\n\n\n }\n );\n\n\n if (!queryPlan.sortFieldsSameAsIndexFields) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n\n /**\n * Comment this in for debugging to check all fields in the database.\n */\n // const docsInDb = await state.dexieTable.filter(queryMatcher).toArray();\n // let documents = docsInDb\n // .map(docData => stripDexieKey(docData))\n // .sort(sortComparator);\n // if (preparedQuery.skip) {\n // documents = documents.slice(preparedQuery.skip);\n // }\n // if (preparedQuery.limit && documents.length > preparedQuery.limit) {\n // documents = documents.slice(0, preparedQuery.limit);\n // }\n\n\n\n return {\n documents: rows\n };\n}\n\n\nexport async function dexieCount(\n instance: RxStorageInstanceDexie,\n preparedQuery: DexiePreparedQuery\n): Promise {\n const state = await instance.internals;\n const queryPlan = preparedQuery.queryPlan;\n const queryPlanFields: string[] = queryPlan.index;\n\n const keyRange = getKeyRangeByQueryPlan(\n queryPlan,\n (state.dexieDb as any)._options.IDBKeyRange\n );\n let count: number = -1;\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n async (dexieTx) => {\n const tx = (dexieTx as any).idbtrans;\n const store = tx.objectStore(DEXIE_DOCS_TABLE_NAME);\n let index: any;\n if (\n queryPlanFields.length === 1 &&\n queryPlanFields[0] === instance.primaryPath\n ) {\n index = store;\n } else {\n let indexName: string;\n if (queryPlanFields.length === 1) {\n indexName = dexieReplaceIfStartsWithPipe(queryPlanFields[0]);\n } else {\n indexName = '[' +\n queryPlanFields\n .map(field => dexieReplaceIfStartsWithPipe(field))\n .join('+')\n + ']';\n }\n index = store.index(indexName);\n }\n\n const request = index.count(keyRange);\n count = await new Promise((res, rej) => {\n request.onsuccess = function () {\n res(request.result);\n };\n request.onerror = (err: any) => rej(err);\n });\n }\n );\n return count;\n}\n"],"mappings":";;;;;;;;;;;AAOA;AAKA;AAIO,SAASA,sBAAsB,CAClCC,SAAsB,EACtBC,WAAiB,EACnB;EACE,IAAI,CAACA,WAAW,EAAE;IACd,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;MAC/B,MAAM,IAAIC,KAAK,CAAC,qBAAqB,CAAC;IAC1C,CAAC,MAAM;MACHF,WAAW,GAAGC,MAAM,CAACD,WAAW;IACpC;EACJ;EAEA,IAAIG,GAAQ;EACZ;AACJ;AACA;AACA;EACI,IAAIJ,SAAS,CAACK,KAAK,CAACC,MAAM,KAAK,CAAC,EAAE;IAC9BF,GAAG,GAAGH,WAAW,CAACM,KAAK,CACnBP,SAAS,CAACQ,SAAS,CAAC,CAAC,CAAC,EACtBR,SAAS,CAACS,OAAO,CAAC,CAAC,CAAC,EACpBT,SAAS,CAACU,cAAc,EACxBV,SAAS,CAACW,YAAY,CACzB;EACL,CAAC,MAAM;IACHP,GAAG,GAAGH,WAAW,CA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ACG,WAAW,CAACC,kCAAqB,CAAC;oBAEnD,IACIT,eAAe,CAACxB,MAAM,KAAK,CAAC,IAC5BwB,eAAe,CAAC,CAAC,CAAC,KAAKjB,QAAQ,CAAC2B,WAAW,EAC7C;sBACEnC,KAAK,GAAGgC,KAAK;oBACjB,CAAC,MAAM;sBAEH,IAAIP,eAAe,CAACxB,MAAM,KAAK,CAAC,EAAE;wBAC9BmC,SAAS,GAAG,IAAAC,yCAA4B,EAACZ,eAAe,CAAC,CAAC,CAAC,CAAC;sBAChE,CAAC,MAAM;wBACHW,SAAS,GAAG,GAAG,GACXX,eAAe,CACVa,GAAG,CAAC,UAAAC,KAAK;0BAAA,OAAI,IAAAF,yCAA4B,EAACE,KAAK,CAAC;wBAAA,EAAC,CACjDC,IAAI,CAAC,GAAG,CAAC,GACZ,GAAG;sBACb;sBACAxC,KAAK,GAAGgC,KAAK,CAAChC,KAAK,CAACoC,SAAS,CAAC;oBAClC;oBAEM2B,OAAO,GAAG/D,KAAK,CAAC8D,KAAK,CAACxC,QAAQ,CAAC;oBAAA;oBAAA,OACvB,IAAIqB,OAAO,CAAS,UAACC,GAAG,EAAEoB,GAAG,EAAK;sBAC5CD,OAAO,CAAClB,SAAS,GAAG,YAAY;wBAC5BD,GAAG,CAACmB,OAAO,CAACd,MAAM,CAAC;sBACvB,CAAC;sBACDc,OAAO,CAACE,OAAO,GAAG,UAACC,GAAQ;wBAAA,OAAKF,GAAG,CAACE,GAAG,CAAC;sBAAA;oBAC5C,CAAC,CAAC;kBAAA;oBALFJ,KAAK;kBAAA;kBAAA;oBAAA;gBAAA;cAAA;YAAA,CAMR;YAAA;cAAA;YAAA;UAAA,IACJ;QAAA;UAAA,kCACMA,KAAK;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACf;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/dexie-statics.js b/dist/lib/plugins/storage-dexie/dexie-statics.js similarity index 100% rename from dist/lib/plugins/dexie/dexie-statics.js rename to dist/lib/plugins/storage-dexie/dexie-statics.js diff --git a/dist/lib/plugins/storage-dexie/dexie-statics.js.map b/dist/lib/plugins/storage-dexie/dexie-statics.js.map new file mode 100644 index 00000000000..cb5e0e4160d --- /dev/null +++ b/dist/lib/plugins/storage-dexie/dexie-statics.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-statics.js","names":["RxStorageDexieStatics","prepareQuery","schema","mutateableQuery","sort","newRxError","query","queryPlan","getQueryPlan","getSortComparator","preparedQuery","getDexieSortComparator","getQueryMatcher","_schema","mingoQuery","getMingoQuery","selector","fun","doc","_deleted","cursor","find","next","checkpointSchema","DEFAULT_CHECKPOINT_SCHEMA"],"sources":["../../../../src/plugins/storage-dexie/dexie-statics.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n RxDocumentData,\n RxJsonSchema,\n RxStorageStatics,\n DexiePreparedQuery,\n FilledMangoQuery\n} from '../../types';\nimport {\n getDexieSortComparator\n} from './dexie-helper';\nimport { newRxError } from '../../rx-error';\nimport { getQueryPlan } from '../../query-planner';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\nimport { getMingoQuery } from '../../rx-query-mingo';\n\nexport const RxStorageDexieStatics: RxStorageStatics = {\n prepareQuery(\n schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ): DexiePreparedQuery {\n\n if (!mutateableQuery.sort) {\n throw newRxError('SNH', {\n query: mutateableQuery\n });\n }\n\n /**\n * Store the query plan together with the\n * prepared query to save performance.\n */\n const queryPlan = getQueryPlan(\n schema,\n mutateableQuery\n );\n\n return {\n query: mutateableQuery,\n queryPlan\n };\n },\n\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: DexiePreparedQuery\n ): DeterministicSortComparator {\n return getDexieSortComparator(schema, preparedQuery.query);\n },\n\n getQueryMatcher(\n _schema: RxJsonSchema,\n preparedQuery: DexiePreparedQuery\n ): QueryMatcher> {\n const query = preparedQuery.query;\n const mingoQuery = getMingoQuery(query.selector);\n const fun: QueryMatcher> = (doc: RxDocumentData) => {\n if (doc._deleted) {\n return false;\n }\n const cursor = mingoQuery.find([doc]);\n const next = cursor.next();\n if (next) {\n return true;\n } else {\n return false;\n }\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n\n};\n"],"mappings":";;;;;;AAWA;AAGA;AACA;AACA;AACA;AAEO,IAAMA,qBAAuC,GAAG;EACnDC,YAAY,wBACRC,MAA+C,EAC/CC,eAA4C,EACf;IAE7B,IAAI,CAACA,eAAe,CAACC,IAAI,EAAE;MACvB,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;QACpBC,KAAK,EAAEH;MACX,CAAC,CAAC;IACN;;IAEA;AACR;AACA;AACA;IACQ,IAAMI,SAAS,GAAG,IAAAC,0BAAY,EAC1BN,MAAM,EACNC,eAAe,CAClB;IAED,OAAO;MACHG,KAAK,EAAEH,eAAe;MACtBI,SAAS,EAATA;IACJ,CAAC;EACL,CAAC;EAEDE,iBAAiB,6BACbP,MAA+C,EAC/CQ,aAA4C,EACN;IACtC,OAAO,IAAAC,mCAAsB,EAACT,MAAM,EAAEQ,aAAa,CAACJ,KAAK,CAAC;EAC9D,CAAC;EAEDM,eAAe,2BACXC,OAAgC,EAChCH,aAA4C,EACL;IACvC,IAAMJ,KAAK,GAAGI,aAAa,CAACJ,KAAK;IACjC,IAAMQ,UAAU,GAAG,IAAAC,2BAAa,EAACT,KAAK,CAACU,QAAQ,CAAC;IAChD,IAAMC,GAA4C,GAAG,SAA/CA,GAA4C,CAAIC,GAA8B,EAAK;MACrF,IAAIA,GAAG,CAACC,QAAQ,EAAE;QACd,OAAO,KAAK;MAChB;MACA,IAAMC,MAAM,GAAGN,UAAU,CAACO,IAAI,CAAC,CAACH,GAAG,CAAC,CAAC;MACrC,IAAMI,IAAI,GAAGF,MAAM,CAACE,IAAI,EAAE;MAC1B,IAAIA,IAAI,EAAE;QACN,OAAO,IAAI;MACf,CAAC,MAAM;QACH,OAAO,KAAK;MAChB;IACJ,CAAC;IACD,OAAOL,GAAG;EACd,CAAC;EAEDM,gBAAgB,EAAEC;AAEtB,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/index.js b/dist/lib/plugins/storage-dexie/index.js similarity index 100% rename from dist/lib/plugins/dexie/index.js rename to dist/lib/plugins/storage-dexie/index.js diff --git a/dist/lib/plugins/storage-dexie/index.js.map b/dist/lib/plugins/storage-dexie/index.js.map new file mode 100644 index 00000000000..ea9a450ab9f --- /dev/null +++ b/dist/lib/plugins/storage-dexie/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/storage-dexie/index.ts"],"sourcesContent":["export * from './rx-storage-dexie';\nexport * from './rx-storage-instance-dexie';\nexport * from './dexie-helper';\nexport * from './dexie-query';\nexport * from './dexie-statics';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/dexie/rx-storage-dexie.js b/dist/lib/plugins/storage-dexie/rx-storage-dexie.js similarity index 100% rename from dist/lib/plugins/dexie/rx-storage-dexie.js rename to dist/lib/plugins/storage-dexie/rx-storage-dexie.js diff --git a/dist/lib/plugins/storage-dexie/rx-storage-dexie.js.map b/dist/lib/plugins/storage-dexie/rx-storage-dexie.js.map new file mode 100644 index 00000000000..6d2676f0320 --- /dev/null +++ b/dist/lib/plugins/storage-dexie/rx-storage-dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-dexie.js","names":["RxStorageDexie","settings","name","RX_STORAGE_NAME_DEXIE","statics","RxStorageDexieStatics","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","ensureNoBooleanIndex","schema","createDexieStorageInstance","getRxStorageDexie","storage"],"sources":["../../../../src/plugins/storage-dexie/rx-storage-dexie.ts"],"sourcesContent":["import type {\n RxStorage,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNoBooleanIndex,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport type {\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport {\n createDexieStorageInstance,\n RxStorageInstanceDexie\n} from './rx-storage-instance-dexie';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { RxStorageDexieStatics } from './dexie-statics';\n\n\n\nexport class RxStorageDexie implements RxStorage {\n public name = RX_STORAGE_NAME_DEXIE;\n public statics = RxStorageDexieStatics;\n\n constructor(\n public settings: DexieSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n ensureNoBooleanIndex(params.schema);\n return createDexieStorageInstance(this, params, this.settings);\n }\n}\n\n\nexport function getRxStorageDexie(\n settings: DexieSettings = {}\n): RxStorageDexie {\n const storage = new RxStorageDexie(settings);\n return storage;\n}\n"],"mappings":";;;;;;;AAIA;AAQA;AAIA;AACA;AAAwD,IAI3CA,cAAc;EAIvB,wBACWC,QAAuB,EAChC;IAAA,KALKC,IAAI,GAAGC,kCAAqB;IAAA,KAC5BC,OAAO,GAAGC,mCAAqB;IAAA,KAG3BJ,QAAuB,GAAvBA,QAAuB;EAC9B;EAAC;EAAA,OAEEK,qBAAqB,GAA5B,+BACIC,MAAiE,EACvB;IAC1C,IAAAC,wDAAuC,EAACD,MAAM,CAAC;IAC/C,IAAAE,iCAAoB,EAACF,MAAM,CAACG,MAAM,CAAC;IACnC,OAAO,IAAAC,kDAA0B,EAAC,IAAI,EAAEJ,MAAM,EAAE,IAAI,CAACN,QAAQ,CAAC;EAClE,CAAC;EAAA;AAAA;AAAA;AAIE,SAASW,iBAAiB,GAEf;EAAA,IADdX,QAAuB,uEAAG,CAAC,CAAC;EAE5B,IAAMY,OAAO,GAAG,IAAIb,cAAc,CAACC,QAAQ,CAAC;EAC5C,OAAOY,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-dexie/rx-storage-instance-dexie.js b/dist/lib/plugins/storage-dexie/rx-storage-instance-dexie.js new file mode 100644 index 00000000000..d20a7464fb7 --- /dev/null +++ b/dist/lib/plugins/storage-dexie/rx-storage-instance-dexie.js @@ -0,0 +1,424 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RxStorageInstanceDexie = void 0; +exports.createDexieStorageInstance = createDexieStorageInstance; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _rxjs = require("rxjs"); +var _utils = require("../utils"); +var _dexieHelper = require("./dexie-helper"); +var _dexieQuery = require("./dexie-query"); +var _rxSchemaHelper = require("../../rx-schema-helper"); +var _rxStorageHelper = require("../../rx-storage-helper"); +var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); +var _rxError = require("../../rx-error"); +var instanceId = (0, _utils.now)(); +var RxStorageInstanceDexie = /*#__PURE__*/function () { + function RxStorageInstanceDexie(storage, databaseName, collectionName, schema, internals, options, settings) { + this.changes$ = new _rxjs.Subject(); + this.instanceId = instanceId++; + this.closed = false; + this.storage = storage; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + this.settings = settings; + this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); + } + var _proto = RxStorageInstanceDexie.prototype; + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(documentWrites, context) { + var _this = this; + var state, ret, documentKeys, categorized, lastState, endTime; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + ensureNotClosed(this); + _context2.next = 3; + return this.internals; + case 3: + state = _context2.sent; + ret = { + success: {}, + error: {} + }; + documentKeys = documentWrites.map(function (writeRow) { + return writeRow.document[_this.primaryPath]; + }); + categorized = null; + _context2.next = 9; + return state.dexieDb.transaction('rw', state.dexieTable, state.dexieDeletedTable, /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var docsInDbMap, docsInDbWithInternals, bulkPutDocs, bulkRemoveDocs, bulkPutDeletedDocs, bulkRemoveDeletedDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + docsInDbMap = new Map(); + _context.next = 3; + return (0, _dexieHelper.getDocsInDb)(_this.internals, documentKeys); + case 3: + docsInDbWithInternals = _context.sent; + docsInDbWithInternals.forEach(function (docWithDexieInternals) { + var doc = docWithDexieInternals ? (0, _dexieHelper.fromDexieToStorage)(docWithDexieInternals) : docWithDexieInternals; + if (doc) { + docsInDbMap.set(doc[_this.primaryPath], doc); + } + return doc; + }); + categorized = (0, _rxStorageHelper.categorizeBulkWriteRows)(_this, _this.primaryPath, docsInDbMap, documentWrites, context); + ret.error = categorized.errors; + + /** + * Batch up the database operations + * so we can later run them in bulk. + */ + bulkPutDocs = []; + bulkRemoveDocs = []; + bulkPutDeletedDocs = []; + bulkRemoveDeletedDocs = []; + categorized.bulkInsertDocs.forEach(function (row) { + var docId = row.document[_this.primaryPath]; + ret.success[docId] = row.document; + bulkPutDocs.push(row.document); + }); + categorized.bulkUpdateDocs.forEach(function (row) { + var docId = row.document[_this.primaryPath]; + ret.success[docId] = row.document; + if (row.document._deleted && row.previous && !row.previous._deleted) { + // newly deleted + bulkRemoveDocs.push(docId); + bulkPutDeletedDocs.push(row.document); + } else if (row.document._deleted && row.previous && row.previous._deleted) { + // deleted was modified but is still deleted + bulkPutDeletedDocs.push(row.document); + } else if (!row.document._deleted) { + // non-deleted was changed + bulkPutDocs.push(row.document); + } else { + throw (0, _rxError.newRxError)('SNH', { + args: { + row: row + } + }); + } + }); + _context.next = 15; + return Promise.all([bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(function (d) { + return (0, _dexieHelper.fromStorageToDexie)(d); + })) : _utils.PROMISE_RESOLVE_VOID, bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : _utils.PROMISE_RESOLVE_VOID, bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(function (d) { + return (0, _dexieHelper.fromStorageToDexie)(d); + })) : _utils.PROMISE_RESOLVE_VOID, bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : _utils.PROMISE_RESOLVE_VOID]); + case 15: + case "end": + return _context.stop(); + } + }, _callee); + }))); + case 9: + if ((0, _utils.ensureNotFalsy)(categorized).eventBulk.events.length > 0) { + lastState = (0, _rxStorageHelper.getNewestOfDocumentStates)(this.primaryPath, Object.values(ret.success)); + (0, _utils.ensureNotFalsy)(categorized).eventBulk.checkpoint = { + id: lastState[this.primaryPath], + lwt: lastState._meta.lwt + }; + endTime = (0, _utils.now)(); + (0, _utils.ensureNotFalsy)(categorized).eventBulk.events.forEach(function (event) { + return event.endTime = endTime; + }); + this.changes$.next((0, _utils.ensureNotFalsy)(categorized).eventBulk); + } + return _context2.abrupt("return", ret); + case 11: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function bulkWrite(_x, _x2) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(); + _proto.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ids, deleted) { + var _this2 = this; + var state, ret; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + ensureNotClosed(this); + _context4.next = 3; + return this.internals; + case 3: + state = _context4.sent; + ret = {}; + _context4.next = 7; + return state.dexieDb.transaction('r', state.dexieTable, state.dexieDeletedTable, /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var docsInDb; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!deleted) { + _context3.next = 6; + break; + } + _context3.next = 3; + return (0, _dexieHelper.getDocsInDb)(_this2.internals, ids); + case 3: + docsInDb = _context3.sent; + _context3.next = 9; + break; + case 6: + _context3.next = 8; + return state.dexieTable.bulkGet(ids); + case 8: + docsInDb = _context3.sent; + case 9: + ids.forEach(function (id, idx) { + var documentInDb = docsInDb[idx]; + if (documentInDb && (!documentInDb._deleted || deleted)) { + ret[id] = (0, _dexieHelper.fromDexieToStorage)(documentInDb); + } + }); + case 10: + case "end": + return _context3.stop(); + } + }, _callee3); + }))); + case 7: + return _context4.abrupt("return", ret); + case 8: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function findDocumentsById(_x3, _x4) { + return _findDocumentsById.apply(this, arguments); + } + return findDocumentsById; + }(); + _proto.query = function query(preparedQuery) { + ensureNotClosed(this); + return (0, _dexieQuery.dexieQuery)(this, preparedQuery); + }; + _proto.count = /*#__PURE__*/function () { + var _count = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(preparedQuery) { + var result; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return (0, _dexieQuery.dexieCount)(this, preparedQuery); + case 2: + result = _context5.sent; + return _context5.abrupt("return", { + count: result, + mode: 'fast' + }); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function count(_x5) { + return _count.apply(this, arguments); + } + return count; + }(); + _proto.getChangedDocumentsSince = /*#__PURE__*/function () { + var _getChangedDocumentsSince = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(limit, checkpoint) { + var _this3 = this; + var sinceLwt, sinceId, state, _yield$Promise$all, changedDocsNormal, changedDocsDeleted, changedDocs, lastDoc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + ensureNotClosed(this); + sinceLwt = checkpoint ? checkpoint.lwt : _utils.RX_META_LWT_MINIMUM; + sinceId = checkpoint ? checkpoint.id : ''; + _context7.next = 5; + return this.internals; + case 5: + state = _context7.sent; + _context7.next = 8; + return Promise.all([state.dexieTable, state.dexieDeletedTable].map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(table) { + var query, changedDocuments; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + query = table.where('[_meta.lwt+' + _this3.primaryPath + ']').above([sinceLwt, sinceId]).limit(limit); + _context6.next = 3; + return query.toArray(); + case 3: + changedDocuments = _context6.sent; + return _context6.abrupt("return", changedDocuments.map(function (d) { + return (0, _dexieHelper.fromDexieToStorage)(d); + })); + case 5: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return function (_x8) { + return _ref3.apply(this, arguments); + }; + }())); + case 8: + _yield$Promise$all = _context7.sent; + changedDocsNormal = _yield$Promise$all[0]; + changedDocsDeleted = _yield$Promise$all[1]; + changedDocs = changedDocsNormal.concat(changedDocsDeleted); + changedDocs = (0, _utils.sortDocumentsByLastWriteTime)(this.primaryPath, changedDocs); + changedDocs = changedDocs.slice(0, limit); + lastDoc = (0, _utils.lastOfArray)(changedDocs); + return _context7.abrupt("return", { + documents: changedDocs, + checkpoint: lastDoc ? { + id: lastDoc[this.primaryPath], + lwt: lastDoc._meta.lwt + } : checkpoint ? checkpoint : { + id: '', + lwt: 0 + } + }); + case 16: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function getChangedDocumentsSince(_x6, _x7) { + return _getChangedDocumentsSince.apply(this, arguments); + } + return getChangedDocumentsSince; + }(); + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { + var state; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + ensureNotClosed(this); + _context8.next = 3; + return this.internals; + case 3: + state = _context8.sent; + _context8.next = 6; + return Promise.all([state.dexieDeletedTable.clear(), state.dexieTable.clear()]); + case 6: + return _context8.abrupt("return", this.close()); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function remove() { + return _remove.apply(this, arguments); + } + return remove; + }(); + _proto.changeStream = function changeStream() { + ensureNotClosed(this); + return this.changes$.asObservable(); + }; + _proto.cleanup = /*#__PURE__*/function () { + var _cleanup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(minimumDeletedTime) { + var _this4 = this; + var state; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + ensureNotClosed(this); + _context10.next = 3; + return this.internals; + case 3: + state = _context10.sent; + _context10.next = 6; + return state.dexieDb.transaction('rw', state.dexieDeletedTable, /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9() { + var maxDeletionTime, toRemove, removeIds; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + maxDeletionTime = (0, _utils.now)() - minimumDeletedTime; + _context9.next = 3; + return state.dexieDeletedTable.where('_meta.lwt').below(maxDeletionTime).toArray(); + case 3: + toRemove = _context9.sent; + removeIds = toRemove.map(function (doc) { + return doc[_this4.primaryPath]; + }); + _context9.next = 7; + return state.dexieDeletedTable.bulkDelete(removeIds); + case 7: + case "end": + return _context9.stop(); + } + }, _callee9); + }))); + case 6: + return _context10.abrupt("return", true); + case 7: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function cleanup(_x9) { + return _cleanup.apply(this, arguments); + } + return cleanup; + }(); + _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { + ensureNotClosed(this); + throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.'); + }; + _proto.close = function close() { + ensureNotClosed(this); + this.closed = true; + this.changes$.complete(); + (0, _dexieHelper.closeDexieDb)(this.internals); + return _utils.PROMISE_RESOLVE_VOID; + }; + _proto.conflictResultionTasks = function conflictResultionTasks() { + return new _rxjs.Subject(); + }; + _proto.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(_taskSolution) { + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + function resolveConflictResultionTask(_x10) { + return _resolveConflictResultionTask.apply(this, arguments); + } + return resolveConflictResultionTask; + }(); + return RxStorageInstanceDexie; +}(); +exports.RxStorageInstanceDexie = RxStorageInstanceDexie; +function createDexieStorageInstance(storage, params, settings) { + var internals = (0, _dexieHelper.getDexieDbWithTables)(params.databaseName, params.collectionName, settings, params.schema); + var instance = new RxStorageInstanceDexie(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); + (0, _rxStorageMultiinstance.addRxStorageMultiInstanceSupport)(_dexieHelper.RX_STORAGE_NAME_DEXIE, params, instance); + return Promise.resolve(instance); +} +function ensureNotClosed(instance) { + if (instance.closed) { + throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName); + } +} +//# sourceMappingURL=rx-storage-instance-dexie.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-dexie/rx-storage-instance-dexie.js.map b/dist/lib/plugins/storage-dexie/rx-storage-instance-dexie.js.map new file mode 100644 index 00000000000..3b6e02e2110 --- /dev/null +++ b/dist/lib/plugins/storage-dexie/rx-storage-instance-dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-dexie.js","names":["instanceId","now","RxStorageInstanceDexie","storage","databaseName","collectionName","schema","internals","options","settings","changes$","Subject","closed","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","bulkWrite","documentWrites","context","ensureNotClosed","state","ret","success","error","documentKeys","map","writeRow","document","categorized","dexieDb","transaction","dexieTable","dexieDeletedTable","docsInDbMap","Map","getDocsInDb","docsInDbWithInternals","forEach","docWithDexieInternals","doc","fromDexieToStorage","set","categorizeBulkWriteRows","errors","bulkPutDocs","bulkRemoveDocs","bulkPutDeletedDocs","bulkRemoveDeletedDocs","bulkInsertDocs","row","docId","push","bulkUpdateDocs","_deleted","previous","newRxError","args","Promise","all","length","bulkPut","d","fromStorageToDexie","PROMISE_RESOLVE_VOID","bulkDelete","ensureNotFalsy","eventBulk","events","lastState","getNewestOfDocumentStates","Object","values","checkpoint","id","lwt","_meta","endTime","event","next","findDocumentsById","ids","deleted","docsInDb","bulkGet","idx","documentInDb","query","preparedQuery","dexieQuery","count","dexieCount","result","mode","getChangedDocumentsSince","limit","sinceLwt","RX_META_LWT_MINIMUM","sinceId","table","where","above","toArray","changedDocuments","changedDocsNormal","changedDocsDeleted","changedDocs","concat","sortDocumentsByLastWriteTime","slice","lastDoc","lastOfArray","documents","remove","clear","close","changeStream","asObservable","cleanup","minimumDeletedTime","maxDeletionTime","below","toRemove","removeIds","getAttachmentData","_documentId","_attachmentId","Error","complete","closeDexieDb","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","createDexieStorageInstance","params","getDexieDbWithTables","instance","addRxStorageMultiInstanceSupport","RX_STORAGE_NAME_DEXIE","resolve"],"sources":["../../../../src/plugins/storage-dexie/rx-storage-instance-dexie.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n now,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM,\n sortDocumentsByLastWriteTime,\n lastOfArray,\n ensureNotFalsy\n} from '../utils';\nimport type {\n RxStorageInstance,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n RxStorageInstanceCreationParams,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n CategorizeBulkWriteRowsOutput,\n RxStorageCountResult\n} from '../../types';\nimport {\n DexiePreparedQuery,\n DexieSettings,\n DexieStorageInternals\n} from '../../types/plugins/dexie';\nimport { RxStorageDexie } from './rx-storage-dexie';\nimport {\n closeDexieDb,\n fromDexieToStorage,\n fromStorageToDexie,\n getDexieDbWithTables,\n getDocsInDb,\n RX_STORAGE_NAME_DEXIE\n} from './dexie-helper';\nimport { dexieCount, dexieQuery } from './dexie-query';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport } from '../../rx-storage-multiinstance';\nimport { newRxError } from '../../rx-error';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceDexie implements RxStorageInstance<\nRxDocType,\nDexieStorageInternals,\nDexieSettings,\nRxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageDexie,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: DexieStorageInternals,\n public readonly options: Readonly,\n public readonly settings: DexieSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const documentKeys: string[] = documentWrites.map(writeRow => writeRow.document[this.primaryPath] as any);\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n const docsInDbMap = new Map>();\n const docsInDbWithInternals = await getDocsInDb(this.internals, documentKeys);\n docsInDbWithInternals.forEach(docWithDexieInternals => {\n const doc = docWithDexieInternals ? fromDexieToStorage(docWithDexieInternals) : docWithDexieInternals;\n if (doc) {\n docsInDbMap.set(doc[this.primaryPath], doc);\n }\n return doc;\n });\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDbMap,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Batch up the database operations\n * so we can later run them in bulk.\n */\n const bulkPutDocs: any[] = [];\n const bulkRemoveDocs: string[] = [];\n const bulkPutDeletedDocs: any[] = [];\n const bulkRemoveDeletedDocs: string[] = [];\n\n categorized.bulkInsertDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n bulkPutDocs.push(row.document);\n });\n categorized.bulkUpdateDocs.forEach(row => {\n const docId: string = (row.document as any)[this.primaryPath];\n ret.success[docId] = row.document as any;\n if (\n row.document._deleted &&\n (row.previous && !row.previous._deleted)\n ) {\n // newly deleted\n bulkRemoveDocs.push(docId);\n bulkPutDeletedDocs.push(row.document);\n } else if (\n row.document._deleted &&\n row.previous && row.previous._deleted\n ) {\n // deleted was modified but is still deleted\n bulkPutDeletedDocs.push(row.document);\n } else if (!row.document._deleted) {\n // non-deleted was changed\n bulkPutDocs.push(row.document);\n } else {\n throw newRxError('SNH', { args: { row } });\n }\n });\n\n await Promise.all([\n bulkPutDocs.length > 0 ? state.dexieTable.bulkPut(bulkPutDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDocs.length > 0 ? state.dexieTable.bulkDelete(bulkRemoveDocs) : PROMISE_RESOLVE_VOID,\n bulkPutDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkPut(bulkPutDeletedDocs.map(d => fromStorageToDexie(d))) : PROMISE_RESOLVE_VOID,\n bulkRemoveDeletedDocs.length > 0 ? state.dexieDeletedTable.bulkDelete(bulkRemoveDeletedDocs) : PROMISE_RESOLVE_VOID\n ]);\n });\n\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n const endTime = now();\n ensureNotFalsy(categorized).eventBulk.events.forEach(event => (event as any).endTime = endTime);\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n\n return ret;\n }\n\n async findDocumentsById(\n ids: string[],\n deleted: boolean\n ): Promise> {\n ensureNotClosed(this);\n const state = await this.internals;\n const ret: RxDocumentDataById = {};\n\n await state.dexieDb.transaction(\n 'r',\n state.dexieTable,\n state.dexieDeletedTable,\n async () => {\n let docsInDb: RxDocumentData[];\n if (deleted) {\n docsInDb = await getDocsInDb(this.internals, ids);\n } else {\n docsInDb = await state.dexieTable.bulkGet(ids);\n }\n ids.forEach((id, idx) => {\n const documentInDb = docsInDb[idx];\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = fromDexieToStorage(documentInDb);\n }\n });\n });\n return ret;\n }\n\n query(preparedQuery: DexiePreparedQuery): Promise> {\n ensureNotClosed(this);\n return dexieQuery(\n this,\n preparedQuery\n );\n }\n async count(\n preparedQuery: DexiePreparedQuery\n ): Promise {\n const result = await dexieCount(this, preparedQuery);\n return {\n count: result,\n mode: 'fast'\n };\n }\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n ensureNotClosed(this);\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n const state = await this.internals;\n\n\n const [changedDocsNormal, changedDocsDeleted] = await Promise.all(\n [\n state.dexieTable,\n state.dexieDeletedTable\n ].map(async (table) => {\n const query = table\n .where('[_meta.lwt+' + this.primaryPath + ']')\n .above([sinceLwt, sinceId])\n .limit(limit);\n const changedDocuments: RxDocumentData[] = await query.toArray();\n return changedDocuments.map(d => fromDexieToStorage(d));\n })\n );\n let changedDocs = changedDocsNormal.concat(changedDocsDeleted);\n\n changedDocs = sortDocumentsByLastWriteTime(this.primaryPath as any, changedDocs);\n changedDocs = changedDocs.slice(0, limit);\n\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n async remove(): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await Promise.all([\n state.dexieDeletedTable.clear(),\n state.dexieTable.clear()\n ]);\n return this.close();\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotClosed(this);\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n ensureNotClosed(this);\n const state = await this.internals;\n await state.dexieDb.transaction(\n 'rw',\n state.dexieDeletedTable,\n async () => {\n const maxDeletionTime = now() - minimumDeletedTime;\n const toRemove = await state.dexieDeletedTable\n .where('_meta.lwt')\n .below(maxDeletionTime)\n .toArray();\n const removeIds: string[] = toRemove.map(doc => doc[this.primaryPath]);\n await state.dexieDeletedTable.bulkDelete(removeIds);\n }\n );\n\n /**\n * TODO instead of deleting all deleted docs at once,\n * only clean up some of them and return false if there are more documents to clean up.\n * This ensures that when many documents have to be purged,\n * we do not block the more important tasks too long.\n */\n return true;\n }\n\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n ensureNotClosed(this);\n throw new Error('Attachments are not implemented in the dexie RxStorage. Make a pull request.');\n }\n\n close(): Promise {\n ensureNotClosed(this);\n this.closed = true;\n this.changes$.complete();\n closeDexieDb(this.internals);\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\n\nexport function createDexieStorageInstance(\n storage: RxStorageDexie,\n params: RxStorageInstanceCreationParams,\n settings: DexieSettings\n): Promise> {\n const internals = getDexieDbWithTables(\n params.databaseName,\n params.collectionName,\n settings,\n params.schema\n );\n\n const instance = new RxStorageInstanceDexie(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_DEXIE,\n params,\n instance\n );\n\n return Promise.resolve(instance);\n}\n\n\n\nfunction ensureNotClosed(\n instance: RxStorageInstanceDexie\n) {\n if (instance.closed) {\n throw new Error('RxStorageInstanceDexie is closed ' + instance.databaseName + '-' + instance.collectionName);\n }\n}\n"],"mappings":";;;;;;;;;;AAAA;AAIA;AAgCA;AAQA;AACA;AACA;AACA;AACA;AAEA,IAAIA,UAAU,GAAG,IAAAC,UAAG,GAAE;AAAC,IAEVC,sBAAsB;EAW/B,gCACoBC,OAAuB,EACvBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAAgC,EAChCC,OAAgC,EAChCC,QAAuB,EACzC;IAAA,KAZMC,QAAQ,GAAoG,IAAIC,aAAO,EAAE;IAAA,KACjHX,UAAU,GAAGA,UAAU,EAAE;IAAA,KAClCY,MAAM,GAAG,KAAK;IAAA,KAGDT,OAAuB,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IAAA+H,iCAAoB,EAClCD,MAAM,CAACjI,YAAY,EACnBiI,MAAM,CAAChI,cAAc,EACrBI,QAAQ,EACR4H,MAAM,CAAC/H,MAAM,CAChB;EAED,IAAMiI,QAAQ,GAAG,IAAIrI,sBAAsB,CACvCC,OAAO,EACPkI,MAAM,CAACjI,YAAY,EACnBiI,MAAM,CAAChI,cAAc,EACrBgI,MAAM,CAAC/H,MAAM,EACbC,SAAS,EACT8H,MAAM,CAAC7H,OAAO,EACdC,QAAQ,CACX;EAED,IAAA+H,wDAAgC,EAC5BC,kCAAqB,EACrBJ,MAAM,EACNE,QAAQ,CACX;EAED,OAAO9E,OAAO,CAACiF,OAAO,CAACH,QAAQ,CAAC;AACpC;AAIA,SAASpH,eAAe,CACpBoH,QAAqC,EACvC;EACE,IAAIA,QAAQ,CAAC3H,MAAM,EAAE;IACjB,MAAM,IAAIkH,KAAK,CAAC,mCAAmC,GAAGS,QAAQ,CAACnI,YAAY,GAAG,GAAG,GAAGmI,QAAQ,CAAClI,cAAc,CAAC;EAChH;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/foundationdb-helpers.js b/dist/lib/plugins/storage-foundationdb/foundationdb-helpers.js similarity index 100% rename from dist/lib/plugins/foundationdb/foundationdb-helpers.js rename to dist/lib/plugins/storage-foundationdb/foundationdb-helpers.js diff --git a/dist/lib/plugins/storage-foundationdb/foundationdb-helpers.js.map b/dist/lib/plugins/storage-foundationdb/foundationdb-helpers.js.map new file mode 100644 index 00000000000..113dd330f63 --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/foundationdb-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"foundationdb-helpers.js","names":["getFoundationDBIndexName","index","join","CLEANUP_INDEX"],"sources":["../../../../src/plugins/storage-foundationdb/foundationdb-helpers.ts"],"sourcesContent":["export function getFoundationDBIndexName(index: string[]): string {\n return index.join('|');\n}\nexport const CLEANUP_INDEX: string[] = ['_deleted', '_meta.lwt'];\n"],"mappings":";;;;;;;AAAO,SAASA,wBAAwB,CAACC,KAAe,EAAU;EAC9D,OAAOA,KAAK,CAACC,IAAI,CAAC,GAAG,CAAC;AAC1B;AACO,IAAMC,aAAuB,GAAG,CAAC,UAAU,EAAE,WAAW,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-foundationdb/foundationdb-query.js b/dist/lib/plugins/storage-foundationdb/foundationdb-query.js new file mode 100644 index 00000000000..94c1a7e05fa --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/foundationdb-query.js @@ -0,0 +1,134 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.queryFoundationDB = queryFoundationDB; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _customIndex = require("../../custom-index"); +var _utils = require("../../plugins/utils"); +var _storageDexie = require("../storage-dexie"); +var _foundationdbHelpers = require("./foundationdb-helpers"); +function queryFoundationDB(_x, _x2) { + return _queryFoundationDB.apply(this, arguments); +} +function _queryFoundationDB() { + _queryFoundationDB = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(instance, preparedQuery) { + var queryPlan, query, skip, limit, skipPlusLimit, queryPlanFields, mustManuallyResort, queryMatcher, dbs, indexForName, indexName, indexDB, lowerBound, lowerBoundString, upperBound, upperBoundString, result, sortComparator; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + queryPlan = preparedQuery.queryPlan; + query = preparedQuery.query; + skip = query.skip ? query.skip : 0; + limit = query.limit ? query.limit : Infinity; + skipPlusLimit = skip + limit; + queryPlanFields = queryPlan.index; + mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields; + queryMatcher = false; + if (!queryPlan.selectorSatisfiedByIndex) { + queryMatcher = _storageDexie.RxStorageDexieStatics.getQueryMatcher(instance.schema, preparedQuery); + } + _context2.next = 11; + return instance.internals.dbsPromise; + case 11: + dbs = _context2.sent; + indexForName = queryPlanFields.slice(0); + indexForName.unshift('_deleted'); + indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(indexForName); + indexDB = (0, _utils.ensureNotFalsy)(dbs.indexes[indexName]).db; + lowerBound = queryPlan.startKeys; + lowerBound = [false].concat(lowerBound); + lowerBoundString = (0, _customIndex.getStartIndexStringFromLowerBound)(instance.schema, indexForName, lowerBound, queryPlan.inclusiveStart); + upperBound = queryPlan.endKeys; + upperBound = [false].concat(upperBound); + upperBoundString = (0, _customIndex.getStartIndexStringFromUpperBound)(instance.schema, indexForName, upperBound, queryPlan.inclusiveEnd); + _context2.next = 24; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(tx) { + var innerResult, indexTx, mainTx, range, done, next, docIds, docsData; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + innerResult = []; + indexTx = tx.at(indexDB.subspace); + mainTx = tx.at(dbs.main.subspace); + range = indexTx.getRangeBatch(lowerBoundString, upperBoundString, { + // TODO these options seem to be broken in the foundationdb node bindings + // limit: instance.settings.batchSize, + // streamingMode: StreamingMode.Exact + }); + done = false; + case 5: + if (done) { + _context.next = 19; + break; + } + _context.next = 8; + return range.next(); + case 8: + next = _context.sent; + if (!next.done) { + _context.next = 12; + break; + } + done = true; + return _context.abrupt("break", 19); + case 12: + docIds = next.value.map(function (row) { + return row[1]; + }); + _context.next = 15; + return Promise.all(docIds.map(function (docId) { + return mainTx.get(docId); + })); + case 15: + docsData = _context.sent; + docsData.forEach(function (docData) { + if (!done) { + if (!queryMatcher || queryMatcher(docData)) { + innerResult.push(docData); + } + } + if (!mustManuallyResort && innerResult.length === skipPlusLimit) { + done = true; + range["return"](); + } + }); + _context.next = 5; + break; + case 19: + return _context.abrupt("return", innerResult); + case 20: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + case 24: + result = _context2.sent; + if (mustManuallyResort) { + sortComparator = _storageDexie.RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery); + result = result.sort(sortComparator); + } + + // apply skip and limit boundaries. + result = result.slice(skip, skipPlusLimit); + return _context2.abrupt("return", { + documents: result + }); + case 28: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _queryFoundationDB.apply(this, arguments); +} +//# sourceMappingURL=foundationdb-query.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-foundationdb/foundationdb-query.js.map b/dist/lib/plugins/storage-foundationdb/foundationdb-query.js.map new file mode 100644 index 00000000000..3b26c6d93cc --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/foundationdb-query.js.map @@ -0,0 +1 @@ +{"version":3,"file":"foundationdb-query.js","names":["queryFoundationDB","instance","preparedQuery","queryPlan","query","skip","limit","Infinity","skipPlusLimit","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","queryMatcher","selectorSatisfiedByIndex","RxStorageDexieStatics","getQueryMatcher","schema","internals","dbsPromise","dbs","indexForName","slice","unshift","indexName","getFoundationDBIndexName","indexDB","ensureNotFalsy","indexes","db","lowerBound","startKeys","concat","lowerBoundString","getStartIndexStringFromLowerBound","inclusiveStart","upperBound","endKeys","upperBoundString","getStartIndexStringFromUpperBound","inclusiveEnd","root","doTransaction","tx","innerResult","indexTx","at","subspace","mainTx","main","range","getRangeBatch","done","next","docIds","value","map","row","Promise","all","docId","get","docsData","forEach","docData","push","length","result","sortComparator","getSortComparator","sort","documents"],"sources":["../../../../src/plugins/storage-foundationdb/foundationdb-query.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport type {\n RxDocumentData,\n RxStorageQueryResult\n} from '../../types';\nimport { ensureNotFalsy } from '../../plugins/utils';\nimport { RxStorageDexieStatics } from '../storage-dexie';\nimport { getFoundationDBIndexName } from './foundationdb-helpers';\nimport type {\n FoundationDBPreparedQuery\n} from './foundationdb-types';\nimport { RxStorageInstanceFoundationDB } from './rx-storage-instance-foundationdb';\n\nexport async function queryFoundationDB(\n instance: RxStorageInstanceFoundationDB,\n preparedQuery: FoundationDBPreparedQuery\n): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n instance.schema,\n preparedQuery\n );\n }\n\n const dbs = await instance.internals.dbsPromise;\n\n\n const indexForName = queryPlanFields.slice(0);\n indexForName.unshift('_deleted');\n const indexName = getFoundationDBIndexName(indexForName);\n const indexDB = ensureNotFalsy(dbs.indexes[indexName]).db;\n\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n instance.schema,\n indexForName,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n instance.schema,\n indexForName,\n upperBound,\n queryPlan.inclusiveEnd\n );\n let result = await dbs.root.doTransaction(async (tx: any) => {\n const innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexDB.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n\n const range = indexTx.getRangeBatch(\n lowerBoundString,\n upperBoundString,\n {\n // TODO these options seem to be broken in the foundationdb node bindings\n // limit: instance.settings.batchSize,\n // streamingMode: StreamingMode.Exact\n }\n );\n let done = false;\n while (!done) {\n const next = await range.next();\n if (next.done) {\n done = true;\n break;\n }\n const docIds = next.value.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n docsData.forEach((docData) => {\n if (!done) {\n if (!queryMatcher || queryMatcher(docData)) {\n innerResult.push(docData);\n }\n }\n if (\n !mustManuallyResort &&\n innerResult.length === skipPlusLimit\n ) {\n done = true;\n range.return();\n }\n });\n }\n return innerResult;\n });\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(instance.schema, preparedQuery);\n result = result.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n result = result.slice(skip, skipPlusLimit);\n\n return {\n documents: result\n };\n}\n"],"mappings":";;;;;;;;;AACA;AAQA;AACA;AACA;AAAkE,SAM5CA,iBAAiB;EAAA;AAAA;AAAA;EAAA,mGAAhC,kBACHC,QAAkD,EAClDC,aAAmD;IAAA;IAAA;MAAA;QAAA;UAE7CC,SAAS,GAAGD,aAAa,CAACC,SAAS;UACnCC,KAAK,GAAGF,aAAa,CAACE,KAAK;UAC3BC,IAAI,GAAGD,KAAK,CAACC,IAAI,GAAGD,KAAK,CAACC,IAAI,GAAG,CAAC;UAClCC,KAAK,GAAGF,KAAK,CAACE,KAAK,GAAGF,KAAK,CAACE,KAAK,GAAGC,QAAQ;UAC5CC,aAAa,GAAGH,IAAI,GAAGC,KAAK;UAC5BG,eAAyB,GAAGN,SAAS,CAACO,KAAK;UAC3CC,kBAAkB,GAAG,CAACR,SAAS,CAACS,2BAA2B;UAG7DC,YAA6D,GAAG,KAAK;UACzE,IAAI,CAACV,SAAS,CAACW,wBAAwB,EAAE;YACrCD,YAAY,GAAGE,mCAAqB,CAACC,eAAe,CAChDf,QAAQ,CAACgB,MAAM,EACff,aAAa,CAChB;UACL;UAAC;UAAA,OAEiBD,QAAQ,CAACiB,SAAS,CAACC,UAAU;QAAA;UAAzCC,GAAG;UAGHC,YAAY,GAAGZ,eAAe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AAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACJ;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/foundationdb-types.js b/dist/lib/plugins/storage-foundationdb/foundationdb-types.js similarity index 100% rename from dist/lib/plugins/foundationdb/foundationdb-types.js rename to dist/lib/plugins/storage-foundationdb/foundationdb-types.js diff --git a/dist/lib/plugins/storage-foundationdb/foundationdb-types.js.map b/dist/lib/plugins/storage-foundationdb/foundationdb-types.js.map new file mode 100644 index 00000000000..8f74dc14034 --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/foundationdb-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"foundationdb-types.js","names":[],"sources":["../../../../src/plugins/storage-foundationdb/foundationdb-types.ts"],"sourcesContent":["/* eslint-disable no-unused-vars */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type {\n DexiePreparedQuery,\n EventBulk,\n RxAttachmentWriteData,\n RxDocumentData,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types';\nexport type RxStorageFoundationDBSettings = {\n /**\n * Version of the API of the foundationDB server.\n */\n apiVersion: number;\n /**\n * Path to the foundationDB cluster file\n * like '/path/to/fdb.cluster'\n * (optional)\n */\n clusterFile?: string;\n batchSize?: number;\n};\nexport type RxStorageFoundationDBInstanceCreationOptions = {\n // can be overwritte per instance\n batchSize?: number;\n};\n\n/**\n * TODO atm we cannot import types from 'foundationdb'\n * because 'foundationdb' is an optional peer dependency\n * this is NOT also in the devDependencies.\n * This is because it requires to install the foundationdb client cli\n * which would mean everyone that wants to develop RxDB must have this installed manually.\n */\n// import {\n// open as foundationDBOpen,\n// Database,\n// Transaction\n// } from 'foundationdb';\n\nexport type FoundationDBIndexMeta = {\n indexName: string;\n index: string[];\n getIndexableString: (doc: RxDocumentData) => string;\n db: FoundationDBDatabase;\n};\n\nexport type FoundationDBConnection = any; // ReturnType;\nexport type FoundationDBDatabase = any; // Database;\nexport type FoundationDBTransaction = any; // Transaction, any>;\nexport type FoundationDBStorageInternals = {\n connection: FoundationDBConnection;\n dbsPromise: Promise<{\n root: FoundationDBDatabase;\n main: FoundationDBDatabase;\n attachments: FoundationDBDatabase;\n events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>>;\n indexes: {\n [indexName: string]: FoundationDBIndexMeta;\n };\n }>;\n};\nexport type RxStorageFoundationDB = RxStorage, RxStorageFoundationDBInstanceCreationOptions> & {\n};\n\n\nexport type FoundationDBPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/foundationdb/index.js b/dist/lib/plugins/storage-foundationdb/index.js similarity index 97% rename from dist/lib/plugins/foundationdb/index.js rename to dist/lib/plugins/storage-foundationdb/index.js index d2d5b763c9b..0d768cd9ce2 100644 --- a/dist/lib/plugins/foundationdb/index.js +++ b/dist/lib/plugins/storage-foundationdb/index.js @@ -8,7 +8,7 @@ var _exportNames = { }; exports.getRxStorageFoundationDB = getRxStorageFoundationDB; var _rxStorageHelper = require("../../rx-storage-helper"); -var _dexieStatics = require("../dexie/dexie-statics"); +var _dexieStatics = require("../storage-dexie/dexie-statics"); var _rxStorageInstanceFoundationdb = require("./rx-storage-instance-foundationdb"); var _foundationdbTypes = require("./foundationdb-types"); Object.keys(_foundationdbTypes).forEach(function (key) { diff --git a/dist/lib/plugins/storage-foundationdb/index.js.map b/dist/lib/plugins/storage-foundationdb/index.js.map new file mode 100644 index 00000000000..1f97f95028c --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["versionSet","getRxStorageFoundationDB","settings","apiVersion","Error","require","setAPIVersion","storage","name","statics","RxStorageDexieStatics","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","useSettings","Object","assign","options","batchSize","createFoundationDBStorageInstance"],"sources":["../../../../src/plugins/storage-foundationdb/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type {\n RxStorageInstanceCreationParams\n} from '../../types';\nimport { RxStorageDexieStatics } from '../storage-dexie/dexie-statics';\nimport type {\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n\nimport {\n createFoundationDBStorageInstance,\n RxStorageInstanceFoundationDB\n} from './rx-storage-instance-foundationdb';\n\n\nlet versionSet: undefined | number;\n\nexport function getRxStorageFoundationDB(\n settings: RxStorageFoundationDBSettings\n): RxStorageFoundationDB {\n if (versionSet && versionSet !== settings.apiVersion) {\n throw new Error('foundationdb already initialized with api version ' + versionSet);\n } else if (!versionSet) {\n versionSet = settings.apiVersion;\n const { setAPIVersion } = require('foundationdb');\n setAPIVersion(settings.apiVersion);\n }\n\n\n const storage: RxStorageFoundationDB = {\n name: 'foundationdb',\n statics: RxStorageDexieStatics,\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n if (!useSettings.batchSize) {\n useSettings.batchSize = 50;\n }\n return createFoundationDBStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './foundationdb-types';\nexport * from './foundationdb-helpers';\n"],"mappings":";;;;;;;;;AAAA;AAIA;AAOA;AA2CA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAtCA,IAAIA,UAA8B;AAE3B,SAASC,wBAAwB,CACpCC,QAAuC,EAClB;EACrB,IAAIF,UAAU,IAAIA,UAAU,KAAKE,QAAQ,CAACC,UAAU,EAAE;IAClD,MAAM,IAAIC,KAAK,CAAC,oDAAoD,GAAGJ,UAAU,CAAC;EACtF,CAAC,MAAM,IAAI,CAACA,UAAU,EAAE;IACpBA,UAAU,GAAGE,QAAQ,CAACC,UAAU;IAChC,eAA0BE,OAAO,CAAC,cAAc,CAAC;MAAzCC,aAAa,YAAbA,aAAa;IACrBA,aAAa,CAACJ,QAAQ,CAACC,UAAU,CAAC;EACtC;EAGA,IAAMI,OAA8B,GAAG;IACnCC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAEC,mCAAqB;IAC9BC,qBAAqB,iCACjBC,MAAgG,EAC/C;MACjD,IAAAC,wDAAuC,EAACD,MAAM,CAAC;MAC/C,IAAME,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFd,QAAQ,EACRU,MAAM,CAACK,OAAO,CACjB;MACD,IAAI,CAACH,WAAW,CAACI,SAAS,EAAE;QACxBJ,WAAW,CAACI,SAAS,GAAG,EAAE;MAC9B;MACA,OAAO,IAAAC,gEAAiC,EAAC,IAAI,EAAEP,MAAM,EAAEE,WAAW,CAAC;IACvE;EACJ,CAAC;EAED,OAAOP,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js b/dist/lib/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js new file mode 100644 index 00000000000..d893d1c79c3 --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js @@ -0,0 +1,607 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RxStorageInstanceFoundationDB = void 0; +exports.createFoundationDBStorageInstance = createFoundationDBStorageInstance; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _rxjs = require("rxjs"); +var _rxSchemaHelper = require("../../rx-schema-helper"); +var _rxStorageHelper = require("../../rx-storage-helper"); +var _foundationdbHelpers = require("./foundationdb-helpers"); +var _customIndex = require("../../custom-index"); +var _utils = require("../../plugins/utils"); +var _foundationdbQuery = require("./foundationdb-query"); +var _queryPlanner = require("../../query-planner"); +var _storageMemory = require("../storage-memory"); +// import { +// open as foundationDBOpen, +// directory as foundationDBDirectory, +// encoders as foundationDBEncoders, +// keySelector as foundationDBKeySelector, +// StreamingMode as foundationDBStreamingMode +// } from 'foundationdb'; +var RxStorageInstanceFoundationDB = /*#__PURE__*/function () { + function RxStorageInstanceFoundationDB(storage, databaseName, collectionName, schema, internals, options, settings) { + this.closed = false; + this.changes$ = new _rxjs.Subject(); + this.storage = storage; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + this.settings = settings; + this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); + } + var _proto = RxStorageInstanceFoundationDB.prototype; + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(documentWrites, context) { + var _this = this; + var dbs, categorized, result, lastState; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context3.sent; + categorized = null; + _context3.next = 6; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(tx) { + var ret, ids, mainTx, attachmentTx, docsInDB; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + ret = { + success: {}, + error: {} + }; + ids = documentWrites.map(function (row) { + return row.document[_this.primaryPath]; + }); + mainTx = tx.at(dbs.main.subspace); + attachmentTx = tx.at(dbs.attachments.subspace); + docsInDB = new Map(); + /** + * TODO this might be faster if fdb + * any time adds a bulk-fetch-by-key method. + */ + _context2.next = 7; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(id) { + var doc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return mainTx.get(id); + case 2: + doc = _context.sent; + docsInDB.set(id, doc); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x4) { + return _ref2.apply(this, arguments); + }; + }())); + case 7: + categorized = (0, _rxStorageHelper.categorizeBulkWriteRows)(_this, _this.primaryPath, docsInDB, documentWrites, context); + ret.error = categorized.errors; + + // INSERTS + categorized.bulkInsertDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this.primaryPath]; + ret.success[docId] = writeRow.document; + + // insert document data + mainTx.set(docId, writeRow.document); + + // insert secondary indexes + Object.values(dbs.indexes).forEach(function (indexMeta) { + var indexString = indexMeta.getIndexableString(writeRow.document); + var indexTx = tx.at(indexMeta.db.subspace); + indexTx.set(indexString, docId); + }); + }); + // UPDATES + categorized.bulkUpdateDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this.primaryPath]; + + // overwrite document data + mainTx.set(docId, writeRow.document); + + // update secondary indexes + Object.values(dbs.indexes).forEach(function (indexMeta) { + var oldIndexString = indexMeta.getIndexableString((0, _utils.ensureNotFalsy)(writeRow.previous)); + var newIndexString = indexMeta.getIndexableString(writeRow.document); + if (oldIndexString !== newIndexString) { + var indexTx = tx.at(indexMeta.db.subspace); + indexTx["delete"](oldIndexString); + indexTx.set(newIndexString, docId); + } + }); + ret.success[docId] = writeRow.document; + }); + + // attachments + categorized.attachmentsAdd.forEach(function (attachment) { + attachmentTx.set((0, _storageMemory.attachmentMapKey)(attachment.documentId, attachment.attachmentId), attachment.attachmentData); + }); + categorized.attachmentsUpdate.forEach(function (attachment) { + attachmentTx.set((0, _storageMemory.attachmentMapKey)(attachment.documentId, attachment.attachmentId), attachment.attachmentData); + }); + categorized.attachmentsRemove.forEach(function (attachment) { + attachmentTx["delete"]((0, _storageMemory.attachmentMapKey)(attachment.documentId, attachment.attachmentId)); + }); + return _context2.abrupt("return", ret); + case 15: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + case 6: + result = _context3.sent; + /** + * The events must be emitted AFTER the transaction + * has finished. + * Otherwise an observable changestream might cause a read + * to a document that does not already exist outside of the transaction. + */ + if ((0, _utils.ensureNotFalsy)(categorized).eventBulk.events.length > 0) { + lastState = (0, _rxStorageHelper.getNewestOfDocumentStates)(this.primaryPath, Object.values(result.success)); + (0, _utils.ensureNotFalsy)(categorized).eventBulk.checkpoint = { + id: lastState[this.primaryPath], + lwt: lastState._meta.lwt + }; + this.changes$.next((0, _utils.ensureNotFalsy)(categorized).eventBulk); + } + return _context3.abrupt("return", result); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function bulkWrite(_x, _x2) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(); + _proto.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(ids, withDeleted) { + var dbs; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context6.sent; + return _context6.abrupt("return", dbs.main.doTransaction( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(tx) { + var ret; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + ret = {}; + _context5.next = 3; + return Promise.all(ids.map( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(docId) { + var docInDb; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return tx.get(docId); + case 2: + docInDb = _context4.sent; + if (docInDb && (!docInDb._deleted || withDeleted)) { + ret[docId] = docInDb; + } + case 4: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return function (_x8) { + return _ref4.apply(this, arguments); + }; + }())); + case 3: + return _context5.abrupt("return", ret); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x7) { + return _ref3.apply(this, arguments); + }; + }())); + case 4: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function findDocumentsById(_x5, _x6) { + return _findDocumentsById.apply(this, arguments); + } + return findDocumentsById; + }(); + _proto.query = function query(preparedQuery) { + return (0, _foundationdbQuery.queryFoundationDB)(this, preparedQuery); + }; + _proto.count = /*#__PURE__*/function () { + var _count = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(preparedQuery) { + var result; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.query(preparedQuery); + case 2: + result = _context7.sent; + return _context7.abrupt("return", { + count: result.documents.length, + mode: 'fast' + }); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function count(_x9) { + return _count.apply(this, arguments); + } + return count; + }(); + _proto.getAttachmentData = /*#__PURE__*/function () { + var _getAttachmentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(documentId, attachmentId) { + var dbs, attachment; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context8.sent; + _context8.next = 5; + return dbs.attachments.get((0, _storageMemory.attachmentMapKey)(documentId, attachmentId)); + case 5: + attachment = _context8.sent; + return _context8.abrupt("return", attachment.data); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function getAttachmentData(_x10, _x11) { + return _getAttachmentData.apply(this, arguments); + } + return getAttachmentData; + }(); + _proto.getChangedDocumentsSince = /*#__PURE__*/function () { + var _getChangedDocumentsSince = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(limit, checkpoint) { + var _require, keySelector, StreamingMode, dbs, index, indexName, indexMeta, lowerBoundString, _checkpointPartialDoc, checkpointPartialDoc, result, lastDoc; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + _require = require('foundationdb'), keySelector = _require.keySelector, StreamingMode = _require.StreamingMode; + _context10.next = 3; + return this.internals.dbsPromise; + case 3: + dbs = _context10.sent; + index = ['_meta.lwt', this.primaryPath]; + indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(index); + indexMeta = dbs.indexes[indexName]; + lowerBoundString = ''; + if (checkpoint) { + checkpointPartialDoc = (_checkpointPartialDoc = {}, _checkpointPartialDoc[this.primaryPath] = checkpoint.id, _checkpointPartialDoc._meta = { + lwt: checkpoint.lwt + }, _checkpointPartialDoc); + lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc); + } + _context10.next = 11; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(tx) { + var innerResult, indexTx, mainTx, range, docIds, docsData; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + innerResult = []; + indexTx = tx.at(indexMeta.db.subspace); + mainTx = tx.at(dbs.main.subspace); + _context9.next = 5; + return indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), _queryPlanner.INDEX_MAX, { + limit: limit, + streamingMode: StreamingMode.Exact + }); + case 5: + range = _context9.sent; + docIds = range.map(function (row) { + return row[1]; + }); + _context9.next = 9; + return Promise.all(docIds.map(function (docId) { + return mainTx.get(docId); + })); + case 9: + docsData = _context9.sent; + innerResult = innerResult.concat(docsData); + return _context9.abrupt("return", innerResult); + case 12: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + return function (_x14) { + return _ref5.apply(this, arguments); + }; + }()); + case 11: + result = _context10.sent; + lastDoc = (0, _utils.lastOfArray)(result); + return _context10.abrupt("return", { + documents: result, + checkpoint: lastDoc ? { + id: lastDoc[this.primaryPath], + lwt: lastDoc._meta.lwt + } : checkpoint ? checkpoint : { + id: '', + lwt: 0 + } + }); + case 14: + case "end": + return _context10.stop(); + } + }, _callee10, this); + })); + function getChangedDocumentsSince(_x12, _x13) { + return _getChangedDocumentsSince.apply(this, arguments); + } + return getChangedDocumentsSince; + }(); + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11() { + var dbs; + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return this.internals.dbsPromise; + case 2: + dbs = _context11.sent; + _context11.next = 5; + return dbs.root.doTransaction(function (tx) { + tx.clearRange('', _queryPlanner.INDEX_MAX); + return _utils.PROMISE_RESOLVE_VOID; + }); + case 5: + return _context11.abrupt("return", this.close()); + case 6: + case "end": + return _context11.stop(); + } + }, _callee11, this); + })); + function remove() { + return _remove.apply(this, arguments); + } + return remove; + }(); + _proto.cleanup = /*#__PURE__*/function () { + var _cleanup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(minimumDeletedTime) { + var _this2 = this; + var _require2, keySelector, StreamingMode, maxDeletionTime, dbs, index, indexName, indexMeta, lowerBoundString, upperBoundString, noMoreUndeleted; + return _regenerator["default"].wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + _require2 = require('foundationdb'), keySelector = _require2.keySelector, StreamingMode = _require2.StreamingMode; + maxDeletionTime = (0, _utils.now)() - minimumDeletedTime; + _context13.next = 4; + return this.internals.dbsPromise; + case 4: + dbs = _context13.sent; + index = _foundationdbHelpers.CLEANUP_INDEX; + indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(index); + indexMeta = dbs.indexes[indexName]; + lowerBoundString = (0, _customIndex.getStartIndexStringFromLowerBound)(this.schema, index, [true, + /** + * Do not use 0 here, + * because 1 is the minimum value for _meta.lwt + */ + 1], false); + upperBoundString = (0, _customIndex.getStartIndexStringFromUpperBound)(this.schema, index, [true, maxDeletionTime], true); + noMoreUndeleted = true; + _context13.next = 13; + return dbs.root.doTransaction( /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(tx) { + var batchSize, indexTx, mainTx, range, docIds, docsData; + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + batchSize = (0, _utils.ensureNotFalsy)(_this2.settings.batchSize); + indexTx = tx.at(indexMeta.db.subspace); + mainTx = tx.at(dbs.main.subspace); + _context12.next = 5; + return indexTx.getRangeAll(keySelector.firstGreaterThan(lowerBoundString), upperBoundString, { + limit: batchSize + 1, + // get one more extra to detect what to return from cleanup() + streamingMode: StreamingMode.Exact + }); + case 5: + range = _context12.sent; + if (range.length > batchSize) { + noMoreUndeleted = false; + range.pop(); + } + docIds = range.map(function (row) { + return row[1]; + }); + _context12.next = 10; + return Promise.all(docIds.map(function (docId) { + return mainTx.get(docId); + })); + case 10: + docsData = _context12.sent; + Object.values(dbs.indexes).forEach(function (indexMetaInner) { + var subIndexDB = tx.at(indexMetaInner.db.subspace); + docsData.forEach(function (docData) { + var indexString = indexMetaInner.getIndexableString(docData); + subIndexDB["delete"](indexString); + }); + }); + docIds.forEach(function (id) { + return mainTx["delete"](id); + }); + case 13: + case "end": + return _context12.stop(); + } + }, _callee12); + })); + return function (_x16) { + return _ref6.apply(this, arguments); + }; + }()); + case 13: + return _context13.abrupt("return", noMoreUndeleted); + case 14: + case "end": + return _context13.stop(); + } + }, _callee13, this); + })); + function cleanup(_x15) { + return _cleanup.apply(this, arguments); + } + return cleanup; + }(); + _proto.conflictResultionTasks = function conflictResultionTasks() { + return new _rxjs.Subject().asObservable(); + }; + _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { + return _utils.PROMISE_RESOLVE_VOID; + }; + _proto.close = /*#__PURE__*/function () { + var _close = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee14() { + var dbs; + return _regenerator["default"].wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + if (!this.closed) { + _context14.next = 2; + break; + } + return _context14.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.changes$.complete(); + _context14.next = 6; + return this.internals.dbsPromise; + case 6: + dbs = _context14.sent; + dbs.root.close(); + + // TODO shouldn't we close the index databases? + // Object.values(dbs.indexes).forEach(db => db.close()); + case 8: + case "end": + return _context14.stop(); + } + }, _callee14, this); + })); + function close() { + return _close.apply(this, arguments); + } + return close; + }(); + return RxStorageInstanceFoundationDB; +}(); +exports.RxStorageInstanceFoundationDB = RxStorageInstanceFoundationDB; +function createFoundationDBStorageInstance(storage, params, settings) { + var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(params.schema.primaryKey); + var _require3 = require('foundationdb'), + open = _require3.open, + directory = _require3.directory, + encoders = _require3.encoders; + var connection = open(settings.clusterFile); + var dbsPromise = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee15() { + var dir, root, main, events, attachments, indexDBs, useIndexes, useIndexesFinal; + return _regenerator["default"].wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + _context15.next = 2; + return directory.createOrOpen(connection, 'rxdb'); + case 2: + dir = _context15.sent; + root = connection.at(dir).at(params.databaseName + '.').at(params.collectionName + '.').at(params.schema.version + '.'); + main = root.at('main.').withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples + .withValueEncoding(encoders.json); // and values using JSON + events = root.at('events.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); + attachments = root.at('attachments.').withKeyEncoding(encoders.string).withValueEncoding(encoders.json); + indexDBs = {}; + useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : []; + useIndexes.push([primaryPath]); + useIndexesFinal = useIndexes.map(function (index) { + var indexAr = (0, _utils.toArray)(index); + indexAr.unshift('_deleted'); + return indexAr; + }); // used for `getChangedDocumentsSince()` + useIndexesFinal.push(['_meta.lwt', primaryPath]); + useIndexesFinal.push(_foundationdbHelpers.CLEANUP_INDEX); + useIndexesFinal.forEach(function (indexAr) { + var indexName = (0, _foundationdbHelpers.getFoundationDBIndexName)(indexAr); + var indexDB = root.at(indexName + '.').withKeyEncoding(encoders.string).withValueEncoding(encoders.string); + indexDBs[indexName] = { + indexName: indexName, + db: indexDB, + getIndexableString: (0, _customIndex.getIndexableStringMonad)(params.schema, indexAr), + index: indexAr + }; + }); + return _context15.abrupt("return", { + root: root, + main: main, + events: events, + attachments: attachments, + indexes: indexDBs + }); + case 15: + case "end": + return _context15.stop(); + } + }, _callee15); + }))(); + var internals = { + connection: connection, + dbsPromise: dbsPromise + }; + var instance = new RxStorageInstanceFoundationDB(storage, params.databaseName, params.collectionName, params.schema, internals, params.options, settings); + return Promise.resolve(instance); +} +//# sourceMappingURL=rx-storage-instance-foundationdb.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js.map b/dist/lib/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js.map new file mode 100644 index 00000000000..9f3d50c63e3 --- /dev/null +++ b/dist/lib/plugins/storage-foundationdb/rx-storage-instance-foundationdb.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-foundationdb.js","names":["RxStorageInstanceFoundationDB","storage","databaseName","collectionName","schema","internals","options","settings","closed","changes$","Subject","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","bulkWrite","documentWrites","context","dbsPromise","dbs","categorized","root","doTransaction","tx","ret","success","error","ids","map","row","document","mainTx","at","main","subspace","attachmentTx","attachments","docsInDB","Map","Promise","all","id","get","doc","set","categorizeBulkWriteRows","errors","bulkInsertDocs","forEach","writeRow","docId","Object","values","indexes","indexMeta","indexString","getIndexableString","indexTx","db","bulkUpdateDocs","oldIndexString","ensureNotFalsy","previous","newIndexString","attachmentsAdd","attachment","attachmentMapKey","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","result","eventBulk","events","length","lastState","getNewestOfDocumentStates","checkpoint","lwt","_meta","next","findDocumentsById","withDeleted","docInDb","_deleted","query","preparedQuery","queryFoundationDB","count","documents","mode","getAttachmentData","data","getChangedDocumentsSince","limit","require","keySelector","StreamingMode","index","indexName","getFoundationDBIndexName","lowerBoundString","checkpointPartialDoc","innerResult","getRangeAll","firstGreaterThan","INDEX_MAX","streamingMode","Exact","range","docIds","docsData","concat","lastDoc","lastOfArray","changeStream","asObservable","remove","clearRange","PROMISE_RESOLVE_VOID","close","cleanup","minimumDeletedTime","maxDeletionTime","now","CLEANUP_INDEX","getStartIndexStringFromLowerBound","upperBoundString","getStartIndexStringFromUpperBound","noMoreUndeleted","batchSize","pop","indexMetaInner","subIndexDB","docData","conflictResultionTasks","resolveConflictResultionTask","_taskSolution","reject","Error","complete","createFoundationDBStorageInstance","params","open","directory","encoders","connection","clusterFile","createOrOpen","dir","version","withKeyEncoding","string","withValueEncoding","json","indexDBs","useIndexes","slice","push","useIndexesFinal","indexAr","toArray","unshift","indexDB","getIndexableStringMonad","instance","resolve"],"sources":["../../../../src/plugins/storage-foundationdb/rx-storage-instance-foundationdb.ts"],"sourcesContent":["import { Observable, Subject } from 'rxjs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type {\n BulkWriteRow,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport type {\n FoundationDBDatabase,\n FoundationDBIndexMeta,\n FoundationDBPreparedQuery,\n FoundationDBStorageInternals,\n RxStorageFoundationDB,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageFoundationDBSettings\n} from './foundationdb-types';\n// import {\n// open as foundationDBOpen,\n// directory as foundationDBDirectory,\n// encoders as foundationDBEncoders,\n// keySelector as foundationDBKeySelector,\n// StreamingMode as foundationDBStreamingMode\n// } from 'foundationdb';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport {\n\n CLEANUP_INDEX,\n getFoundationDBIndexName\n} from './foundationdb-helpers';\nimport {\n getIndexableStringMonad,\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport {\n ensureNotFalsy,\n lastOfArray,\n now,\n PROMISE_RESOLVE_VOID,\n toArray\n} from '../../plugins/utils';\nimport { queryFoundationDB } from './foundationdb-query';\nimport { INDEX_MAX } from '../../query-planner';\nimport { attachmentMapKey } from '../storage-memory';\n\nexport class RxStorageInstanceFoundationDB implements RxStorageInstance<\n RxDocType,\n FoundationDBStorageInternals,\n RxStorageFoundationDBInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n public readonly primaryPath: StringKeys>;\n\n public closed = false;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n\n constructor(\n public readonly storage: RxStorageFoundationDB,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: FoundationDBStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageFoundationDBSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n const dbs = await this.internals.dbsPromise;\n let categorized: CategorizeBulkWriteRowsOutput | undefined = null as any;\n const result = await dbs.root.doTransaction(async (tx: any) => {\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const ids = documentWrites.map(row => (row.document as any)[this.primaryPath]);\n const mainTx = tx.at(dbs.main.subspace);\n const attachmentTx = tx.at(dbs.attachments.subspace);\n const docsInDB = new Map>();\n /**\n * TODO this might be faster if fdb\n * any time adds a bulk-fetch-by-key method.\n */\n await Promise.all(\n ids.map(async (id) => {\n const doc = await mainTx.get(id);\n docsInDB.set(id, doc);\n })\n );\n\n\n categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDB,\n documentWrites,\n context\n );\n\n ret.error = categorized.errors;\n\n // INSERTS\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n ret.success[docId] = writeRow.document as any;\n\n // insert document data\n mainTx.set(docId, writeRow.document);\n\n // insert secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const indexString = indexMeta.getIndexableString(writeRow.document as any);\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.set(indexString, docId);\n });\n });\n // UPDATES\n categorized.bulkUpdateDocs.forEach((writeRow: BulkWriteRow) => {\n const docId: string = writeRow.document[this.primaryPath] as any;\n\n // overwrite document data\n mainTx.set(docId, writeRow.document);\n\n // update secondary indexes\n Object.values(dbs.indexes).forEach(indexMeta => {\n const oldIndexString = indexMeta.getIndexableString(ensureNotFalsy(writeRow.previous));\n const newIndexString = indexMeta.getIndexableString(writeRow.document as any);\n if (oldIndexString !== newIndexString) {\n const indexTx = tx.at(indexMeta.db.subspace);\n indexTx.delete(oldIndexString);\n indexTx.set(newIndexString, docId);\n }\n });\n ret.success[docId] = writeRow.document as any;\n });\n\n // attachments\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentTx.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentTx.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n\n return ret;\n });\n /**\n * The events must be emitted AFTER the transaction\n * has finished.\n * Otherwise an observable changestream might cause a read\n * to a document that does not already exist outside of the transaction.\n */\n if (ensureNotFalsy(categorized).eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(result.success)\n );\n ensureNotFalsy(categorized).eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(ensureNotFalsy(categorized).eventBulk);\n }\n return result;\n }\n\n async findDocumentsById(ids: string[], withDeleted: boolean): Promise> {\n const dbs = await this.internals.dbsPromise;\n return dbs.main.doTransaction(async (tx: any) => {\n const ret: RxDocumentDataById = {};\n await Promise.all(\n ids.map(async (docId) => {\n const docInDb = await tx.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n })\n );\n return ret;\n });\n }\n query(preparedQuery: FoundationDBPreparedQuery): Promise> {\n return queryFoundationDB(this, preparedQuery);\n }\n async count(\n preparedQuery: FoundationDBPreparedQuery\n ): Promise {\n /**\n * At this point in time (end 2022), FoundationDB does not support\n * range counts. So we have to run a normal query and use the result set length.\n * @link https://github.com/apple/foundationdb/issues/5981\n */\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n async getAttachmentData(documentId: string, attachmentId: string): Promise {\n const dbs = await this.internals.dbsPromise;\n const attachment = await dbs.attachments.get(attachmentMapKey(documentId, attachmentId));\n return attachment.data;\n }\n async getChangedDocumentsSince(limit: number, checkpoint?: RxStorageDefaultCheckpoint): Promise<{ documents: RxDocumentData[]; checkpoint: RxStorageDefaultCheckpoint; }> {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const dbs = await this.internals.dbsPromise;\n const index = [\n '_meta.lwt',\n this.primaryPath as any\n ];\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n let lowerBoundString = '';\n if (checkpoint) {\n const checkpointPartialDoc: any = {\n [this.primaryPath]: checkpoint.id,\n _meta: {\n lwt: checkpoint.lwt\n }\n };\n lowerBoundString = indexMeta.getIndexableString(checkpointPartialDoc);\n }\n const result: RxDocumentData[] = await dbs.root.doTransaction(async (tx: any) => {\n let innerResult: RxDocumentData[] = [];\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n INDEX_MAX,\n {\n limit,\n streamingMode: StreamingMode.Exact\n }\n );\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(\n docIds.map((docId: string) => mainTx.get(docId))\n );\n innerResult = innerResult.concat(docsData);\n return innerResult;\n });\n const lastDoc = lastOfArray(result);\n return {\n documents: result,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n changeStream(): Observable, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async remove(): Promise {\n const dbs = await this.internals.dbsPromise;\n await dbs.root.doTransaction((tx: any) => {\n tx.clearRange('', INDEX_MAX);\n return PROMISE_RESOLVE_VOID;\n });\n return this.close();\n }\n async cleanup(minimumDeletedTime: number): Promise {\n const {\n keySelector,\n StreamingMode\n } = require('foundationdb');\n const maxDeletionTime = now() - minimumDeletedTime;\n const dbs = await this.internals.dbsPromise;\n const index = CLEANUP_INDEX;\n const indexName = getFoundationDBIndexName(index);\n const indexMeta = dbs.indexes[indexName];\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n /**\n * Do not use 0 here,\n * because 1 is the minimum value for _meta.lwt\n */\n 1\n ],\n false\n );\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n [\n true,\n maxDeletionTime\n ],\n true\n );\n let noMoreUndeleted: boolean = true;\n await dbs.root.doTransaction(async (tx: any) => {\n const batchSize = ensureNotFalsy(this.settings.batchSize);\n const indexTx = tx.at(indexMeta.db.subspace);\n const mainTx = tx.at(dbs.main.subspace);\n const range = await indexTx.getRangeAll(\n keySelector.firstGreaterThan(lowerBoundString),\n upperBoundString,\n {\n limit: batchSize + 1, // get one more extra to detect what to return from cleanup()\n streamingMode: StreamingMode.Exact\n }\n );\n if (range.length > batchSize) {\n noMoreUndeleted = false;\n range.pop();\n }\n const docIds = range.map((row: string[]) => row[1]);\n const docsData: RxDocumentData[] = await Promise.all(docIds.map((docId: string) => mainTx.get(docId)));\n\n Object\n .values(dbs.indexes)\n .forEach(indexMetaInner => {\n const subIndexDB = tx.at(indexMetaInner.db.subspace);\n docsData.forEach(docData => {\n const indexString = indexMetaInner.getIndexableString(docData);\n subIndexDB.delete(indexString);\n });\n });\n docIds.forEach((id: string) => mainTx.delete(id));\n });\n\n return noMoreUndeleted;\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject().asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n\n async close() {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n\n const dbs = await this.internals.dbsPromise;\n dbs.root.close();\n\n // TODO shouldn't we close the index databases?\n // Object.values(dbs.indexes).forEach(db => db.close());\n }\n}\n\n\nexport function createFoundationDBStorageInstance(\n storage: RxStorageFoundationDB,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageFoundationDBSettings\n): Promise> {\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n const {\n open,\n directory,\n encoders\n } = require('foundationdb');\n\n const connection = open(settings.clusterFile);\n const dbsPromise = (async () => {\n const dir = await directory.createOrOpen(connection, 'rxdb');\n\n const root = connection\n .at(dir)\n .at(params.databaseName + '.')\n .at(params.collectionName + '.')\n .at(params.schema.version + '.');\n const main: FoundationDBDatabase = root\n .at('main.')\n .withKeyEncoding(encoders.string) // automatically encode & decode keys using tuples\n .withValueEncoding(encoders.json) as any; // and values using JSON\n\n\n const events: FoundationDBDatabase>, RxStorageDefaultCheckpoint>> = root\n .at('events.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n const attachments: FoundationDBDatabase = root\n .at('attachments.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.json) as any;\n\n\n const indexDBs: { [indexName: string]: FoundationDBIndexMeta; } = {};\n const useIndexes = params.schema.indexes ? params.schema.indexes.slice(0) : [];\n useIndexes.push([primaryPath]);\n const useIndexesFinal = useIndexes.map(index => {\n const indexAr = toArray(index);\n indexAr.unshift('_deleted');\n return indexAr;\n });\n // used for `getChangedDocumentsSince()`\n useIndexesFinal.push([\n '_meta.lwt',\n primaryPath\n ]);\n useIndexesFinal.push(CLEANUP_INDEX);\n useIndexesFinal.forEach(indexAr => {\n const indexName = getFoundationDBIndexName(indexAr);\n const indexDB = root.at(indexName + '.')\n .withKeyEncoding(encoders.string)\n .withValueEncoding(encoders.string);\n indexDBs[indexName] = {\n indexName,\n db: indexDB,\n getIndexableString: getIndexableStringMonad(params.schema, indexAr),\n index: indexAr\n };\n });\n\n return {\n root,\n main,\n events,\n attachments,\n indexes: indexDBs\n };\n })();\n\n\n const internals: FoundationDBStorageInternals = {\n connection,\n dbsPromise: dbsPromise\n };\n\n const instance = new RxStorageInstanceFoundationDB(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AAoCA;AAIA;AAKA;AAKA;AAOA;AACA;AACA;AA9BA;AACA;AACA;AACA;AACA;AACA;AACA;AAAA,IA0BaA,6BAA6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XA,WAAW;YACXiB,OAAO,EAAEuG;UACb,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACJ,IAAG;EAGJ,IAAMtJ,SAAkD,GAAG;IACvD6I,UAAU,EAAVA,UAAU;IACVjI,UAAU,EAAEA;EAChB,CAAC;EAED,IAAMoJ,QAAQ,GAAG,IAAIrK,6BAA6B,CAC9CC,OAAO,EACP6I,MAAM,CAAC5I,YAAY,EACnB4I,MAAM,CAAC3I,cAAc,EACrB2I,MAAM,CAAC1I,MAAM,EACbC,SAAS,EACTyI,MAAM,CAACxI,OAAO,EACdC,QAAQ,CACX;EACD,OAAO+B,OAAO,CAACgI,OAAO,CAACD,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/index.js b/dist/lib/plugins/storage-lokijs/index.js similarity index 100% rename from dist/lib/plugins/lokijs/index.js rename to dist/lib/plugins/storage-lokijs/index.js diff --git a/dist/lib/plugins/storage-lokijs/index.js.map b/dist/lib/plugins/storage-lokijs/index.js.map new file mode 100644 index 00000000000..1af03c9e910 --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/storage-lokijs/index.ts"],"sourcesContent":["export * from './rx-storage-lokijs';\nexport * from './lokijs-helper';\nexport * from './rx-storage-instance-loki';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/loki-save-queue.js b/dist/lib/plugins/storage-lokijs/loki-save-queue.js similarity index 54% rename from dist/lib/plugins/lokijs/loki-save-queue.js rename to dist/lib/plugins/storage-lokijs/loki-save-queue.js index 2024b5efdf7..c0bea3a9781 100644 --- a/dist/lib/plugins/lokijs/loki-save-queue.js +++ b/dist/lib/plugins/storage-lokijs/loki-save-queue.js @@ -1,10 +1,13 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.LokiSaveQueue = void 0; -var _util = require("../../util"); +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utils = require("../utils"); /** * The autosave feature of lokijs has strange behaviors * and often runs a save in critical moments when other @@ -22,7 +25,7 @@ var LokiSaveQueue = /*#__PURE__*/function () { function LokiSaveQueue(lokiDatabase, databaseSettings) { this.writesSinceLastRun = 0; - this.saveQueue = _util.PROMISE_RESOLVE_VOID; + this.saveQueue = _utils.PROMISE_RESOLVE_VOID; this.saveQueueC = 0; this.lokiDatabase = lokiDatabase; this.databaseSettings = databaseSettings; @@ -42,34 +45,34 @@ var LokiSaveQueue = /*#__PURE__*/function () { return this.saveQueue; } this.saveQueueC = this.saveQueueC + 1; - this.saveQueue = this.saveQueue.then(function () { - try { - /** - * Always wait until the JavaScript process is idle. - * This ensures that CPU blocking writes are finished - * before we proceed. - */ - return Promise.resolve((0, _util.requestIdlePromise)()).then(function () { - // no write happened since the last save call - if (_this.writesSinceLastRun === 0) { - return; - } - - /** - * Because LokiJS is a in-memory database, - * we can just wait until the JavaScript process is idle - * via requestIdlePromise(). Then we know that nothing important - * is running at the moment. - */ - return Promise.resolve((0, _util.requestIdlePromise)().then(function () { - return (0, _util.requestIdlePromise)(); - })).then(function () { - if (_this.writesSinceLastRun === 0) { - return; + this.saveQueue = this.saveQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var writeAmount; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _utils.requestIdlePromise)(); + case 2: + if (!(_this.writesSinceLastRun === 0)) { + _context.next = 4; + break; + } + return _context.abrupt("return"); + case 4: + _context.next = 6; + return (0, _utils.requestIdlePromise)().then(function () { + return (0, _utils.requestIdlePromise)(); + }); + case 6: + if (!(_this.writesSinceLastRun === 0)) { + _context.next = 8; + break; } - var writeAmount = _this.writesSinceLastRun; + return _context.abrupt("return"); + case 8: + writeAmount = _this.writesSinceLastRun; _this.writesSinceLastRun = 0; - return new Promise(function (res, rej) { + return _context.abrupt("return", new Promise(function (res, rej) { _this.lokiDatabase.saveDatabase(function (err) { if (err) { _this.writesSinceLastRun = _this.writesSinceLastRun + writeAmount; @@ -81,13 +84,13 @@ var LokiSaveQueue = /*#__PURE__*/function () { res(); } }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })["catch"](function () {}).then(function () { + })); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })))["catch"](function () {}).then(function () { _this.saveQueueC = _this.saveQueueC - 1; }); return this.saveQueue; diff --git a/dist/lib/plugins/storage-lokijs/loki-save-queue.js.map b/dist/lib/plugins/storage-lokijs/loki-save-queue.js.map new file mode 100644 index 00000000000..986d49b9dcb --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/loki-save-queue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"loki-save-queue.js","names":["LokiSaveQueue","lokiDatabase","databaseSettings","writesSinceLastRun","saveQueue","PROMISE_RESOLVE_VOID","saveQueueC","addWrite","run","adapter","then","requestIdlePromise","writeAmount","Promise","res","rej","saveDatabase","err","autosaveCallback"],"sources":["../../../../src/plugins/storage-lokijs/loki-save-queue.ts"],"sourcesContent":["import type { LokiDatabaseSettings } from '../../types';\nimport {\n PROMISE_RESOLVE_VOID,\n requestIdlePromise\n} from '../utils';\n\n/**\n * The autosave feature of lokijs has strange behaviors\n * and often runs a save in critical moments when other\n * more important tasks are running.\n * So instead we use a custom save queue that ensures we\n * only run loki.saveDatabase() when nothing else is running.\n */\nexport class LokiSaveQueue {\n public writesSinceLastRun: number = 0;\n\n /**\n * Ensures that we do not run multiple saves\n * in parallel\n */\n public saveQueue: Promise = PROMISE_RESOLVE_VOID;\n // track amount of non-finished save calls in the queue.\n public saveQueueC = 0;\n\n constructor(\n public readonly lokiDatabase: Loki,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n\n }\n\n public addWrite() {\n this.writesSinceLastRun = this.writesSinceLastRun + 1;\n this.run();\n }\n\n public run() {\n if (\n // no persistence adapter given, so we do not need to save\n !this.databaseSettings.adapter ||\n // do not add more then two pending calls to the queue.\n this.saveQueueC > 2\n\n ) {\n return this.saveQueue;\n }\n\n this.saveQueueC = this.saveQueueC + 1;\n this.saveQueue = this.saveQueue\n .then(async () => {\n /**\n * Always wait until the JavaScript process is idle.\n * This ensures that CPU blocking writes are finished\n * before we proceed.\n */\n await requestIdlePromise();\n\n // no write happened since the last save call\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n /**\n * Because LokiJS is a in-memory database,\n * we can just wait until the JavaScript process is idle\n * via requestIdlePromise(). Then we know that nothing important\n * is running at the moment.\n */\n await requestIdlePromise().then(() => requestIdlePromise());\n\n if (this.writesSinceLastRun === 0) {\n return;\n }\n\n const writeAmount = this.writesSinceLastRun;\n this.writesSinceLastRun = 0;\n return new Promise((res, rej) => {\n this.lokiDatabase.saveDatabase(err => {\n if (err) {\n this.writesSinceLastRun = this.writesSinceLastRun + writeAmount;\n rej(err);\n } else {\n if (this.databaseSettings.autosaveCallback) {\n this.databaseSettings.autosaveCallback();\n }\n res();\n }\n });\n });\n })\n .catch(() => { })\n .then(() => {\n this.saveQueueC = this.saveQueueC - 1;\n });\n return this.saveQueue;\n }\n}\n"],"mappings":";;;;;;;;;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOaA,aAAa;EAGtB;AACJ;AACA;AACA;;EAEI;;EAGA,uBACoBC,YAAkB,EAClBC,gBAAsC,EACxD;IAAA,KAbKC,kBAAkB,GAAW,CAAC;IAAA,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/DG,GAAG,CAACE,GAAG,CAAC;gBACZ,CAAC,MAAM;kBACH,IAAI,KAAI,CAACf,gBAAgB,CAACgB,gBAAgB,EAAE;oBACxC,KAAI,CAAChB,gBAAgB,CAACgB,gBAAgB,EAAE;kBAC5C;kBACAJ,GAAG,EAAE;gBACT;cACJ,CAAC,CAAC;YACN,CAAC,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA,CACL,GAAC,SACI,CAAC,YAAM,CAAE,CAAC,CAAC,CAChBJ,IAAI,CAAC,YAAM;MACR,KAAI,CAACJ,UAAU,GAAG,KAAI,CAACA,UAAU,GAAG,CAAC;IACzC,CAAC,CAAC;IACN,OAAO,IAAI,CAACF,SAAS;EACzB,CAAC;EAAA;AAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-lokijs/lokijs-helper.js b/dist/lib/plugins/storage-lokijs/lokijs-helper.js new file mode 100644 index 00000000000..d41735c8bdb --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/lokijs-helper.js @@ -0,0 +1,520 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RX_STORAGE_NAME_LOKIJS = exports.OPEN_LOKIJS_STORAGE_INSTANCES = exports.LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = exports.LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = exports.LOKIJS_COLLECTION_DEFAULT_OPTIONS = exports.CHANGES_COLLECTION_SUFFIX = void 0; +exports.closeLokiCollections = closeLokiCollections; +exports.getLokiDatabase = getLokiDatabase; +exports.getLokiLeaderElector = getLokiLeaderElector; +exports.getLokiSortComparator = getLokiSortComparator; +exports.handleRemoteRequest = handleRemoteRequest; +exports.mustUseLocalState = mustUseLocalState; +exports.requestRemoteInstance = requestRemoteInstance; +exports.stripLokiKey = stripLokiKey; +exports.waitUntilHasLeader = waitUntilHasLeader; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _rxStorageInstanceLoki = require("./rx-storage-instance-loki"); +var _lokijs = _interopRequireDefault(require("lokijs")); +var _unload = require("unload"); +var _utils = require("../utils"); +var _lokiSaveQueue = require("./loki-save-queue"); +var _rxError = require("../../rx-error"); +var _objectPath = _interopRequireDefault(require("object-path")); +var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); +var _leaderElection = require("../leader-election"); +var CHANGES_COLLECTION_SUFFIX = '-rxdb-changes'; +exports.CHANGES_COLLECTION_SUFFIX = CHANGES_COLLECTION_SUFFIX; +var LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request'; +exports.LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE; +var LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object'; +exports.LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE; +var RX_STORAGE_NAME_LOKIJS = 'lokijs'; + +/** + * Loki attaches a $loki property to all data + * which must be removed before returning the data back to RxDB. + */ +exports.RX_STORAGE_NAME_LOKIJS = RX_STORAGE_NAME_LOKIJS; +function stripLokiKey(docData) { + if (!docData.$loki) { + return docData; + } + var cloned = (0, _utils.flatClone)(docData); + + /** + * In RxDB version 12.0.0, + * we introduced the _meta field that already contains the last write time. + * To be backwards compatible, we have to move the $lastWriteAt to the _meta field. + * TODO remove this in the next major version. + */ + if (cloned.$lastWriteAt) { + cloned._meta = { + lwt: cloned.$lastWriteAt + }; + delete cloned.$lastWriteAt; + } + delete cloned.$loki; + return cloned; +} + +/** + * Used to check in tests if all instances have been cleaned up. + */ +var OPEN_LOKIJS_STORAGE_INSTANCES = new Set(); +exports.OPEN_LOKIJS_STORAGE_INSTANCES = OPEN_LOKIJS_STORAGE_INSTANCES; +var LOKIJS_COLLECTION_DEFAULT_OPTIONS = { + disableChangesApi: true, + disableMeta: true, + disableDeltaChangesApi: true, + disableFreeze: true, + // TODO use 'immutable' like WatermelonDB does it + cloneMethod: 'shallow-assign', + clone: false, + transactional: false, + autoupdate: false +}; +exports.LOKIJS_COLLECTION_DEFAULT_OPTIONS = LOKIJS_COLLECTION_DEFAULT_OPTIONS; +var LOKI_DATABASE_STATE_BY_NAME = new Map(); +function getLokiDatabase(databaseName, databaseSettings) { + var databaseState = LOKI_DATABASE_STATE_BY_NAME.get(databaseName); + if (!databaseState) { + /** + * We assume that as soon as an adapter is passed, + * the database has to be persistend. + */ + var hasPersistence = !!databaseSettings.adapter; + databaseState = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var persistenceMethod, useSettings, database, lokiSaveQueue, loadDatabasePromise, unloads, state; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + persistenceMethod = hasPersistence ? 'adapter' : 'memory'; + if (databaseSettings.persistenceMethod) { + persistenceMethod = databaseSettings.persistenceMethod; + } + useSettings = Object.assign( + // defaults + { + autoload: hasPersistence, + persistenceMethod: persistenceMethod, + verbose: true + }, databaseSettings, + // overwrites + { + /** + * RxDB uses its custom load and save handling + * so we disable the LokiJS save/load handlers. + */ + autoload: false, + autosave: false, + throttledSaves: false + }); + database = new _lokijs["default"](databaseName + '.db', (0, _utils.flatClone)(useSettings)); + lokiSaveQueue = new _lokiSaveQueue.LokiSaveQueue(database, useSettings); + /** + * Wait until all data is loaded from persistence adapter. + * Wrap the loading into the saveQueue to ensure that when many + * collections are created at the same time, the load-calls do not interfere + * with each other and cause error logs. + */ + if (!hasPersistence) { + _context.next = 10; + break; + } + loadDatabasePromise = new Promise(function (res, rej) { + try { + database.loadDatabase({ + recursiveWait: false + }, function (err) { + if (useSettings.autoloadCallback) { + useSettings.autoloadCallback(err); + } + if (err) { + rej(err); + } else { + res(); + } + }); + } catch (err) { + rej(err); + } + }); + lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(function () { + return loadDatabasePromise; + }); + _context.next = 10; + return loadDatabasePromise; + case 10: + /** + * Autosave database on process end + */ + unloads = []; + if (hasPersistence) { + unloads.push((0, _unload.add)(function () { + return lokiSaveQueue.run(); + })); + } + state = { + database: database, + databaseSettings: useSettings, + saveQueue: lokiSaveQueue, + collections: {}, + unloads: unloads + }; + return _context.abrupt("return", state); + case 14: + case "end": + return _context.stop(); + } + }, _callee); + }))(); + LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState); + } + return databaseState; +} +function closeLokiCollections(_x, _x2) { + return _closeLokiCollections.apply(this, arguments); +} +/** + * This function is at lokijs-helper + * because we need it in multiple places. + */ +function _closeLokiCollections() { + _closeLokiCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(databaseName, collections) { + var databaseState; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return LOKI_DATABASE_STATE_BY_NAME.get(databaseName); + case 2: + databaseState = _context2.sent; + if (databaseState) { + _context2.next = 5; + break; + } + return _context2.abrupt("return"); + case 5: + _context2.next = 7; + return databaseState.saveQueue.run(); + case 7: + collections.forEach(function (collection) { + var collectionName = collection.name; + delete databaseState.collections[collectionName]; + }); + if (!(Object.keys(databaseState.collections).length === 0)) { + _context2.next = 13; + break; + } + // all collections closed -> also close database + LOKI_DATABASE_STATE_BY_NAME["delete"](databaseName); + databaseState.unloads.forEach(function (u) { + return u.remove(); + }); + _context2.next = 13; + return new Promise(function (res, rej) { + databaseState.database.close(function (err) { + if (err) { + rej(err); + } else { + res(); + } + }); + }); + case 13: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _closeLokiCollections.apply(this, arguments); +} +function getLokiSortComparator(_schema, query) { + if (!query.sort) { + throw (0, _rxError.newRxError)('SNH', { + query: query + }); + } + var sortOptions = query.sort; + var fun = function fun(a, b) { + var compareResult = 0; // 1 | -1 + sortOptions.find(function (sortPart) { + var fieldName = Object.keys(sortPart)[0]; + var direction = Object.values(sortPart)[0]; + var directionMultiplier = direction === 'asc' ? 1 : -1; + var valueA = _objectPath["default"].get(a, fieldName); + var valueB = _objectPath["default"].get(b, fieldName); + if (valueA === valueB) { + return false; + } else { + if (valueA > valueB) { + compareResult = 1 * directionMultiplier; + return true; + } else { + compareResult = -1 * directionMultiplier; + return true; + } + } + }); + + /** + * Two different objects should never have the same sort position. + * We ensure this by having the unique primaryKey in the sort params + * which is added by RxDB if not existing yet. + */ + if (!compareResult) { + throw (0, _rxError.newRxError)('SNH', { + args: { + query: query, + a: a, + b: b + } + }); + } + return compareResult; + }; + return fun; +} +function getLokiLeaderElector(databaseInstanceToken, broadcastChannelRefObject, databaseName) { + var broadcastChannel = (0, _rxStorageMultiinstance.getBroadcastChannelReference)(databaseInstanceToken, databaseName, broadcastChannelRefObject); + var elector = (0, _leaderElection.getLeaderElectorByBroadcastChannel)(broadcastChannel); + return elector; +} + +/** + * For multi-instance usage, we send requests to the RxStorage + * to the current leading instance over the BroadcastChannel. + */ +function requestRemoteInstance(_x3, _x4, _x5) { + return _requestRemoteInstance.apply(this, arguments); +} +/** + * Handles a request that came from a remote instance via requestRemoteInstance() + * Runs the requested operation over the local db instance and sends back the result. + */ +function _requestRemoteInstance() { + _requestRemoteInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(instance, operation, params) { + var isRxStorageInstanceLoki, messageType, leaderElector, broadcastChannel, whenDeathListener, leaderDeadPromise, requestId, responseListener, responsePromise; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + isRxStorageInstanceLoki = typeof instance.query === 'function'; + messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE; + leaderElector = (0, _utils.ensureNotFalsy)(instance.internals.leaderElector); + _context3.next = 5; + return waitUntilHasLeader(leaderElector); + case 5: + broadcastChannel = leaderElector.broadcastChannel; + leaderDeadPromise = new Promise(function (res) { + whenDeathListener = function whenDeathListener(msg) { + if (msg.context === 'leader' && msg.action === 'death') { + res({ + retry: true + }); + } + }; + broadcastChannel.addEventListener('internal', whenDeathListener); + }); + requestId = (0, _utils.randomCouchString)(12); + responsePromise = new Promise(function (res, _rej) { + responseListener = function responseListener(msg) { + if (msg.type === messageType && msg.response === true && msg.requestId === requestId) { + if (msg.isError) { + res({ + retry: false, + error: msg.result + }); + } else { + res({ + retry: false, + result: msg.result + }); + } + } + }; + broadcastChannel.addEventListener('message', responseListener); + }); // send out the request to the other instance + broadcastChannel.postMessage({ + response: false, + type: messageType, + operation: operation, + params: params, + requestId: requestId, + databaseName: instance.databaseName, + collectionName: instance.collectionName + }); + return _context3.abrupt("return", Promise.race([leaderDeadPromise, responsePromise]).then(function (firstResolved) { + // clean up listeners + broadcastChannel.removeEventListener('message', responseListener); + broadcastChannel.removeEventListener('internal', whenDeathListener); + if (firstResolved.retry) { + var _ref2; + /** + * The leader died while a remote request was running + * we re-run the whole operation. + * We cannot just re-run requestRemoteInstance() + * because the current instance might be the new leader now + * and then we have to use the local state instead of requesting the remote. + */ + return (_ref2 = instance)[operation].apply(_ref2, params); + } else { + if (firstResolved.error) { + throw firstResolved.error; + } else { + return firstResolved.result; + } + } + })); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _requestRemoteInstance.apply(this, arguments); +} +function handleRemoteRequest(_x6, _x7) { + return _handleRemoteRequest.apply(this, arguments); +} +function _handleRemoteRequest() { + _handleRemoteRequest = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(instance, msg) { + var operation, params, result, isError, _ref3, response; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE && msg.requestId && msg.databaseName === instance.databaseName && msg.collectionName === instance.collectionName && !msg.response)) { + _context4.next = 17; + break; + } + operation = msg.operation; + params = msg.params; + isError = false; + _context4.prev = 4; + _context4.next = 7; + return (_ref3 = instance)[operation].apply(_ref3, params); + case 7: + result = _context4.sent; + _context4.next = 15; + break; + case 10: + _context4.prev = 10; + _context4.t0 = _context4["catch"](4); + console.dir(_context4.t0); + isError = true; + result = _context4.t0; + case 15: + response = { + response: true, + requestId: msg.requestId, + databaseName: instance.databaseName, + collectionName: instance.collectionName, + result: result, + isError: isError, + type: msg.type + }; + (0, _utils.ensureNotFalsy)(instance.internals.leaderElector).broadcastChannel.postMessage(response); + case 17: + case "end": + return _context4.stop(); + } + }, _callee4, null, [[4, 10]]); + })); + return _handleRemoteRequest.apply(this, arguments); +} +function waitUntilHasLeader(_x8) { + return _waitUntilHasLeader.apply(this, arguments); +} +/** + * If the local state must be used, that one is returned. + * Returns false if a remote instance must be used. + */ +function _waitUntilHasLeader() { + _waitUntilHasLeader = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(leaderElector) { + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (leaderElector.hasLeader) { + _context5.next = 7; + break; + } + _context5.next = 3; + return leaderElector.applyOnce(); + case 3: + _context5.next = 5; + return (0, _utils.promiseWait)(0); + case 5: + _context5.next = 0; + break; + case 7: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _waitUntilHasLeader.apply(this, arguments); +} +function mustUseLocalState(_x9) { + return _mustUseLocalState.apply(this, arguments); +} +function _mustUseLocalState() { + _mustUseLocalState = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(instance) { + var leaderElector; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!instance.closed) { + _context6.next = 2; + break; + } + throw (0, _rxError.newRxError)('SNH', { + args: { + instanceClosed: instance.closed, + databaseName: instance.databaseName, + collectionName: instance.collectionName + } + }); + case 2: + if (!instance.internals.localState) { + _context6.next = 4; + break; + } + return _context6.abrupt("return", instance.internals.localState); + case 4: + leaderElector = (0, _utils.ensureNotFalsy)(instance.internals.leaderElector); + _context6.next = 7; + return waitUntilHasLeader(leaderElector); + case 7: + if (!instance.internals.localState) { + _context6.next = 9; + break; + } + return _context6.abrupt("return", instance.internals.localState); + case 9: + if (!(leaderElector.isLeader && !instance.internals.localState)) { + _context6.next = 14; + break; + } + // own is leader, use local instance + instance.internals.localState = (0, _rxStorageInstanceLoki.createLokiLocalState)({ + databaseInstanceToken: instance.databaseInstanceToken, + databaseName: instance.databaseName, + collectionName: instance.collectionName, + options: instance.options, + schema: instance.schema, + multiInstance: instance.internals.leaderElector ? true : false + }, instance.databaseSettings); + return _context6.abrupt("return", (0, _utils.ensureNotFalsy)(instance.internals.localState)); + case 14: + return _context6.abrupt("return", false); + case 15: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _mustUseLocalState.apply(this, arguments); +} +//# sourceMappingURL=lokijs-helper.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-lokijs/lokijs-helper.js.map b/dist/lib/plugins/storage-lokijs/lokijs-helper.js.map new file mode 100644 index 00000000000..10a710c64d7 --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/lokijs-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-helper.js","names":["CHANGES_COLLECTION_SUFFIX","LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE","LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE","RX_STORAGE_NAME_LOKIJS","stripLokiKey","docData","$loki","cloned","flatClone","$lastWriteAt","_meta","lwt","OPEN_LOKIJS_STORAGE_INSTANCES","Set","LOKIJS_COLLECTION_DEFAULT_OPTIONS","disableChangesApi","disableMeta","disableDeltaChangesApi","disableFreeze","cloneMethod","clone","transactional","autoupdate","LOKI_DATABASE_STATE_BY_NAME","Map","getLokiDatabase","databaseName","databaseSettings","databaseState","get","hasPersistence","adapter","persistenceMethod","useSettings","Object","assign","autoload","verbose","autosave","throttledSaves","database","lokijs","lokiSaveQueue","LokiSaveQueue","loadDatabasePromise","Promise","res","rej","loadDatabase","recursiveWait","err","autoloadCallback","saveQueue","then","unloads","push","unloadAdd","run","state","collections","set","closeLokiCollections","forEach","collection","collectionName","name","keys","length","u","remove","close","getLokiSortComparator","_schema","query","sort","newRxError","sortOptions","fun","a","b","compareResult","find","sortPart","fieldName","direction","values","directionMultiplier","valueA","objectPath","valueB","args","getLokiLeaderElector","databaseInstanceToken","broadcastChannelRefObject","broadcastChannel","getBroadcastChannelReference","elector","getLeaderElectorByBroadcastChannel","requestRemoteInstance","instance","operation","params","isRxStorageInstanceLoki","messageType","leaderElector","ensureNotFalsy","internals","waitUntilHasLeader","leaderDeadPromise","whenDeathListener","msg","context","action","retry","addEventListener","requestId","randomCouchString","responsePromise","_rej","responseListener","type","response","isError","error","result","postMessage","race","firstResolved","removeEventListener","handleRemoteRequest","console","dir","hasLeader","applyOnce","promiseWait","mustUseLocalState","closed","instanceClosed","localState","isLeader","createLokiLocalState","options","schema","multiInstance"],"sources":["../../../../src/plugins/storage-lokijs/lokijs-helper.ts"],"sourcesContent":["import { createLokiLocalState, RxStorageInstanceLoki } from './rx-storage-instance-loki';\nimport lokijs, { Collection } from 'lokijs';\nimport type {\n LokiDatabaseSettings,\n LokiDatabaseState,\n LokiLocalDatabaseState,\n LokiRemoteResponseBroadcastMessage,\n MangoQuery,\n MangoQuerySortDirection,\n MangoQuerySortPart,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport {\n add as unloadAdd,\n AddReturn\n} from 'unload';\nimport { ensureNotFalsy, flatClone, promiseWait, randomCouchString } from '../utils';\nimport { LokiSaveQueue } from './loki-save-queue';\nimport type { DeterministicSortComparator } from 'event-reduce-js';\nimport { newRxError } from '../../rx-error';\nimport objectPath from 'object-path';\nimport {\n LeaderElector,\n OnMessageHandler\n} from 'broadcast-channel';\nimport { getBroadcastChannelReference } from '../../rx-storage-multiinstance';\nimport { getLeaderElectorByBroadcastChannel } from '../leader-election';\n\nexport const CHANGES_COLLECTION_SUFFIX = '-rxdb-changes';\nexport const LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request';\nexport const LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE = 'rxdb-lokijs-remote-request-key-object';\nexport const RX_STORAGE_NAME_LOKIJS = 'lokijs';\n\n/**\n * Loki attaches a $loki property to all data\n * which must be removed before returning the data back to RxDB.\n */\nexport function stripLokiKey(docData: RxDocumentData & { $loki?: number; }): T {\n if (!docData.$loki) {\n return docData;\n }\n const cloned = flatClone(docData);\n\n /**\n * In RxDB version 12.0.0,\n * we introduced the _meta field that already contains the last write time.\n * To be backwards compatible, we have to move the $lastWriteAt to the _meta field.\n * TODO remove this in the next major version.\n */\n if ((cloned as any).$lastWriteAt) {\n cloned._meta = {\n lwt: (cloned as any).$lastWriteAt\n };\n delete (cloned as any).$lastWriteAt;\n }\n\n delete cloned.$loki;\n return cloned;\n}\n\n/**\n * Used to check in tests if all instances have been cleaned up.\n */\nexport const OPEN_LOKIJS_STORAGE_INSTANCES: Set> = new Set();\n\n\nexport const LOKIJS_COLLECTION_DEFAULT_OPTIONS: Partial> = {\n disableChangesApi: true,\n disableMeta: true,\n disableDeltaChangesApi: true,\n disableFreeze: true,\n // TODO use 'immutable' like WatermelonDB does it\n cloneMethod: 'shallow-assign',\n clone: false,\n transactional: false,\n autoupdate: false\n};\n\nconst LOKI_DATABASE_STATE_BY_NAME: Map> = new Map();\nexport function getLokiDatabase(\n databaseName: string,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n let databaseState: Promise | undefined = LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n /**\n * We assume that as soon as an adapter is passed,\n * the database has to be persistend.\n */\n const hasPersistence: boolean = !!databaseSettings.adapter;\n databaseState = (async () => {\n let persistenceMethod = hasPersistence ? 'adapter' : 'memory';\n if (databaseSettings.persistenceMethod) {\n persistenceMethod = databaseSettings.persistenceMethod;\n }\n const useSettings = Object.assign(\n // defaults\n {\n autoload: hasPersistence,\n persistenceMethod,\n verbose: true\n },\n databaseSettings,\n // overwrites\n {\n /**\n * RxDB uses its custom load and save handling\n * so we disable the LokiJS save/load handlers.\n */\n autoload: false,\n autosave: false,\n throttledSaves: false\n }\n );\n const database = new lokijs(\n databaseName + '.db',\n flatClone(useSettings)\n );\n const lokiSaveQueue = new LokiSaveQueue(\n database,\n useSettings\n );\n\n /**\n * Wait until all data is loaded from persistence adapter.\n * Wrap the loading into the saveQueue to ensure that when many\n * collections are created at the same time, the load-calls do not interfere\n * with each other and cause error logs.\n */\n if (hasPersistence) {\n const loadDatabasePromise = new Promise((res, rej) => {\n try {\n database.loadDatabase({\n recursiveWait: false\n }, (err) => {\n if (useSettings.autoloadCallback) {\n useSettings.autoloadCallback(err);\n }\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n } catch (err) {\n rej(err);\n }\n });\n lokiSaveQueue.saveQueue = lokiSaveQueue.saveQueue.then(() => loadDatabasePromise);\n await loadDatabasePromise;\n }\n\n /**\n * Autosave database on process end\n */\n const unloads: AddReturn[] = [];\n if (hasPersistence) {\n unloads.push(\n unloadAdd(() => lokiSaveQueue.run())\n );\n }\n\n const state: LokiDatabaseState = {\n database,\n databaseSettings: useSettings,\n saveQueue: lokiSaveQueue,\n collections: {},\n unloads\n };\n\n return state;\n })();\n LOKI_DATABASE_STATE_BY_NAME.set(databaseName, databaseState);\n }\n return databaseState;\n}\n\nexport async function closeLokiCollections(\n databaseName: string,\n collections: Collection[]\n) {\n const databaseState = await LOKI_DATABASE_STATE_BY_NAME.get(databaseName);\n if (!databaseState) {\n // already closed\n return;\n }\n await databaseState.saveQueue.run();\n collections.forEach(collection => {\n const collectionName = collection.name;\n delete databaseState.collections[collectionName];\n });\n if (Object.keys(databaseState.collections).length === 0) {\n // all collections closed -> also close database\n LOKI_DATABASE_STATE_BY_NAME.delete(databaseName);\n databaseState.unloads.forEach(u => u.remove());\n await new Promise((res, rej) => {\n databaseState.database.close(err => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n}\n\n/**\n * This function is at lokijs-helper\n * because we need it in multiple places.\n */\nexport function getLokiSortComparator(\n _schema: RxJsonSchema>,\n query: MangoQuery\n): DeterministicSortComparator {\n if (!query.sort) {\n throw newRxError('SNH', { query });\n }\n const sortOptions: MangoQuerySortPart[] = query.sort;\n\n const fun: DeterministicSortComparator = (a: RxDocType, b: RxDocType) => {\n let compareResult: number = 0; // 1 | -1\n sortOptions.find(sortPart => {\n const fieldName: string = Object.keys(sortPart)[0];\n const direction: MangoQuerySortDirection = Object.values(sortPart)[0];\n const directionMultiplier = direction === 'asc' ? 1 : -1;\n const valueA: any = objectPath.get(a as any, fieldName);\n const valueB: any = objectPath.get(b as any, fieldName);\n if (valueA === valueB) {\n return false;\n } else {\n if (valueA > valueB) {\n compareResult = 1 * directionMultiplier;\n return true;\n } else {\n compareResult = -1 * directionMultiplier;\n return true;\n }\n }\n });\n\n /**\n * Two different objects should never have the same sort position.\n * We ensure this by having the unique primaryKey in the sort params\n * which is added by RxDB if not existing yet.\n */\n if (!compareResult) {\n throw newRxError('SNH', { args: { query, a, b } });\n }\n\n return compareResult as any;\n };\n return fun;\n}\n\nexport function getLokiLeaderElector(\n databaseInstanceToken: string,\n broadcastChannelRefObject: any,\n databaseName: string\n): LeaderElector {\n const broadcastChannel = getBroadcastChannelReference(\n databaseInstanceToken,\n databaseName,\n broadcastChannelRefObject\n );\n const elector = getLeaderElectorByBroadcastChannel(broadcastChannel);\n return elector;\n}\n\n/**\n * For multi-instance usage, we send requests to the RxStorage\n * to the current leading instance over the BroadcastChannel.\n */\nexport async function requestRemoteInstance(\n instance: RxStorageInstanceLoki,\n operation: string,\n params: any[]\n): Promise {\n const isRxStorageInstanceLoki = typeof (instance as any).query === 'function';\n const messageType = isRxStorageInstanceLoki ? LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE : LOKI_KEY_OBJECT_BROADCAST_CHANNEL_MESSAGE_TYPE;\n\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n const broadcastChannel = leaderElector.broadcastChannel;\n\n type WinningPromise = {\n retry: boolean;\n result?: any;\n error?: any;\n };\n\n let whenDeathListener: OnMessageHandler;\n const leaderDeadPromise = new Promise(res => {\n whenDeathListener = (msg: any) => {\n if (msg.context === 'leader' && msg.action === 'death') {\n res({\n retry: true\n });\n }\n };\n broadcastChannel.addEventListener('internal', whenDeathListener);\n });\n const requestId = randomCouchString(12);\n let responseListener: OnMessageHandler;\n const responsePromise = new Promise((res, _rej) => {\n responseListener = (msg: any) => {\n if (\n msg.type === messageType &&\n msg.response === true &&\n msg.requestId === requestId\n ) {\n if (msg.isError) {\n res({\n retry: false,\n error: msg.result\n });\n } else {\n res({\n retry: false,\n result: msg.result\n });\n }\n }\n };\n broadcastChannel.addEventListener('message', responseListener);\n });\n\n // send out the request to the other instance\n broadcastChannel.postMessage({\n response: false,\n type: messageType,\n operation,\n params,\n requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n });\n\n\n return Promise.race([\n leaderDeadPromise,\n responsePromise\n ]).then(firstResolved => {\n\n // clean up listeners\n broadcastChannel.removeEventListener('message', responseListener);\n broadcastChannel.removeEventListener('internal', whenDeathListener);\n\n if (firstResolved.retry) {\n /**\n * The leader died while a remote request was running\n * we re-run the whole operation.\n * We cannot just re-run requestRemoteInstance()\n * because the current instance might be the new leader now\n * and then we have to use the local state instead of requesting the remote.\n */\n return (instance as any)[operation](...params);\n } else {\n if (firstResolved.error) {\n throw firstResolved.error;\n } else {\n return firstResolved.result;\n }\n }\n });\n}\n\n/**\n * Handles a request that came from a remote instance via requestRemoteInstance()\n * Runs the requested operation over the local db instance and sends back the result.\n */\nexport async function handleRemoteRequest(\n instance: RxStorageInstanceLoki,\n msg: any\n) {\n if (\n msg.type === LOKI_BROADCAST_CHANNEL_MESSAGE_TYPE &&\n msg.requestId &&\n msg.databaseName === instance.databaseName &&\n msg.collectionName === instance.collectionName &&\n !msg.response\n ) {\n const operation = (msg as any).operation;\n const params = (msg as any).params;\n let result: any;\n let isError = false;\n try {\n result = await (instance as any)[operation](...params);\n } catch (err) {\n console.dir(err);\n isError = true;\n result = err;\n }\n const response: LokiRemoteResponseBroadcastMessage = {\n response: true,\n requestId: msg.requestId,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n result,\n isError,\n type: msg.type\n };\n ensureNotFalsy(instance.internals.leaderElector).broadcastChannel.postMessage(response);\n }\n}\n\n\nexport async function waitUntilHasLeader(leaderElector: LeaderElector) {\n while (\n !leaderElector.hasLeader\n ) {\n await leaderElector.applyOnce();\n await promiseWait(0);\n }\n}\n\n/**\n * If the local state must be used, that one is returned.\n * Returns false if a remote instance must be used.\n */\nexport async function mustUseLocalState(\n instance: RxStorageInstanceLoki\n): Promise {\n if (instance.closed) {\n /**\n * If this happens, it means that RxDB made a call to an already closed storage instance.\n * This must never happen because when RxDB closes a collection or database,\n * all tasks must be cleared so that no more calls are made the the storage.\n */\n throw newRxError('SNH', {\n args: {\n instanceClosed: instance.closed,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName\n }\n });\n }\n\n\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n const leaderElector = ensureNotFalsy(instance.internals.leaderElector);\n await waitUntilHasLeader(leaderElector);\n\n /**\n * It might already have a localState after the applying\n * because another subtask also called mustUSeLocalState()\n */\n if (instance.internals.localState) {\n return instance.internals.localState;\n }\n\n if (\n leaderElector.isLeader &&\n !instance.internals.localState\n ) {\n // own is leader, use local instance\n instance.internals.localState = createLokiLocalState({\n databaseInstanceToken: instance.databaseInstanceToken,\n databaseName: instance.databaseName,\n collectionName: instance.collectionName,\n options: instance.options,\n schema: (instance as RxStorageInstanceLoki).schema,\n multiInstance: instance.internals.leaderElector ? true : false\n }, instance.databaseSettings);\n return ensureNotFalsy(instance.internals.localState);\n } else {\n // other is leader, send message to remote leading instance\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AACA;AAYA;AAIA;AACA;AAEA;AACA;AAKA;AACA;AAEO,IAAMA,yBAAyB,GAAG,eAAe;AAAC;AAClD,IAAMC,mCAAmC,GAAG,4BAA4B;AAAC;AACzE,IAAMC,8CAA8C,GAAG,uCAAuC;AAAC;AAC/F,IAAMC,sBAAsB,GAAG,QAAQ;;AAE9C;AACA;AACA;AACA;AAHA;AAIO,SAASC,YAAY,CAAIC,OAAgD,EAAK;EACjF,IAAI,CAACA,OAAO,CAACC,KAAK,EAAE;IAChB,OAAOD,OAAO;EAClB;EACA,IAAME,MAAM,GAAG,IAAAC,gBAAS,EAACH,OAAO,CAAC;;EAEjC;AACJ;AACA;AACA;AACA;AACA;EACI,IAAKE,MAAM,CAASE,YAAY,EAAE;IAC9BF,MAAM,CAACG,KAAK,GAAG;MACXC,GAAG,EAAGJ,MAAM,CAASE;IACzB,CAAC;IACD,OAAQF,MAAM,CAASE,YAAY;EACvC;EAEA,OAAOF,MAAM,CAACD,KAAK;EACnB,OAAOC,MAAM;AACjB;;AAEA;AACA;AACA;AACO,IAAMK,6BAA8D,GAAG,IAAIC,GAAG,EAAE;AAAC;AAGjF,IAAMC,iCAAkE,GAAG;EAC9EC,iBAAiB,EAAE,IAAI;EACvBC,WAAW,EAAE,IAAI;EACjBC,sBAAsB,EAAE,IAAI;EAC5BC,aAAa,EAAE,IAAI;EACnB;EACAC,WAAW,EAAE,gBAAgB;EAC7BC,KAAK,EAAE,KAAK;EACZC,aAAa,EAAE,KAAK;EACpBC,UAAU,EAAE;AAChB,CAAC;AAAC;AAEF,IAAMC,2BAAoE,GAAG,IAAIC,GAAG,EAAE;AAC/E,SAASC,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,QAAQ,CAACO,SAAS,CAACgC,UAAU,CAAC;QAAA;UAAA,kCAG7C,KAAK;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAEnB;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-lokijs/rx-storage-instance-loki.js b/dist/lib/plugins/storage-lokijs/rx-storage-instance-loki.js new file mode 100644 index 00000000000..7986325ed6d --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/rx-storage-instance-loki.js @@ -0,0 +1,567 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RxStorageInstanceLoki = void 0; +exports.createLokiLocalState = createLokiLocalState; +exports.createLokiStorageInstance = createLokiStorageInstance; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _rxjs = require("rxjs"); +var _utils = require("../utils"); +var _rxError = require("../../rx-error"); +var _lokijsHelper = require("./lokijs-helper"); +var _rxSchemaHelper = require("../../rx-schema-helper"); +var _rxStorageHelper = require("../../rx-storage-helper"); +var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); +var instanceId = (0, _utils.now)(); +var RxStorageInstanceLoki = /*#__PURE__*/function () { + function RxStorageInstanceLoki(databaseInstanceToken, storage, databaseName, collectionName, schema, internals, options, databaseSettings) { + var _this = this; + this.changes$ = new _rxjs.Subject(); + this.instanceId = instanceId++; + this.closed = false; + this.databaseInstanceToken = databaseInstanceToken; + this.storage = storage; + this.databaseName = databaseName; + this.collectionName = collectionName; + this.schema = schema; + this.internals = internals; + this.options = options; + this.databaseSettings = databaseSettings; + this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); + _lokijsHelper.OPEN_LOKIJS_STORAGE_INSTANCES.add(this); + if (this.internals.leaderElector) { + /** + * To run handleRemoteRequest(), + * the instance will call its own methods. + * But these methods could have already been swapped out by a RxStorageWrapper + * so we must store the original methods here and use them instead. + */ + var copiedSelf = { + bulkWrite: this.bulkWrite.bind(this), + changeStream: this.changeStream.bind(this), + cleanup: this.cleanup.bind(this), + close: this.close.bind(this), + query: this.query.bind(this), + count: this.count.bind(this), + findDocumentsById: this.findDocumentsById.bind(this), + collectionName: this.collectionName, + databaseName: this.databaseName, + conflictResultionTasks: this.conflictResultionTasks.bind(this), + getAttachmentData: this.getAttachmentData.bind(this), + getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this), + internals: this.internals, + options: this.options, + remove: this.remove.bind(this), + resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this), + schema: this.schema + }; + this.internals.leaderElector.awaitLeadership().then(function () { + // this instance is leader now, so it has to reply to queries from other instances + (0, _utils.ensureNotFalsy)(_this.internals.leaderElector).broadcastChannel.addEventListener('message', function (msg) { + return (0, _lokijsHelper.handleRemoteRequest)(copiedSelf, msg); + }); + }); + } + } + var _proto = RxStorageInstanceLoki.prototype; + _proto.bulkWrite = /*#__PURE__*/function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(documentWrites, context) { + var _this2 = this; + var localState, ret, docsInDb, docsInDbWithLokiKey, categorized, lastState; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(documentWrites.length === 0)) { + _context.next = 2; + break; + } + throw (0, _rxError.newRxError)('P2', { + args: { + documentWrites: documentWrites + } + }); + case 2: + _context.next = 4; + return (0, _lokijsHelper.mustUseLocalState)(this); + case 4: + localState = _context.sent; + if (localState) { + _context.next = 7; + break; + } + return _context.abrupt("return", (0, _lokijsHelper.requestRemoteInstance)(this, 'bulkWrite', [documentWrites])); + case 7: + ret = { + success: {}, + error: {} + }; + docsInDb = new Map(); + docsInDbWithLokiKey = new Map(); + documentWrites.forEach(function (writeRow) { + var id = writeRow.document[_this2.primaryPath]; + var documentInDb = localState.collection.by(_this2.primaryPath, id); + if (documentInDb) { + docsInDbWithLokiKey.set(id, documentInDb); + docsInDb.set(id, (0, _lokijsHelper.stripLokiKey)(documentInDb)); + } + }); + categorized = (0, _rxStorageHelper.categorizeBulkWriteRows)(this, this.primaryPath, docsInDb, documentWrites, context); + ret.error = categorized.errors; + categorized.bulkInsertDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this2.primaryPath]; + localState.collection.insert((0, _utils.flatClone)(writeRow.document)); + ret.success[docId] = writeRow.document; + }); + categorized.bulkUpdateDocs.forEach(function (writeRow) { + var docId = writeRow.document[_this2.primaryPath]; + var documentInDbWithLokiKey = (0, _utils.getFromMapOrThrow)(docsInDbWithLokiKey, docId); + var writeDoc = Object.assign({}, writeRow.document, { + $loki: documentInDbWithLokiKey.$loki + }); + localState.collection.update(writeDoc); + ret.success[docId] = writeRow.document; + }); + localState.databaseState.saveQueue.addWrite(); + if (categorized.eventBulk.events.length > 0) { + lastState = (0, _rxStorageHelper.getNewestOfDocumentStates)(this.primaryPath, Object.values(ret.success)); + categorized.eventBulk.checkpoint = { + id: lastState[this.primaryPath], + lwt: lastState._meta.lwt + }; + this.changes$.next(categorized.eventBulk); + } + return _context.abrupt("return", ret); + case 18: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function bulkWrite(_x, _x2) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(); + _proto.findDocumentsById = /*#__PURE__*/function () { + var _findDocumentsById = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(ids, deleted) { + var _this3 = this; + var localState, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, _lokijsHelper.mustUseLocalState)(this); + case 2: + localState = _context2.sent; + if (localState) { + _context2.next = 5; + break; + } + return _context2.abrupt("return", (0, _lokijsHelper.requestRemoteInstance)(this, 'findDocumentsById', [ids, deleted])); + case 5: + ret = {}; + ids.forEach(function (id) { + var documentInDb = localState.collection.by(_this3.primaryPath, id); + if (documentInDb && (!documentInDb._deleted || deleted)) { + ret[id] = (0, _lokijsHelper.stripLokiKey)(documentInDb); + } + }); + return _context2.abrupt("return", ret); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function findDocumentsById(_x3, _x4) { + return _findDocumentsById.apply(this, arguments); + } + return findDocumentsById; + }(); + _proto.query = /*#__PURE__*/function () { + var _query = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(preparedQuery) { + var localState, query, foundDocuments; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _lokijsHelper.mustUseLocalState)(this); + case 2: + localState = _context3.sent; + if (localState) { + _context3.next = 5; + break; + } + return _context3.abrupt("return", (0, _lokijsHelper.requestRemoteInstance)(this, 'query', [preparedQuery])); + case 5: + query = localState.collection.chain().find(preparedQuery.selector); + if (preparedQuery.sort) { + query = query.sort((0, _lokijsHelper.getLokiSortComparator)(this.schema, preparedQuery)); + } + + /** + * Offset must be used before limit in LokiJS + * @link https://github.com/techfort/LokiJS/issues/570 + */ + if (preparedQuery.skip) { + query = query.offset(preparedQuery.skip); + } + if (preparedQuery.limit) { + query = query.limit(preparedQuery.limit); + } + foundDocuments = query.data().map(function (lokiDoc) { + return (0, _lokijsHelper.stripLokiKey)(lokiDoc); + }); + return _context3.abrupt("return", { + documents: foundDocuments + }); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function query(_x5) { + return _query.apply(this, arguments); + } + return query; + }(); + _proto.count = /*#__PURE__*/function () { + var _count = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(preparedQuery) { + var result; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return this.query(preparedQuery); + case 2: + result = _context4.sent; + return _context4.abrupt("return", { + count: result.documents.length, + mode: 'fast' + }); + case 4: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function count(_x6) { + return _count.apply(this, arguments); + } + return count; + }(); + _proto.getAttachmentData = function getAttachmentData(_documentId, _attachmentId) { + throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.'); + }; + _proto.getChangedDocumentsSince = /*#__PURE__*/function () { + var _getChangedDocumentsSince = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(limit, checkpoint) { + var localState, sinceLwt, query, changedDocs, first, lastDoc; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return (0, _lokijsHelper.mustUseLocalState)(this); + case 2: + localState = _context5.sent; + if (localState) { + _context5.next = 5; + break; + } + return _context5.abrupt("return", (0, _lokijsHelper.requestRemoteInstance)(this, 'getChangedDocumentsSince', [limit, checkpoint])); + case 5: + sinceLwt = checkpoint ? checkpoint.lwt : _utils.RX_META_LWT_MINIMUM; + query = localState.collection.chain().find({ + '_meta.lwt': { + $gte: sinceLwt + } + }).sort((0, _utils.getSortDocumentsByLastWriteTimeComparator)(this.primaryPath)); + changedDocs = query.data(); + first = changedDocs[0]; + if (checkpoint && first && first[this.primaryPath] === checkpoint.id && first._meta.lwt === checkpoint.lwt) { + changedDocs.shift(); + } + changedDocs = changedDocs.slice(0, limit); + lastDoc = (0, _utils.lastOfArray)(changedDocs); + return _context5.abrupt("return", { + documents: changedDocs.map(function (docData) { + return (0, _lokijsHelper.stripLokiKey)(docData); + }), + checkpoint: lastDoc ? { + id: lastDoc[this.primaryPath], + lwt: lastDoc._meta.lwt + } : checkpoint ? checkpoint : { + id: '', + lwt: 0 + } + }); + case 13: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function getChangedDocumentsSince(_x7, _x8) { + return _getChangedDocumentsSince.apply(this, arguments); + } + return getChangedDocumentsSince; + }(); + _proto.changeStream = function changeStream() { + return this.changes$.asObservable(); + }; + _proto.cleanup = /*#__PURE__*/function () { + var _cleanup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(minimumDeletedTime) { + var localState, deleteAmountPerRun, maxDeletionTime, query, foundDocuments; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return (0, _lokijsHelper.mustUseLocalState)(this); + case 2: + localState = _context6.sent; + if (localState) { + _context6.next = 5; + break; + } + return _context6.abrupt("return", (0, _lokijsHelper.requestRemoteInstance)(this, 'cleanup', [minimumDeletedTime])); + case 5: + deleteAmountPerRun = 10; + maxDeletionTime = (0, _utils.now)() - minimumDeletedTime; + query = localState.collection.chain().find({ + _deleted: true, + '_meta.lwt': { + $lt: maxDeletionTime + } + }).limit(deleteAmountPerRun); + foundDocuments = query.data(); + if (foundDocuments.length > 0) { + localState.collection.remove(foundDocuments); + localState.databaseState.saveQueue.addWrite(); + } + return _context6.abrupt("return", foundDocuments.length !== deleteAmountPerRun); + case 11: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function cleanup(_x9) { + return _cleanup.apply(this, arguments); + } + return cleanup; + }(); + _proto.close = /*#__PURE__*/function () { + var _close = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { + var localState, dbState; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + if (!this.closed) { + _context7.next = 2; + break; + } + return _context7.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.changes$.complete(); + _lokijsHelper.OPEN_LOKIJS_STORAGE_INSTANCES["delete"](this); + if (!this.internals.localState) { + _context7.next = 16; + break; + } + _context7.next = 8; + return this.internals.localState; + case 8: + localState = _context7.sent; + _context7.next = 11; + return (0, _lokijsHelper.getLokiDatabase)(this.databaseName, this.databaseSettings); + case 11: + dbState = _context7.sent; + _context7.next = 14; + return dbState.saveQueue.run(); + case 14: + _context7.next = 16; + return (0, _lokijsHelper.closeLokiCollections)(this.databaseName, [localState.collection]); + case 16: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function close() { + return _close.apply(this, arguments); + } + return close; + }(); + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { + var localState; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return (0, _lokijsHelper.mustUseLocalState)(this); + case 2: + localState = _context8.sent; + if (localState) { + _context8.next = 5; + break; + } + return _context8.abrupt("return", (0, _lokijsHelper.requestRemoteInstance)(this, 'remove', [])); + case 5: + localState.databaseState.database.removeCollection(localState.collection.name); + _context8.next = 8; + return localState.databaseState.saveQueue.run(); + case 8: + return _context8.abrupt("return", this.close()); + case 9: + case "end": + return _context8.stop(); + } + }, _callee8, this); + })); + function remove() { + return _remove.apply(this, arguments); + } + return remove; + }(); + _proto.conflictResultionTasks = function conflictResultionTasks() { + return new _rxjs.Subject(); + }; + _proto.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(_taskSolution) { + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + function resolveConflictResultionTask(_x10) { + return _resolveConflictResultionTask.apply(this, arguments); + } + return resolveConflictResultionTask; + }(); + return RxStorageInstanceLoki; +}(); +exports.RxStorageInstanceLoki = RxStorageInstanceLoki; +function createLokiLocalState(_x11, _x12) { + return _createLokiLocalState.apply(this, arguments); +} +function _createLokiLocalState() { + _createLokiLocalState = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(params, databaseSettings) { + var databaseState, indices, primaryKey, lokiCollectionName, collectionOptions, collection, ret; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + if (!params.options) { + params.options = {}; + } + _context10.next = 3; + return (0, _lokijsHelper.getLokiDatabase)(params.databaseName, databaseSettings); + case 3: + databaseState = _context10.sent; + /** + * Construct loki indexes from RxJsonSchema indexes. + * TODO what about compound indexes? Are they possible in lokijs? + */ + indices = []; + if (params.schema.indexes) { + params.schema.indexes.forEach(function (idx) { + if (!(0, _utils.isMaybeReadonlyArray)(idx)) { + indices.push(idx); + } + }); + } + /** + * LokiJS has no concept of custom primary key, they use a number-id that is generated. + * To be able to query fast by primary key, we always add an index to the primary. + */ + primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(params.schema.primaryKey); + indices.push(primaryKey); + lokiCollectionName = params.collectionName + '-' + params.schema.version; + collectionOptions = Object.assign({}, lokiCollectionName, { + indices: indices, + unique: [primaryKey] + }, _lokijsHelper.LOKIJS_COLLECTION_DEFAULT_OPTIONS); + collection = databaseState.database.addCollection(lokiCollectionName, collectionOptions); + databaseState.collections[params.collectionName] = collection; + ret = { + databaseState: databaseState, + collection: collection + }; + return _context10.abrupt("return", ret); + case 14: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + return _createLokiLocalState.apply(this, arguments); +} +function createLokiStorageInstance(_x13, _x14, _x15) { + return _createLokiStorageInstance.apply(this, arguments); +} +function _createLokiStorageInstance() { + _createLokiStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(storage, params, databaseSettings) { + var internals, broadcastChannelRefObject, leaderElector, instance, closeBefore, removeBefore; + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + internals = {}; + broadcastChannelRefObject = {}; + if (!params.multiInstance) { + _context11.next = 7; + break; + } + leaderElector = (0, _lokijsHelper.getLokiLeaderElector)(params.databaseInstanceToken, broadcastChannelRefObject, params.databaseName); + internals.leaderElector = leaderElector; + _context11.next = 10; + break; + case 7: + // optimisation shortcut, directly create db is non multi instance. + internals.localState = createLokiLocalState(params, databaseSettings); + _context11.next = 10; + return internals.localState; + case 10: + instance = new RxStorageInstanceLoki(params.databaseInstanceToken, storage, params.databaseName, params.collectionName, params.schema, internals, params.options, databaseSettings); + (0, _rxStorageMultiinstance.addRxStorageMultiInstanceSupport)(_lokijsHelper.RX_STORAGE_NAME_LOKIJS, params, instance, internals.leaderElector ? internals.leaderElector.broadcastChannel : undefined); + if (params.multiInstance) { + /** + * Clean up the broadcast-channel reference on close() + */ + closeBefore = instance.close.bind(instance); + instance.close = function () { + (0, _rxStorageMultiinstance.removeBroadcastChannelReference)(params.databaseInstanceToken, broadcastChannelRefObject); + return closeBefore(); + }; + removeBefore = instance.remove.bind(instance); + instance.remove = function () { + (0, _rxStorageMultiinstance.removeBroadcastChannelReference)(params.databaseInstanceToken, broadcastChannelRefObject); + return removeBefore(); + }; + + /** + * Directly create the localState when/if the db becomes leader. + */ + (0, _utils.ensureNotFalsy)(internals.leaderElector).awaitLeadership().then(function () { + if (!instance.closed) { + (0, _lokijsHelper.mustUseLocalState)(instance); + } + }); + } + return _context11.abrupt("return", instance); + case 14: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + return _createLokiStorageInstance.apply(this, arguments); +} +//# sourceMappingURL=rx-storage-instance-loki.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-lokijs/rx-storage-instance-loki.js.map b/dist/lib/plugins/storage-lokijs/rx-storage-instance-loki.js.map new file mode 100644 index 00000000000..95ce2ee2a2e --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/rx-storage-instance-loki.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-loki.js","names":["instanceId","now","RxStorageInstanceLoki","databaseInstanceToken","storage","databaseName","collectionName","schema","internals","options","databaseSettings","changes$","Subject","closed","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","OPEN_LOKIJS_STORAGE_INSTANCES","add","leaderElector","copiedSelf","bulkWrite","bind","changeStream","cleanup","close","query","count","findDocumentsById","conflictResultionTasks","getAttachmentData","getChangedDocumentsSince","remove","resolveConflictResultionTask","awaitLeadership","then","ensureNotFalsy","broadcastChannel","addEventListener","msg","handleRemoteRequest","documentWrites","context","length","newRxError","args","mustUseLocalState","localState","requestRemoteInstance","ret","success","error","docsInDb","Map","docsInDbWithLokiKey","forEach","writeRow","id","document","documentInDb","collection","by","set","stripLokiKey","categorized","categorizeBulkWriteRows","errors","bulkInsertDocs","docId","insert","flatClone","bulkUpdateDocs","documentInDbWithLokiKey","getFromMapOrThrow","writeDoc","Object","assign","$loki","update","databaseState","saveQueue","addWrite","eventBulk","events","lastState","getNewestOfDocumentStates","values","checkpoint","lwt","_meta","next","ids","deleted","_deleted","preparedQuery","chain","find","selector","sort","getLokiSortComparator","skip","offset","limit","foundDocuments","data","map","lokiDoc","documents","result","mode","_documentId","_attachmentId","Error","sinceLwt","RX_META_LWT_MINIMUM","$gte","getSortDocumentsByLastWriteTimeComparator","changedDocs","first","shift","slice","lastDoc","lastOfArray","docData","asObservable","minimumDeletedTime","deleteAmountPerRun","maxDeletionTime","$lt","Promise","reject","complete","getLokiDatabase","dbState","run","closeLokiCollections","database","removeCollection","name","_taskSolution","createLokiLocalState","params","indices","indexes","idx","isMaybeReadonlyArray","push","lokiCollectionName","version","collectionOptions","unique","LOKIJS_COLLECTION_DEFAULT_OPTIONS","addCollection","collections","createLokiStorageInstance","broadcastChannelRefObject","multiInstance","getLokiLeaderElector","instance","addRxStorageMultiInstanceSupport","RX_STORAGE_NAME_LOKIJS","undefined","closeBefore","removeBroadcastChannelReference","removeBefore"],"sources":["../../../../src/plugins/storage-lokijs/rx-storage-instance-loki.ts"],"sourcesContent":["import {\n Subject,\n Observable\n} from 'rxjs';\nimport {\n flatClone,\n now,\n ensureNotFalsy,\n isMaybeReadonlyArray,\n getFromMapOrThrow,\n getSortDocumentsByLastWriteTimeComparator,\n RX_META_LWT_MINIMUM,\n lastOfArray\n} from '../utils';\nimport { newRxError } from '../../rx-error';\nimport type {\n RxStorageInstance,\n LokiSettings,\n RxStorageChangeEvent,\n RxDocumentData,\n BulkWriteRow,\n RxStorageBulkWriteResponse,\n RxStorageQueryResult,\n RxJsonSchema,\n MangoQuery,\n LokiStorageInternals,\n RxStorageInstanceCreationParams,\n LokiDatabaseSettings,\n LokiLocalDatabaseState,\n EventBulk,\n StringKeys,\n RxDocumentDataById,\n DeepReadonly,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageDefaultCheckpoint,\n RxStorageCountResult\n} from '../../types';\nimport {\n closeLokiCollections,\n getLokiDatabase,\n OPEN_LOKIJS_STORAGE_INSTANCES,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS,\n stripLokiKey,\n getLokiSortComparator,\n getLokiLeaderElector,\n requestRemoteInstance,\n mustUseLocalState,\n handleRemoteRequest,\n RX_STORAGE_NAME_LOKIJS\n} from './lokijs-helper';\nimport type {\n Collection\n} from 'lokijs';\nimport type { RxStorageLoki } from './rx-storage-lokijs';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport { categorizeBulkWriteRows, getNewestOfDocumentStates } from '../../rx-storage-helper';\nimport { addRxStorageMultiInstanceSupport, removeBroadcastChannelReference } from '../../rx-storage-multiinstance';\n\nlet instanceId = now();\n\nexport class RxStorageInstanceLoki implements RxStorageInstance<\n RxDocType,\n LokiStorageInternals,\n LokiSettings,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n private changes$: Subject>, RxStorageDefaultCheckpoint>> = new Subject();\n public readonly instanceId = instanceId++;\n\n public closed = false;\n\n constructor(\n public readonly databaseInstanceToken: string,\n public readonly storage: RxStorageLoki,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: LokiStorageInternals,\n public readonly options: Readonly,\n public readonly databaseSettings: LokiDatabaseSettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n OPEN_LOKIJS_STORAGE_INSTANCES.add(this);\n if (this.internals.leaderElector) {\n\n\n /**\n * To run handleRemoteRequest(),\n * the instance will call its own methods.\n * But these methods could have already been swapped out by a RxStorageWrapper\n * so we must store the original methods here and use them instead.\n */\n const copiedSelf: RxStorageInstance = {\n bulkWrite: this.bulkWrite.bind(this),\n changeStream: this.changeStream.bind(this),\n cleanup: this.cleanup.bind(this),\n close: this.close.bind(this),\n query: this.query.bind(this),\n count: this.count.bind(this),\n findDocumentsById: this.findDocumentsById.bind(this),\n collectionName: this.collectionName,\n databaseName: this.databaseName,\n conflictResultionTasks: this.conflictResultionTasks.bind(this),\n getAttachmentData: this.getAttachmentData.bind(this),\n getChangedDocumentsSince: this.getChangedDocumentsSince.bind(this),\n internals: this.internals,\n options: this.options,\n remove: this.remove.bind(this),\n resolveConflictResultionTask: this.resolveConflictResultionTask.bind(this),\n schema: this.schema\n };\n\n this.internals.leaderElector.awaitLeadership().then(() => {\n // this instance is leader now, so it has to reply to queries from other instances\n ensureNotFalsy(this.internals.leaderElector).broadcastChannel\n .addEventListener('message', (msg) => handleRemoteRequest(copiedSelf as any, msg));\n });\n }\n }\n\n async bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n if (documentWrites.length === 0) {\n throw newRxError('P2', {\n args: {\n documentWrites\n }\n });\n }\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'bulkWrite', [documentWrites]);\n }\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const docsInDb: Map[StringKeys], RxDocumentData> = new Map();\n const docsInDbWithLokiKey: Map<\n RxDocumentData[StringKeys],\n RxDocumentData & { $loki: number; }\n > = new Map();\n documentWrites.forEach(writeRow => {\n const id = writeRow.document[this.primaryPath];\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (documentInDb) {\n docsInDbWithLokiKey.set(id as any, documentInDb);\n docsInDb.set(id as any, stripLokiKey(documentInDb));\n }\n });\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n docsInDb,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n localState.collection.insert(flatClone(writeRow.document));\n ret.success[docId as any] = writeRow.document;\n });\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n const documentInDbWithLokiKey = getFromMapOrThrow(docsInDbWithLokiKey, docId as any);\n const writeDoc: any = Object.assign(\n {},\n writeRow.document,\n {\n $loki: documentInDbWithLokiKey.$loki\n }\n );\n localState.collection.update(writeDoc);\n ret.success[docId as any] = writeRow.document;\n });\n localState.databaseState.saveQueue.addWrite();\n\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.changes$.next(categorized.eventBulk);\n }\n\n return ret;\n }\n async findDocumentsById(ids: string[], deleted: boolean): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'findDocumentsById', [ids, deleted]);\n }\n\n const ret: RxDocumentDataById = {};\n ids.forEach(id => {\n const documentInDb = localState.collection.by(this.primaryPath, id);\n if (\n documentInDb &&\n (!documentInDb._deleted || deleted)\n ) {\n ret[id] = stripLokiKey(documentInDb);\n }\n });\n return ret;\n }\n async query(preparedQuery: MangoQuery): Promise> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'query', [preparedQuery]);\n }\n\n let query = localState.collection\n .chain()\n .find(preparedQuery.selector);\n\n if (preparedQuery.sort) {\n query = query.sort(getLokiSortComparator(this.schema, preparedQuery));\n }\n\n /**\n * Offset must be used before limit in LokiJS\n * @link https://github.com/techfort/LokiJS/issues/570\n */\n if (preparedQuery.skip) {\n query = query.offset(preparedQuery.skip);\n }\n\n if (preparedQuery.limit) {\n query = query.limit(preparedQuery.limit);\n }\n\n const foundDocuments = query.data().map(lokiDoc => stripLokiKey(lokiDoc));\n return {\n documents: foundDocuments\n };\n }\n async count(\n preparedQuery: MangoQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n getAttachmentData(_documentId: string, _attachmentId: string): Promise {\n throw new Error('Attachments are not implemented in the lokijs RxStorage. Make a pull request.');\n }\n\n\n async getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint | null\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'getChangedDocumentsSince', [limit, checkpoint]);\n }\n\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const query = localState.collection\n .chain()\n .find({\n '_meta.lwt': {\n $gte: sinceLwt\n }\n })\n .sort(getSortDocumentsByLastWriteTimeComparator(this.primaryPath as any));\n let changedDocs = query.data();\n\n const first = changedDocs[0];\n if (\n checkpoint &&\n first &&\n first[this.primaryPath] === checkpoint.id &&\n first._meta.lwt === checkpoint.lwt\n ) {\n changedDocs.shift();\n }\n\n changedDocs = changedDocs.slice(0, limit);\n const lastDoc = lastOfArray(changedDocs);\n return {\n documents: changedDocs.map(docData => stripLokiKey(docData)),\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath],\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n return this.changes$.asObservable();\n }\n\n async cleanup(minimumDeletedTime: number): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'cleanup', [minimumDeletedTime]);\n }\n\n const deleteAmountPerRun = 10;\n const maxDeletionTime = now() - minimumDeletedTime;\n const query = localState.collection\n .chain()\n .find({\n _deleted: true,\n '_meta.lwt': {\n $lt: maxDeletionTime\n }\n }).limit(deleteAmountPerRun);\n const foundDocuments = query.data();\n if (foundDocuments.length > 0) {\n localState.collection.remove(foundDocuments);\n localState.databaseState.saveQueue.addWrite();\n }\n\n return foundDocuments.length !== deleteAmountPerRun;\n }\n\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.changes$.complete();\n OPEN_LOKIJS_STORAGE_INSTANCES.delete(this);\n\n if (this.internals.localState) {\n const localState = await this.internals.localState;\n const dbState = await getLokiDatabase(\n this.databaseName,\n this.databaseSettings\n );\n await dbState.saveQueue.run();\n await closeLokiCollections(\n this.databaseName,\n [\n localState.collection\n ]\n );\n }\n }\n async remove(): Promise {\n const localState = await mustUseLocalState(this);\n if (!localState) {\n return requestRemoteInstance(this, 'remove', []);\n }\n localState.databaseState.database.removeCollection(localState.collection.name);\n await localState.databaseState.saveQueue.run();\n return this.close();\n }\n\n conflictResultionTasks(): Observable> {\n return new Subject();\n }\n async resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise { }\n\n}\n\nexport async function createLokiLocalState(\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise {\n if (!params.options) {\n params.options = {};\n }\n\n const databaseState = await getLokiDatabase(\n params.databaseName,\n databaseSettings\n );\n\n /**\n * Construct loki indexes from RxJsonSchema indexes.\n * TODO what about compound indexes? Are they possible in lokijs?\n */\n const indices: string[] = [];\n if (params.schema.indexes) {\n params.schema.indexes.forEach(idx => {\n if (!isMaybeReadonlyArray(idx)) {\n indices.push(idx);\n }\n });\n }\n /**\n * LokiJS has no concept of custom primary key, they use a number-id that is generated.\n * To be able to query fast by primary key, we always add an index to the primary.\n */\n const primaryKey = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n indices.push(primaryKey as string);\n\n const lokiCollectionName = params.collectionName + '-' + params.schema.version;\n const collectionOptions: Partial>> = Object.assign(\n {},\n lokiCollectionName,\n {\n indices: indices as string[],\n unique: [primaryKey]\n } as any,\n LOKIJS_COLLECTION_DEFAULT_OPTIONS\n );\n\n const collection: Collection = databaseState.database.addCollection(\n lokiCollectionName,\n collectionOptions as any\n );\n databaseState.collections[params.collectionName] = collection;\n const ret: LokiLocalDatabaseState = {\n databaseState,\n collection\n };\n\n return ret;\n}\n\n\nexport async function createLokiStorageInstance(\n storage: RxStorageLoki,\n params: RxStorageInstanceCreationParams,\n databaseSettings: LokiDatabaseSettings\n): Promise> {\n const internals: LokiStorageInternals = {};\n\n const broadcastChannelRefObject: DeepReadonly = {};\n\n\n if (params.multiInstance) {\n const leaderElector = getLokiLeaderElector(\n params.databaseInstanceToken,\n broadcastChannelRefObject,\n params.databaseName\n );\n internals.leaderElector = leaderElector;\n } else {\n // optimisation shortcut, directly create db is non multi instance.\n internals.localState = createLokiLocalState(params, databaseSettings);\n await internals.localState;\n }\n\n const instance = new RxStorageInstanceLoki(\n params.databaseInstanceToken,\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n databaseSettings\n );\n\n addRxStorageMultiInstanceSupport(\n RX_STORAGE_NAME_LOKIJS,\n params,\n instance,\n internals.leaderElector ? internals.leaderElector.broadcastChannel : undefined\n );\n\n if (params.multiInstance) {\n /**\n * Clean up the broadcast-channel reference on close()\n */\n const closeBefore = instance.close.bind(instance);\n instance.close = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return closeBefore();\n };\n const removeBefore = instance.remove.bind(instance);\n instance.remove = function () {\n removeBroadcastChannelReference(\n params.databaseInstanceToken,\n broadcastChannelRefObject\n );\n return removeBefore();\n };\n\n /**\n * Directly create the localState when/if the db becomes leader.\n */\n ensureNotFalsy(internals.leaderElector)\n .awaitLeadership()\n .then(() => {\n if (!instance.closed) {\n mustUseLocalState(instance);\n }\n });\n }\n\n\n return instance;\n}\n"],"mappings":";;;;;;;;;;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,SAAS,CAACW,aAAa,GAAGX,SAAS,CAACW,aAAa,CAACkB,gBAAgB,GAAG4H,SAAS,CACjF;UAED,IAAIpB,MAAM,CAACe,aAAa,EAAE;YACtB;AACR;AACA;YACcM,WAAW,GAAGJ,QAAQ,CAACrI,KAAK,CAACH,IAAI,CAACwI,QAAQ,CAAC;YACjDA,QAAQ,CAACrI,KAAK,GAAG,YAAY;cACzB,IAAA0I,uDAA+B,EAC3BtB,MAAM,CAAC1I,qBAAqB,EAC5BwJ,yBAAyB,CAC5B;cACD,OAAOO,WAAW,EAAE;YACxB,CAAC;YACKE,YAAY,GAAGN,QAAQ,CAAC9H,MAAM,CAACV,IAAI,CAACwI,QAAQ,CAAC;YACnDA,QAAQ,CAAC9H,MAAM,GAAG,YAAY;cAC1B,IAAAmI,uDAA+B,EAC3BtB,MAAM,CAAC1I,qBAAqB,EAC5BwJ,yBAAyB,CAC5B;cACD,OAAOS,YAAY,EAAE;YACzB,CAAC;;YAED;AACR;AACA;YACQ,IAAAhI,qBAAc,EAAC5B,SAAS,CAACW,aAAa,CAAC,CAClCe,eAAe,EAAE,CACjBC,IAAI,CAAC,YAAM;cACR,IAAI,CAAC2H,QAAQ,CAACjJ,MAAM,EAAE;gBAClB,IAAAiC,+BAAiB,EAACgH,QAAQ,CAAC;cAC/B;YACJ,CAAC,CAAC;UACV;UAAC,mCAGMA,QAAQ;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAClB;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/lokijs/rx-storage-lokijs.js b/dist/lib/plugins/storage-lokijs/rx-storage-lokijs.js similarity index 93% rename from dist/lib/plugins/lokijs/rx-storage-lokijs.js rename to dist/lib/plugins/storage-lokijs/rx-storage-lokijs.js index 68ef9c18763..be903099db9 100644 --- a/dist/lib/plugins/lokijs/rx-storage-lokijs.js +++ b/dist/lib/plugins/storage-lokijs/rx-storage-lokijs.js @@ -7,15 +7,15 @@ Object.defineProperty(exports, "__esModule", { exports.RxStorageLokiStatics = exports.RxStorageLoki = void 0; exports.getRxStorageLoki = getRxStorageLoki; var _lokijs = _interopRequireDefault(require("lokijs")); -var _util = require("../../util"); +var _utils = require("../utils"); var _rxStorageInstanceLoki = require("./rx-storage-instance-loki"); var _lokijsHelper = require("./lokijs-helper"); var _rxStorageHelper = require("../../rx-storage-helper"); var _rxSchemaHelper = require("../../rx-schema-helper"); var RxStorageLokiStatics = { prepareQuery: function prepareQuery(_schema, mutateableQuery) { - mutateableQuery = (0, _util.flatClone)(mutateableQuery); - if (Object.keys((0, _util.ensureNotFalsy)(mutateableQuery.selector)).length > 0) { + mutateableQuery = (0, _utils.flatClone)(mutateableQuery); + if (Object.keys((0, _utils.ensureNotFalsy)(mutateableQuery.selector)).length > 0) { mutateableQuery.selector = { $and: [{ _deleted: false @@ -46,7 +46,7 @@ var RxStorageLokiStatics = { if (doc._deleted) { return false; } - var docWithResetDeleted = (0, _util.flatClone)(doc); + var docWithResetDeleted = (0, _utils.flatClone)(doc); docWithResetDeleted._deleted = !!docWithResetDeleted._deleted; var fakeCollection = { data: [docWithResetDeleted], diff --git a/dist/lib/plugins/storage-lokijs/rx-storage-lokijs.js.map b/dist/lib/plugins/storage-lokijs/rx-storage-lokijs.js.map new file mode 100644 index 00000000000..ecf1336217f --- /dev/null +++ b/dist/lib/plugins/storage-lokijs/rx-storage-lokijs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-lokijs.js","names":["RxStorageLokiStatics","prepareQuery","_schema","mutateableQuery","flatClone","Object","keys","ensureNotFalsy","selector","length","$and","_deleted","getSortComparator","schema","query","getLokiSortComparator","getQueryMatcher","fun","doc","docWithResetDeleted","fakeCollection","data","binaryIndices","setPrototypeOf","lokijs","Collection","prototype","fakeResultSet","collection","Resultset","find","ret","filteredrows","checkpointSchema","DEFAULT_CHECKPOINT_SCHEMA","RxStorageLoki","databaseSettings","name","RX_STORAGE_NAME_LOKIJS","statics","leaderElectorByLokiDbName","Map","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","createLokiStorageInstance","getRxStorageLoki","storage"],"sources":["../../../../src/plugins/storage-lokijs/rx-storage-lokijs.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport lokijs from 'lokijs';\nimport type {\n FilledMangoQuery,\n LokiDatabaseSettings,\n LokiSettings,\n LokiStorageInternals,\n MangoQuery,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageStatics\n} from '../../types';\nimport {\n ensureNotFalsy,\n flatClone\n} from '../utils';\nimport {\n createLokiStorageInstance,\n RxStorageInstanceLoki\n} from './rx-storage-instance-loki';\nimport { getLokiSortComparator, RX_STORAGE_NAME_LOKIJS } from './lokijs-helper';\nimport type { LeaderElector } from 'broadcast-channel';\n\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport { DEFAULT_CHECKPOINT_SCHEMA } from '../../rx-schema-helper';\n\nexport const RxStorageLokiStatics: RxStorageStatics = {\n prepareQuery(\n _schema: RxJsonSchema>,\n mutateableQuery: FilledMangoQuery\n ) {\n mutateableQuery = flatClone(mutateableQuery);\n if (Object.keys(ensureNotFalsy(mutateableQuery.selector)).length > 0) {\n mutateableQuery.selector = {\n $and: [\n {\n _deleted: false\n },\n mutateableQuery.selector\n ]\n } as any;\n } else {\n mutateableQuery.selector = {\n _deleted: false\n } as any;\n }\n\n return mutateableQuery;\n },\n\n\n getSortComparator(\n schema: RxJsonSchema>,\n query: MangoQuery\n ): DeterministicSortComparator {\n return getLokiSortComparator(schema, query);\n },\n\n /**\n * Returns a function that determines if a document matches a query selector.\n * It is important to have the exact same logix as lokijs uses, to be sure\n * that the event-reduce algorithm works correct.\n * But LokisJS does not export such a function, the query logic is deep inside of\n * the Resultset prototype.\n * Because I am lazy, I do not copy paste and maintain that code.\n * Instead we create a fake Resultset and apply the prototype method Resultset.prototype.find(),\n * same with Collection.\n */\n getQueryMatcher(\n _schema: RxJsonSchema,\n query: MangoQuery\n ): QueryMatcher> {\n const fun: QueryMatcher> = (doc: RxDocumentWriteData) => {\n if (doc._deleted) {\n return false;\n }\n const docWithResetDeleted = flatClone(doc);\n docWithResetDeleted._deleted = !!docWithResetDeleted._deleted;\n\n const fakeCollection = {\n data: [docWithResetDeleted],\n binaryIndices: {}\n };\n Object.setPrototypeOf(fakeCollection, (lokijs as any).Collection.prototype);\n const fakeResultSet: any = {\n collection: fakeCollection\n };\n Object.setPrototypeOf(fakeResultSet, (lokijs as any).Resultset.prototype);\n fakeResultSet.find(query.selector, true);\n\n const ret = fakeResultSet.filteredrows.length > 0;\n return ret;\n };\n return fun;\n },\n\n checkpointSchema: DEFAULT_CHECKPOINT_SCHEMA\n};\n\nexport class RxStorageLoki implements RxStorage {\n public name = RX_STORAGE_NAME_LOKIJS;\n public statics = RxStorageLokiStatics;\n\n /**\n * Create one leader elector by db name.\n * This is done inside of the storage, not globally\n * to make it easier to test multi-tab behavior.\n */\n public leaderElectorByLokiDbName: Map = new Map();\n\n constructor(\n public databaseSettings: LokiDatabaseSettings\n ) { }\n\n public createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n return createLokiStorageInstance(this, params, this.databaseSettings);\n }\n}\n\nexport function getRxStorageLoki(\n databaseSettings: LokiDatabaseSettings = {}\n): RxStorageLoki {\n const storage = new RxStorageLoki(databaseSettings);\n return storage;\n}\n"],"mappings":";;;;;;;;AAIA;AAcA;AAIA;AAIA;AAGA;AACA;AAEO,IAAMA,oBAAsC,GAAG;EAClDC,YAAY,wBACRC,OAAgD,EAChDC,eAA4C,EAC9C;IACEA,eAAe,GAAG,IAAAC,gBAAS,EAACD,eAAe,CAAC;IAC5C,IAAIE,MAAM,CAACC,IAAI,CAAC,IAAAC,qBAAc,EAACJ,eAAe,CAACK,QAAQ,CAAC,CAAC,CAACC,MAAM,GAAG,CAAC,EAAE;MAClE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AAG;EACd,CAAC;EAEDgB,gBAAgB,EAAEC;AACtB,CAAC;AAAC;AAAA,IAEWC,aAAa;EAItB;AACJ;AACA;AACA;AACA;;EAUI,uBACWC,gBAAsC,EAC/C;IAAA,KAnBKC,IAAI,GAAGC,oCAAsB;IAAA,KAC7BC,OAAO,GAAGvC,oBAAoB;IAAA,KAO9BwC,yBAAyB,GAO3B,IAAIC,GAAG,EAAE;IAAA,KAGHL,gBAAsC,GAAtCA,gBAAsC;EAC7C;EAAC;EAAA,OAEEM,qBAAqB,GAA5B,+BACIC,MAAgE,EACvB;IACzC,IAAAC,wDAAuC,EAACD,MAAM,CAAC;IAC/C,OAAO,IAAAE,gDAAyB,EAAC,IAAI,EAAEF,MAAM,EAAE,IAAI,CAACP,gBAAgB,CAAC;EACzE,CAAC;EAAA;AAAA;AAAA;AAGE,SAASU,gBAAgB,GAEf;EAAA,IADbV,gBAAsC,uEAAG,CAAC,CAAC;EAE3C,IAAMW,OAAO,GAAG,IAAIZ,aAAa,CAACC,gBAAgB,CAAC;EACnD,OAAOW,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/binary-search-bounds.js b/dist/lib/plugins/storage-memory/binary-search-bounds.js similarity index 100% rename from dist/lib/plugins/memory/binary-search-bounds.js rename to dist/lib/plugins/storage-memory/binary-search-bounds.js diff --git a/dist/lib/plugins/storage-memory/binary-search-bounds.js.map b/dist/lib/plugins/storage-memory/binary-search-bounds.js.map new file mode 100644 index 00000000000..091b06227d8 --- /dev/null +++ b/dist/lib/plugins/storage-memory/binary-search-bounds.js.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search-bounds.js","names":["ge","a","y","c","l","h","i","m","x","p","undefined","gt","lt","le","eq","norm","f","length","boundGE","boundGT","boundLT","boundLE","boundEQ"],"sources":["../../../../src/plugins/storage-memory/binary-search-bounds.ts"],"sourcesContent":["/**\n * Everything in this file was copied and adapted from\n * @link https://github.com/mikolalysenko/binary-search-bounds\n *\n * TODO We should use the original npm module instead when this bug is fixed:\n * @link https://github.com/mikolalysenko/binary-search-bounds/pull/14\n */\n\n\n\ntype Compare = ((a: T, b: T) => number | null | undefined);\n\nfunction ge(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i: number = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x: any = a[m];\n const p: any = (c !== undefined) ? c(x, y) : (x - (y as any));\n if (p >= 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction gt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = h + 1;\n while (l <= h) {\n const m = (l + h) >>> 1;\n const x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p > 0) {\n i = m; h = m - 1;\n } else {\n l = m + 1;\n }\n }\n return i;\n}\n\nfunction lt(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p < 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction le(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n let i = l - 1;\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p <= 0) {\n i = m; l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return i;\n}\n\nfunction eq(a: T[], y: T, c: Compare, l?: any, h?: any): number {\n while (l <= h) {\n const m = (l + h) >>> 1, x = a[m];\n const p: any = (c !== undefined) ? c(x, y) : ((x as any) - (y as any));\n if (p === 0) {\n return m;\n }\n if (p <= 0) {\n l = m + 1;\n } else {\n h = m - 1;\n }\n }\n return -1;\n}\n\nfunction norm(a: T[], y: T, c: Compare, l: any, h: any, f: any) {\n if (typeof c === 'function') {\n return f(a, y, c, (l === undefined) ? 0 : l | 0, (h === undefined) ? a.length - 1 : h | 0);\n }\n return f(a, y, undefined, (c === undefined) ? 0 : c | 0, (l === undefined) ? a.length - 1 : l | 0);\n}\n\n\nexport function boundGE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, ge);\n}\nexport function boundGT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, gt);\n}\nexport function boundLT(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, lt);\n}\nexport function boundLE(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, le);\n}\nexport function boundEQ(a: T[], y: T, c: Compare, l?: any, h?: any) {\n return norm(a, y, c, l, h, eq);\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,EAAE,CAAIC,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAS,GAAGD,CAAC,GAAG,CAAC;EACrB,OAAOD,CAAC,IAAIC,CAAC,EAAE;IACX,IAAME,CAAC,GAAIH,CAAC,GAAGC,CAAC,KAAM,CAAC;IACvB,IAAMG,CAAM,GAAGP,CAAC,CAACM,CAAC,CAAC;IACnB,IAAME,CAAM,GAAIN,CAAC,KAAKO,SAAS,GAAIP,CAAC,CAACK,CAAC,EAAEN,CAAC,CAAC,GAAIM,CAAC,GAAIN,CAAU;IAC7D,IAAIO,CAAC,IAAI,CAAC,EAAE;MACRH,CAAC,GAAGC,CAAC;MAAEF,CAAC,GAAGE,CAAC,GAAG,CAAC;IACpB,CAAC,MAAM;MACHH,CAAC,GAAGG,CAAC,GAAG,CAAC;IACb;EACJ;EACA,OAAOD,CAAC;AACZ;AAEA,SAASK,EAAE,CAAIV,CAAM,EAAEC,CAAI,EAAEC,CAAa,EAAEC,CAAO,EAAEC,CAAO,EAAU;EAClE,IAAIC,CAAC,GAAGD,CAAC,GAAG,CAAC;EACb,OAAO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,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAEC,CAAC,EAAES,EAAE,CAAC;AAClC"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/index.js b/dist/lib/plugins/storage-memory/index.js similarity index 88% rename from dist/lib/plugins/memory/index.js rename to dist/lib/plugins/storage-memory/index.js index 982dae7b410..e0fa17a3aad 100644 --- a/dist/lib/plugins/memory/index.js +++ b/dist/lib/plugins/storage-memory/index.js @@ -8,8 +8,8 @@ var _exportNames = { }; exports.getRxStorageMemory = getRxStorageMemory; var _rxStorageHelper = require("../../rx-storage-helper"); -var _util = require("../../util"); -var _dexieStatics = require("../dexie/dexie-statics"); +var _utils = require("../../plugins/utils"); +var _dexieStatics = require("../storage-dexie/dexie-statics"); var _rxStorageInstanceMemory = require("./rx-storage-instance-memory"); Object.keys(_rxStorageInstanceMemory).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -70,17 +70,23 @@ Object.keys(_memoryIndexes).forEach(function (key) { } }); }); +/** + * Keep the state even when the storage instance is closed. + * This makes it easier to use the memory storage + * to test filesystem-like and multiInstance behaviors. + */ +var COLLECTION_STATES = new Map(); function getRxStorageMemory() { var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var storage = { name: 'memory', statics: _dexieStatics.RxStorageDexieStatics, - collectionStates: new Map(), + collectionStates: COLLECTION_STATES, createStorageInstance: function createStorageInstance(params) { (0, _rxStorageHelper.ensureRxStorageInstanceParamsAreCorrect)(params); // TODO we should not need to append the schema version here. - params = (0, _util.flatClone)(params); + params = (0, _utils.flatClone)(params); params.collectionName = params.collectionName + '-' + params.schema.version; var useSettings = Object.assign({}, settings, params.options); return (0, _rxStorageInstanceMemory.createMemoryStorageInstance)(this, params, useSettings); diff --git a/dist/lib/plugins/storage-memory/index.js.map b/dist/lib/plugins/storage-memory/index.js.map new file mode 100644 index 00000000000..8670c105b67 --- /dev/null +++ b/dist/lib/plugins/storage-memory/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":["COLLECTION_STATES","Map","getRxStorageMemory","settings","storage","name","statics","RxStorageDexieStatics","collectionStates","createStorageInstance","params","ensureRxStorageInstanceParamsAreCorrect","flatClone","collectionName","schema","version","useSettings","Object","assign","options","createMemoryStorageInstance"],"sources":["../../../../src/plugins/storage-memory/index.ts"],"sourcesContent":["import { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper';\nimport type { RxStorageInstanceCreationParams } from '../../types';\nimport { flatClone } from '../../plugins/utils';\nimport { RxStorageDexieStatics } from '../storage-dexie/dexie-statics';\nimport type {\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\nimport {\n createMemoryStorageInstance,\n RxStorageInstanceMemory\n} from './rx-storage-instance-memory';\n\n/**\n * Keep the state even when the storage instance is closed.\n * This makes it easier to use the memory storage\n * to test filesystem-like and multiInstance behaviors.\n */\nconst COLLECTION_STATES = new Map();\n\nexport function getRxStorageMemory(\n settings: RxStorageMemorySettings = {}\n): RxStorageMemory {\n\n const storage: RxStorageMemory = {\n name: 'memory',\n statics: RxStorageDexieStatics,\n collectionStates: COLLECTION_STATES,\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n ensureRxStorageInstanceParamsAreCorrect(params);\n\n // TODO we should not need to append the schema version here.\n params = flatClone(params);\n params.collectionName = params.collectionName + '-' + params.schema.version;\n\n const useSettings = Object.assign(\n {},\n settings,\n params.options\n );\n\n\n return createMemoryStorageInstance(this, params, useSettings);\n }\n };\n\n return storage;\n}\n\n\nexport * from './memory-helper';\nexport * from './binary-search-bounds';\nexport * from './memory-types';\nexport * from './memory-indexes';\nexport * from './rx-storage-instance-memory';\n"],"mappings":";;;;;;;;;AAAA;AAEA;AACA;AAMA;AAgDA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAJA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AA1CA;AACA;AACA;AACA;AACA;AACA,IAAMA,iBAAiB,GAAG,IAAIC,GAAG,EAAE;AAE5B,SAASC,kBAAkB,GAEf;EAAA,IADfC,QAAiC,uEAAG,CAAC,CAAC;EAGtC,IAAMC,OAAwB,GAAG;IAC7BC,IAAI,EAAE,QAAQ;IACdC,OAAO,EAAEC,mCAAqB;IAC9BC,gBAAgB,EAAER,iBAAiB;IACnCS,qBAAqB,iCACjBC,MAA0F,EAC/C;MAC3C,IAAAC,wDAAuC,EAACD,MAAM,CAAC;;MAE/C;MACAA,MAAM,GAAG,IAAAE,gBAAS,EAACF,MAAM,CAAC;MAC1BA,MAAM,CAACG,cAAc,GAAGH,MAAM,CAACG,cAAc,GAAG,GAAG,GAAGH,MAAM,CAACI,MAAM,CAACC,OAAO;MAE3E,IAAMC,WAAW,GAAGC,MAAM,CAACC,MAAM,CAC7B,CAAC,CAAC,EACFf,QAAQ,EACRO,MAAM,CAACS,OAAO,CACjB;MAGD,OAAO,IAAAC,oDAA2B,EAAC,IAAI,EAAEV,MAAM,EAAEM,WAAW,CAAC;IACjE;EACJ,CAAC;EAED,OAAOZ,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/memory-helper.js b/dist/lib/plugins/storage-memory/memory-helper.js similarity index 100% rename from dist/lib/plugins/memory/memory-helper.js rename to dist/lib/plugins/storage-memory/memory-helper.js diff --git a/dist/lib/plugins/storage-memory/memory-helper.js.map b/dist/lib/plugins/storage-memory/memory-helper.js.map new file mode 100644 index 00000000000..cc495a4a919 --- /dev/null +++ b/dist/lib/plugins/storage-memory/memory-helper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-helper.js","names":["getMemoryCollectionKey","databaseName","collectionName","ensureNotRemoved","instance","internals","removed","Error","attachmentMapKey","documentId","attachmentId","SORT_BY_INDEX_STRING","a","b","indexString","putWriteRowToState","docId","state","stateByIndex","row","docInState","documents","set","document","forEach","byIndex","docsWithIndex","newIndexString","getIndexableString","pushAtSortPosition","id","doc","insertPosition","previousIndexString","prev","splice","next","newRxError","args","indexBefore","boundEQ","compareDocsWithIndex","removeDocFromState","primaryPath","schema","Object","values","positionInIndex"],"sources":["../../../../src/plugins/storage-memory/memory-helper.ts"],"sourcesContent":["import type {\n BulkWriteRow,\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport type {\n DocWithIndexString,\n MemoryStorageInternals,\n MemoryStorageInternalsByIndex\n} from './memory-types';\nimport type { RxStorageInstanceMemory } from './rx-storage-instance-memory';\nimport {\n pushAtSortPosition\n} from 'array-push-at-sort-position';\nimport { newRxError } from '../../rx-error';\nimport { boundEQ } from './binary-search-bounds';\n\n\nexport function getMemoryCollectionKey(\n databaseName: string,\n collectionName: string\n): string {\n return databaseName + '--memory--' + collectionName;\n}\n\n\nexport function ensureNotRemoved(\n instance: RxStorageInstanceMemory\n) {\n if (instance.internals.removed) {\n throw new Error('removed');\n }\n}\n\nexport function attachmentMapKey(documentId: string, attachmentId: string): string {\n return documentId + '||' + attachmentId;\n}\n\nconst SORT_BY_INDEX_STRING = (a: DocWithIndexString, b: DocWithIndexString) => {\n if (a.indexString < b.indexString) {\n return -1;\n } else {\n return 1;\n }\n};\n\n\n\nexport function putWriteRowToState(\n docId: string,\n state: MemoryStorageInternals,\n stateByIndex: MemoryStorageInternalsByIndex[],\n row: BulkWriteRow,\n docInState?: RxDocumentData\n) {\n state.documents.set(docId, row.document as any);\n stateByIndex.forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const newIndexString = byIndex.getIndexableString(row.document as any);\n const [, insertPosition] = pushAtSortPosition(\n docsWithIndex,\n {\n id: docId,\n doc: row.document,\n indexString: newIndexString\n },\n SORT_BY_INDEX_STRING,\n true\n );\n\n /**\n * Remove previous if it was in the state\n */\n if (docInState) {\n const previousIndexString = byIndex.getIndexableString(docInState);\n if (previousIndexString === newIndexString) {\n /**\n * Index not changed -> The old doc must be before or after the new one.\n */\n const prev = docsWithIndex[insertPosition - 1];\n if (prev && prev.id === docId) {\n docsWithIndex.splice(insertPosition - 1, 1);\n } else {\n const next = docsWithIndex[insertPosition + 1];\n if (next.id === docId) {\n docsWithIndex.splice(insertPosition + 1, 1);\n } else {\n throw newRxError('SNH', {\n args: {\n row,\n byIndex\n }\n });\n }\n }\n } else {\n /**\n * Index changed, we must search for the old one and remove it.\n */\n const indexBefore = boundEQ(\n docsWithIndex,\n {\n indexString: previousIndexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(indexBefore, 1);\n }\n }\n });\n}\n\n\nexport function removeDocFromState(\n primaryPath: string,\n schema: RxJsonSchema>,\n state: MemoryStorageInternals,\n doc: RxDocumentData\n) {\n const docId: string = (doc as any)[primaryPath];\n state.documents.delete(docId);\n\n Object.values(state.byIndex).forEach(byIndex => {\n const docsWithIndex = byIndex.docsWithIndex;\n const indexString = byIndex.getIndexableString(doc);\n\n const positionInIndex = boundEQ(\n docsWithIndex,\n {\n indexString\n } as any,\n compareDocsWithIndex\n );\n docsWithIndex.splice(positionInIndex, 1);\n });\n}\n\n\nexport function compareDocsWithIndex(\n a: DocWithIndexString,\n b: DocWithIndexString\n): 1 | 0 | -1 {\n if (a.indexString < b.indexString) {\n return -1;\n } else if (a.indexString === b.indexString) {\n return 0;\n } else {\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA;AAGA;AACA;AAGO,SAASA,sBAAsB,CAClCC,YAAoB,EACpBC,cAAsB,EAChB;EACN,OAAOD,YAAY,GAAG,YAAY,GAAGC,cAAc;AACvD;AAGO,SAASC,gBAAgB,CAC5BC,QAAsC,EACxC;EACE,IAAIA,QAAQ,CAACC,SAAS,CAAC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,EAAE,CAAC,CAAC;EAC5C,CAAC,CAAC;AACN;AAGO,SAASN,oBAAoB,CAChC7B,CAAgC,EAChCC,CAAgC,EACtB;EACV,IAAID,CAAC,CAACE,WAAW,GAAGD,CAAC,CAACC,WAAW,EAAE;IAC/B,OAAO,CAAC,CAAC;EACb,CAAC,MAAM,IAAIF,CAAC,CAACE,WAAW,KAAKD,CAAC,CAACC,WAAW,EAAE;IACxC,OAAO,CAAC;EACZ,CAAC,MAAM;IACH,OAAO,CAAC;EACZ;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/memory-indexes.js b/dist/lib/plugins/storage-memory/memory-indexes.js similarity index 94% rename from dist/lib/plugins/memory/memory-indexes.js rename to dist/lib/plugins/storage-memory/memory-indexes.js index 20bc3b28785..d3f55d96c6b 100644 --- a/dist/lib/plugins/memory/memory-indexes.js +++ b/dist/lib/plugins/storage-memory/memory-indexes.js @@ -7,10 +7,11 @@ exports.addIndexesToInternalsState = addIndexesToInternalsState; exports.getMemoryIndexName = getMemoryIndexName; var _customIndex = require("../../custom-index"); var _rxSchemaHelper = require("../../rx-schema-helper"); +var _utils = require("../../plugins/utils"); function addIndexesToInternalsState(state, schema) { var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); var useIndexes = !schema.indexes ? [] : schema.indexes.map(function (row) { - return Array.isArray(row) ? row.slice(0) : [row]; + return (0, _utils.toArray)(row); }); // we need this as default index diff --git a/dist/lib/plugins/storage-memory/memory-indexes.js.map b/dist/lib/plugins/storage-memory/memory-indexes.js.map new file mode 100644 index 00000000000..8ae694d5709 --- /dev/null +++ b/dist/lib/plugins/storage-memory/memory-indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-indexes.js","names":["addIndexesToInternalsState","state","schema","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","useIndexes","indexes","map","row","toArray","push","forEach","indexAr","unshift","byIndex","getMemoryIndexName","index","docsWithIndex","getIndexableString","getIndexableStringMonad","changesIndex","indexName","join"],"sources":["../../../../src/plugins/storage-memory/memory-indexes.ts"],"sourcesContent":["import { getIndexableStringMonad } from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport type { RxDocumentData, RxJsonSchema } from '../../types';\nimport { toArray } from '../../plugins/utils';\nimport type { MemoryStorageInternals } from './memory-types';\n\nexport function addIndexesToInternalsState(\n state: MemoryStorageInternals,\n schema: RxJsonSchema>\n) {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const useIndexes: string[][] = !schema.indexes ? [] : schema.indexes.map(row => toArray(row)) as any;\n\n // we need this as default index\n useIndexes.push([\n primaryPath\n ]);\n\n // we need this index for running cleanup()\n useIndexes.push([\n '_meta.lwt',\n primaryPath\n ]);\n\n\n useIndexes.forEach(indexAr => {\n /**\n * Running a query will only return non-deleted documents\n * so all indexes must have the the deleted field as first index field.\n */\n indexAr.unshift('_deleted');\n\n state.byIndex[getMemoryIndexName(indexAr)] = {\n index: indexAr,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, indexAr)\n };\n });\n\n // we need this index for the changes()\n const changesIndex = [\n '_meta.lwt',\n primaryPath\n ];\n const indexName = getMemoryIndexName(changesIndex);\n state.byIndex[indexName] = {\n index: changesIndex,\n docsWithIndex: [],\n getIndexableString: getIndexableStringMonad(schema, changesIndex)\n };\n\n}\n\n\nexport function getMemoryIndexName(index: string[]): string {\n return index.join(',');\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAEA;AAGO,SAASA,0BAA0B,CACtCC,KAAwC,EACxCC,MAA+C,EACjD;EACE,IAAMC,WAAW,GAAG,IAAAC,2CAA2B,EAACF,MAAM,CAACG,UAAU,CAAC;EAClE,IAAMC,UAAsB,GAAG,CAACJ,MAAM,CAACK,OAAO,GAAG,EAAE,GAAGL,MAAM,CAACK,OAAO,CAACC,GAAG,CAAC,UAAAC,GAAG;IAAA,OAAI,IAAAC,cAAO,EAACD,GAAG,CAAC;EAAA,EAAQ;;EAEpG;EACAH,UAAU,CAACK,IAAI,CAAC,CACZR,WAAW,CACd,CAAC;;EAEF;EACAG,UAAU,CAACK,IAAI,CAAC,CACZ,WAAW,EACXR,WAAW,CACd,CAAC;EAGFG,UAAU,CAACM,OAAO,CAAC,UAAAC,OAAO,EAAI;IAC1B;AACR;AACA;AACA;IACQA,OAAO,CAACC,OAAO,CAAC,UAAU,CAAC;IAE3Bb,KAAK,CAACc,OAAO,CAACC,kBAAkB,CAACH,OAAO,CAAC,CAAC,GAAG;MACzCI,KAAK,EAAEJ,OAAO;MACdK,aAAa,EAAE,EAAE;MACjBC,kBAAkB,EAAE,IAAAC,oCAAuB,EAAClB,MAAM,EAAEW,OAAO;IAC/D,CAAC;EACL,CAAC,CAAC;;EAEF;EACA,IAAMQ,YAAY,GAAG,CACjB,WAAW,EACXlB,WAAW,CACd;EACD,IAAMmB,SAAS,GAAGN,kBAAkB,CAACK,YAAY,CAAC;EAClDpB,KAAK,CAACc,OAAO,CAACO,SAAS,CAAC,GAAG;IACvBL,KAAK,EAAEI,YAAY;IACnBH,aAAa,EAAE,EAAE;IACjBC,kBAAkB,EAAE,IAAAC,oCAAuB,EAAClB,MAAM,EAAEmB,YAAY;EACpE,CAAC;AAEL;AAGO,SAASL,kBAAkB,CAACC,KAAe,EAAU;EACxD,OAAOA,KAAK,CAACM,IAAI,CAAC,GAAG,CAAC;AAC1B"} \ No newline at end of file diff --git a/dist/lib/plugins/memory/memory-types.js b/dist/lib/plugins/storage-memory/memory-types.js similarity index 100% rename from dist/lib/plugins/memory/memory-types.js rename to dist/lib/plugins/storage-memory/memory-types.js diff --git a/dist/lib/plugins/storage-memory/memory-types.js.map b/dist/lib/plugins/storage-memory/memory-types.js.map new file mode 100644 index 00000000000..1f38fed151b --- /dev/null +++ b/dist/lib/plugins/storage-memory/memory-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/storage-memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n DexiePreparedQuery,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n /**\n * We re-use the memory state when multiple instances\n * are created with the same params.\n * If refCount beomces 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n changes$: Subject>, RxStorageDefaultCheckpoint>>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n\nexport type MemoryPreparedQuery = DexiePreparedQuery;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/plugins/memory/rx-storage-instance-memory.js b/dist/lib/plugins/storage-memory/rx-storage-instance-memory.js similarity index 78% rename from dist/lib/plugins/memory/rx-storage-instance-memory.js rename to dist/lib/plugins/storage-memory/rx-storage-instance-memory.js index e72b766966b..80247eca126 100644 --- a/dist/lib/plugins/memory/rx-storage-instance-memory.js +++ b/dist/lib/plugins/storage-memory/rx-storage-instance-memory.js @@ -1,23 +1,25 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RxStorageInstanceMemory = void 0; exports.createMemoryStorageInstance = createMemoryStorageInstance; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _customIndex = require("../../custom-index"); var _rxSchemaHelper = require("../../rx-schema-helper"); var _rxStorageHelper = require("../../rx-storage-helper"); -var _util = require("../../util"); -var _dexieStatics = require("../dexie/dexie-statics"); +var _utils = require("../../plugins/utils"); +var _dexieStatics = require("../storage-dexie/dexie-statics"); var _binarySearchBounds = require("./binary-search-bounds"); var _memoryHelper = require("./memory-helper"); var _memoryIndexes = require("./memory-indexes"); var RxStorageInstanceMemory = /*#__PURE__*/function () { function RxStorageInstanceMemory(storage, databaseName, collectionName, schema, internals, options, settings) { this.closed = false; - this.changes$ = new _rxjs.Subject(); this.storage = storage; this.databaseName = databaseName; this.collectionName = collectionName; @@ -72,7 +74,7 @@ var RxStorageInstanceMemory = /*#__PURE__*/function () { id: lastState[this.primaryPath], lwt: lastState._meta.lwt }; - this.changes$.next(categorized.eventBulk); + this.internals.changes$.next(categorized.eventBulk); } return Promise.resolve(ret); }; @@ -140,21 +142,33 @@ var RxStorageInstanceMemory = /*#__PURE__*/function () { documents: rows }); }; - _proto.count = function count(preparedQuery) { - try { - var _this3 = this; - return Promise.resolve(_this3.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); + _proto.count = /*#__PURE__*/function () { + var _count = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(preparedQuery) { + var result; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.query(preparedQuery); + case 2: + result = _context.sent; + return _context.abrupt("return", { + count: result.documents.length, + mode: 'fast' + }); + case 4: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function count(_x) { + return _count.apply(this, arguments); } - }; + return count; + }(); _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - var sinceLwt = checkpoint ? checkpoint.lwt : _util.RX_META_LWT_MINIMUM; + var sinceLwt = checkpoint ? checkpoint.lwt : _utils.RX_META_LWT_MINIMUM; var sinceId = checkpoint ? checkpoint.id : ''; var index = ['_meta.lwt', this.primaryPath]; var indexName = (0, _memoryIndexes.getMemoryIndexName)(index); @@ -171,7 +185,7 @@ var RxStorageInstanceMemory = /*#__PURE__*/function () { rows.push(currentDoc.doc); indexOfLower++; } - var lastDoc = (0, _util.lastOfArray)(rows); + var lastDoc = (0, _utils.lastOfArray)(rows); return Promise.resolve({ documents: rows, checkpoint: lastDoc ? { @@ -184,7 +198,7 @@ var RxStorageInstanceMemory = /*#__PURE__*/function () { }); }; _proto.cleanup = function cleanup(minimumDeletedTime) { - var maxDeletionTime = (0, _util.now)() - minimumDeletedTime; + var maxDeletionTime = (0, _utils.now)() - minimumDeletedTime; var index = ['_deleted', '_meta.lwt', this.primaryPath]; var indexName = (0, _memoryIndexes.getMemoryIndexName)(index); var docsWithIndex = this.internals.byIndex[indexName].docsWithIndex; @@ -202,45 +216,51 @@ var RxStorageInstanceMemory = /*#__PURE__*/function () { indexOfLower++; } } - return _util.PROMISE_RESOLVE_TRUE; + return _utils.PROMISE_RESOLVE_TRUE; }; _proto.getAttachmentData = function getAttachmentData(documentId, attachmentId) { (0, _memoryHelper.ensureNotRemoved)(this); - var data = (0, _util.getFromMapOrThrow)(this.internals.attachments, (0, _memoryHelper.attachmentMapKey)(documentId, attachmentId)); + var data = (0, _utils.getFromMapOrThrow)(this.internals.attachments, (0, _memoryHelper.attachmentMapKey)(documentId, attachmentId)); return Promise.resolve(data.data); }; _proto.changeStream = function changeStream() { (0, _memoryHelper.ensureNotRemoved)(this); - return this.changes$.asObservable(); + return this.internals.changes$.asObservable(); }; - _proto.remove = function remove() { - try { - var _this4 = this; - (0, _memoryHelper.ensureNotRemoved)(_this4); - _this4.internals.removed = true; - _this4.storage.collectionStates["delete"]((0, _memoryHelper.getMemoryCollectionKey)(_this4.databaseName, _this4.collectionName)); - return Promise.resolve(_this4.close()).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + (0, _memoryHelper.ensureNotRemoved)(this); + this.internals.removed = true; + this.storage.collectionStates["delete"]((0, _memoryHelper.getMemoryCollectionKey)(this.databaseName, this.collectionName)); + _context2.next = 5; + return this.close(); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _proto.close = function close() { if (this.closed) { return Promise.reject(new Error('already closed')); } this.closed = true; - this.changes$.complete(); this.internals.refCount = this.internals.refCount - 1; - if (this.internals.refCount === 0) { - this.storage.collectionStates["delete"]((0, _memoryHelper.getMemoryCollectionKey)(this.databaseName, this.collectionName)); - } - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; }; _proto.conflictResultionTasks = function conflictResultionTasks() { return this.internals.conflictResultionTasks$.asObservable(); }; _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; }; return RxStorageInstanceMemory; }(); @@ -255,7 +275,8 @@ function createMemoryStorageInstance(storage, params, settings) { documents: new Map(), attachments: params.schema.attachments ? new Map() : undefined, byIndex: {}, - conflictResultionTasks$: new _rxjs.Subject() + conflictResultionTasks$: new _rxjs.Subject(), + changes$: new _rxjs.Subject() }; (0, _memoryIndexes.addIndexesToInternalsState)(internals, params.schema); storage.collectionStates.set(collectionKey, internals); diff --git a/dist/lib/plugins/storage-memory/rx-storage-instance-memory.js.map b/dist/lib/plugins/storage-memory/rx-storage-instance-memory.js.map new file mode 100644 index 00000000000..bd19a832f0b --- /dev/null +++ b/dist/lib/plugins/storage-memory/rx-storage-instance-memory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rx-storage-instance-memory.js","names":["RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","bulkWrite","documentWrites","context","ensureNotRemoved","ret","success","error","categorized","categorizeBulkWriteRows","documents","errors","stateByIndex","Object","values","byIndex","bulkInsertDocs","forEach","writeRow","docId","document","putWriteRowToState","undefined","bulkUpdateDocs","get","attachmentsMap","attachments","attachmentsAdd","attachment","set","attachmentMapKey","documentId","attachmentId","attachmentData","attachmentsUpdate","attachmentsRemove","eventBulk","events","length","lastState","getNewestOfDocumentStates","checkpoint","id","lwt","_meta","changes$","next","Promise","resolve","findDocumentsById","docIds","withDeleted","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","RxStorageDexieStatics","getQueryMatcher","queryPlanFields","index","mustManuallyResort","sortFieldsSameAsIndexFields","concat","lowerBound","startKeys","lowerBoundString","getStartIndexStringFromLowerBound","inclusiveStart","upperBound","endKeys","upperBoundString","getStartIndexStringFromUpperBound","inclusiveEnd","indexName","getMemoryIndexName","docsWithIndex","indexOfLower","boundGE","indexString","compareDocsWithIndex","indexOfUpper","boundLE","rows","done","currentDoc","doc","push","sortComparator","getSortComparator","sort","slice","count","result","mode","getChangedDocumentsSince","sinceLwt","RX_META_LWT_MINIMUM","sinceId","boundGT","lastDoc","lastOfArray","cleanup","minimumDeletedTime","maxDeletionTime","now","removeDocFromState","PROMISE_RESOLVE_TRUE","getAttachmentData","data","getFromMapOrThrow","changeStream","asObservable","remove","removed","collectionStates","getMemoryCollectionKey","close","reject","Error","refCount","PROMISE_RESOLVE_VOID","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","Subject","addIndexesToInternalsState","instance"],"sources":["../../../../src/plugins/storage-memory/rx-storage-instance-memory.ts"],"sourcesContent":["import { QueryMatcher } from 'event-reduce-js';\nimport {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper';\nimport {\n categorizeBulkWriteRows,\n getNewestOfDocumentStates\n} from '../../rx-storage-helper';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types';\nimport {\n getFromMapOrThrow,\n lastOfArray,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n RX_META_LWT_MINIMUM\n} from '../../plugins/utils';\nimport { RxStorageDexieStatics } from '../storage-dexie/dexie-statics';\nimport {\n boundGE,\n boundGT,\n boundLE\n} from './binary-search-bounds';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes';\nimport type {\n MemoryPreparedQuery,\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types';\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n ensureNotRemoved(this);\n\n const ret: RxStorageBulkWriteResponse = {\n success: {},\n error: {}\n };\n\n const categorized = categorizeBulkWriteRows(\n this,\n this.primaryPath as any,\n this.internals.documents,\n documentWrites,\n context\n );\n ret.error = categorized.errors;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n categorized.bulkInsertDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n undefined\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n categorized.bulkUpdateDocs.forEach(writeRow => {\n const docId = writeRow.document[this.primaryPath];\n putWriteRowToState(\n docId as any,\n this.internals,\n stateByIndex,\n writeRow,\n this.internals.documents.get(docId as any)\n );\n ret.success[docId as any] = writeRow.document;\n });\n\n /**\n * Handle attachments\n */\n const attachmentsMap = this.internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n attachment.attachmentData\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n if (categorized.eventBulk.events.length > 0) {\n const lastState = getNewestOfDocumentStates(\n this.primaryPath as any,\n Object.values(ret.success)\n );\n categorized.eventBulk.checkpoint = {\n id: lastState[this.primaryPath],\n lwt: lastState._meta.lwt\n };\n this.internals.changes$.next(categorized.eventBulk);\n }\n return Promise.resolve(ret);\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise> {\n const ret: RxDocumentDataById = {};\n docIds.forEach(docId => {\n const docInDb = this.internals.documents.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret[docId] = docInDb;\n }\n });\n return Promise.resolve(ret);\n }\n\n query(preparedQuery: MemoryPreparedQuery): Promise> {\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = RxStorageDexieStatics.getQueryMatcher(\n this.schema,\n preparedQuery\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortFieldsSameAsIndexFields;\n const index: string[] | undefined = ['_deleted'].concat(queryPlanFields);\n let lowerBound: any[] = queryPlan.startKeys;\n lowerBound = [false].concat(lowerBound);\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound,\n queryPlan.inclusiveStart\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = [false].concat(upperBound);\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound,\n queryPlan.inclusiveEnd\n );\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGE(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n const indexOfUpper = boundLE(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n\n\n if (\n !currentDoc ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n\n if (!queryMatcher || queryMatcher(currentDoc.doc)) {\n rows.push(currentDoc.doc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort) ||\n indexOfLower >= docsWithIndex.length\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = RxStorageDexieStatics.getSortComparator(this.schema, preparedQuery);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: MemoryPreparedQuery\n ): Promise {\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: RxStorageDefaultCheckpoint\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: RxStorageDefaultCheckpoint;\n }> {\n const sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? checkpoint.id : '';\n\n const index = ['_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n ['_meta.lwt', this.primaryPath as any],\n [\n sinceLwt,\n sinceId\n ],\n false\n );\n\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n // TODO use array.slice() so we do not have to iterate here\n const rows: RxDocumentData[] = [];\n while (rows.length < limit && indexOfLower < docsWithIndex.length) {\n const currentDoc = docsWithIndex[indexOfLower];\n rows.push(currentDoc.doc);\n indexOfLower++;\n }\n\n const lastDoc = lastOfArray(rows);\n return Promise.resolve({\n documents: rows,\n checkpoint: lastDoc ? {\n id: lastDoc[this.primaryPath] as any,\n lwt: lastDoc._meta.lwt\n } : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n });\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ],\n false\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n ensureNotRemoved(this);\n const data = getFromMapOrThrow(\n this.internals.attachments,\n attachmentMapKey(documentId, attachmentId)\n );\n return Promise.resolve(data.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.internals.changes$.asObservable();\n }\n\n async remove(): Promise {\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(this.databaseName, this.collectionName)\n );\n await this.close();\n }\n\n close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n\n this.internals.refCount = this.internals.refCount - 1;\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(params.databaseName, params.collectionName);\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject(),\n changes$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;;;;;;;;;AACA;AAIA;AAIA;AACA;AAqBA;AAQA;AACA;AAKA;AAQA;AAG0B,IASbA,uBAAuB;EAUhC,iCACoBC,OAAwB,EACxBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAA4C,EAC5CC,OAAyD,EACzDC,QAAiC,EACnD;IAAA,KAVKC,MAAM,GAAG,KAAK;IAAA,KAGDP,OAAwB,GAAxBA,OAAwB;IAAA,KACxBC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAA4C,GAA5CA,SAA4C;IAAA,KAC5CC,OAAyD,GAAzDA,OAAyD;IAAA,KACzDC,QAAiC,GAAjCA,QAAiC;IAEjD,IAAI,CAACE,WAAW,GAAG,IAAAC,2CAA2B,EAAC,IAAI,CAACN,MAAM,CAACO,UAAU,CAAC;EAC1E;EAAC;EAAA,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AS,EAAE,IAAI6H,GAAG,EAAE;MACpB7G,WAAW,EAAE2G,MAAM,CAAC5I,MAAM,CAACiC,WAAW,GAAG,IAAI6G,GAAG,EAAE,GAAGjH,SAAgB;MACrEP,OAAO,EAAE,CAAC,CAAC;MACXkH,uBAAuB,EAAE,IAAIO,aAAO,EAAE;MACtC3F,QAAQ,EAAE,IAAI2F,aAAO;IACzB,CAAC;IACD,IAAAC,yCAA0B,EAAC/I,SAAS,EAAE2I,MAAM,CAAC5I,MAAM,CAAC;IACpDH,OAAO,CAACmI,gBAAgB,CAAC5F,GAAG,CAACyG,aAAa,EAAE5I,SAAS,CAAC;EAC1D,CAAC,MAAM;IACHA,SAAS,CAACoI,QAAQ,GAAGpI,SAAS,CAACoI,QAAQ,GAAG,CAAC;EAC/C;EAEA,IAAMY,QAAQ,GAAG,IAAIrJ,uBAAuB,CACxCC,OAAO,EACP+I,MAAM,CAAC9I,YAAY,EACnB8I,MAAM,CAAC7I,cAAc,EACrB6I,MAAM,CAAC5I,MAAM,EACbC,SAAS,EACT2I,MAAM,CAAC1I,OAAO,EACdC,QAAQ,CACX;EACD,OAAOmD,OAAO,CAACC,OAAO,CAAC0F,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-remote/remote.js b/dist/lib/plugins/storage-remote/remote.js index f3e3b99e3e9..95e296f4cda 100644 --- a/dist/lib/plugins/storage-remote/remote.js +++ b/dist/lib/plugins/storage-remote/remote.js @@ -5,21 +5,12 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.exposeRxStorageRemote = exposeRxStorageRemote; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _storageRemoteHelpers = require("./storage-remote-helpers"); var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} /** * Run this on the 'remote' part, * so that RxStorageMessageChannel can connect to it. @@ -28,130 +19,164 @@ function exposeRxStorageRemote(settings) { var instanceByFullName = new Map(); settings.messages$.pipe((0, _rxjs.filter)(function (msg) { return msg.method === 'create'; - })).subscribe(function (msg) { - try { - var _temp3 = function _temp3(_result2) { - if (_exit) return _result2; - state.connectionIds.add(msg.connectionId); - var subs = []; - /** - * Automatically subscribe to the streams$ - * because we always need them. - */ - subs.push(state.storageInstance.changeStream().subscribe(function (changes) { - var message = { - connectionId: connectionId, - answerTo: 'changestream', - method: 'changeStream', - "return": changes - }; - settings.send(message); - })); - subs.push(state.storageInstance.conflictResultionTasks().subscribe(function (conflicts) { - var message = { - connectionId: connectionId, - answerTo: 'conflictResultionTasks', - method: 'conflictResultionTasks', - "return": conflicts - }; - settings.send(message); - })); - subs.push(settings.messages$.pipe((0, _rxjs.filter)(function (subMsg) { - return subMsg.connectionId === connectionId; - })).subscribe(function (plainMessage) { - try { - var message = plainMessage; - if (message.method === 'create') { - return Promise.resolve(); + })).subscribe( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(msg) { + var connectionId, params, fullName, state, newRxStorageInstance, subs; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + connectionId = msg.connectionId; + /** + * Do an isArray check here + * for runtime check types to ensure we have + * instance creation params and not method input params. + */ + if (!Array.isArray(msg.params)) { + _context2.next = 3; + break; } - if (!Array.isArray(message.params)) { - return Promise.resolve(); + return _context2.abrupt("return"); + case 3: + params = msg.params; + /** + * We de-duplicate the storage instances. + * This makes sense in many environments like + * electron where on main process contains the storage + * for multiple renderer processes. Same goes for SharedWorkers etc. + */ + fullName = [params.databaseName, params.collectionName, params.schema.version].join('|'); + state = instanceByFullName.get(fullName); + if (state) { + _context2.next = 21; + break; } - var result; - return Promise.resolve(_catch(function () { - /** - * On calls to 'close()', - * we only close the main instance if there are no other - * ports connected. - */ - if (message.method === 'close' && (0, _util.ensureNotFalsy)(state).connectionIds.size > 1) { - settings.send((0, _storageRemoteHelpers.createAnswer)(message, null)); - (0, _util.ensureNotFalsy)(state).connectionIds["delete"](connectionId); - subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - return; - } - return Promise.resolve((0, _util.ensureNotFalsy)(state).storageInstance[message.method](message.params[0], message.params[1], message.params[2], message.params[3])).then(function (_message$method) { - result = _message$method; - if (message.method === 'close' || message.method === 'remove') { - subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - (0, _util.ensureNotFalsy)(state).connectionIds["delete"](connectionId); - instanceByFullName["delete"](fullName); - /** - * TODO how to notify the other ports on remove() ? - */ - } - - settings.send((0, _storageRemoteHelpers.createAnswer)(message, result)); - }); - }, function (err) { - settings.send((0, _storageRemoteHelpers.createErrorAnswer)(message, err)); + _context2.prev = 7; + _context2.next = 10; + return settings.storage.createStorageInstance(params); + case 10: + newRxStorageInstance = _context2.sent; + state = { + storageInstance: newRxStorageInstance, + connectionIds: new Set(), + params: params + }; + instanceByFullName.set(fullName, state); + _context2.next = 19; + break; + case 15: + _context2.prev = 15; + _context2.t0 = _context2["catch"](7); + settings.send((0, _storageRemoteHelpers.createErrorAnswer)(msg, _context2.t0)); + return _context2.abrupt("return"); + case 19: + _context2.next = 22; + break; + case 21: + // if instance already existed, ensure that the schema is equal + if (!(0, _fastDeepEqual["default"])(params.schema, state.params.schema)) { + settings.send((0, _storageRemoteHelpers.createErrorAnswer)(msg, new Error('Remote storage: schema not equal to existing storage'))); + } + case 22: + state.connectionIds.add(msg.connectionId); + subs = []; + /** + * Automatically subscribe to the streams$ + * because we always need them. + */ + subs.push(state.storageInstance.changeStream().subscribe(function (changes) { + var message = { + connectionId: connectionId, + answerTo: 'changestream', + method: 'changeStream', + "return": changes + }; + settings.send(message); })); - } catch (e) { - return Promise.reject(e); - } - })); - settings.send((0, _storageRemoteHelpers.createAnswer)(msg, 'ok')); - }; - var _exit = false; - var connectionId = msg.connectionId; - /** - * Do an isArray check here - * for runtime check types to ensure we have - * instance creation params and not method input params. - */ - if (Array.isArray(msg.params)) { - return Promise.resolve(); - } - var params = msg.params; - /** - * We de-duplicate the storage instances. - * This makes sense in many environments like - * electron where on main process contains the storage - * for multiple renderer processes. Same goes for SharedWorkers etc. - */ - var fullName = [params.databaseName, params.collectionName, params.schema.version].join('|'); - var state = instanceByFullName.get(fullName); - var _temp2 = function () { - if (!state) { - var _temp = _catch(function () { - return Promise.resolve(settings.storage.createStorageInstance(params)).then(function (newRxStorageInstance) { - state = { - storageInstance: newRxStorageInstance, - connectionIds: new Set(), - params: params + subs.push(state.storageInstance.conflictResultionTasks().subscribe(function (conflicts) { + var message = { + connectionId: connectionId, + answerTo: 'conflictResultionTasks', + method: 'conflictResultionTasks', + "return": conflicts + }; + settings.send(message); + })); + subs.push(settings.messages$.pipe((0, _rxjs.filter)(function (subMsg) { + return subMsg.connectionId === connectionId; + })).subscribe( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(plainMessage) { + var message, result; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + message = plainMessage; + if (!(message.method === 'create')) { + _context.next = 3; + break; + } + return _context.abrupt("return"); + case 3: + if (Array.isArray(message.params)) { + _context.next = 5; + break; + } + return _context.abrupt("return"); + case 5: + _context.prev = 5; + if (!(message.method === 'close' && (0, _utils.ensureNotFalsy)(state).connectionIds.size > 1)) { + _context.next = 11; + break; + } + settings.send((0, _storageRemoteHelpers.createAnswer)(message, null)); + (0, _utils.ensureNotFalsy)(state).connectionIds["delete"](connectionId); + subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + return _context.abrupt("return"); + case 11: + _context.next = 13; + return (0, _utils.ensureNotFalsy)(state).storageInstance[message.method](message.params[0], message.params[1], message.params[2], message.params[3]); + case 13: + result = _context.sent; + if (message.method === 'close' || message.method === 'remove') { + subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + (0, _utils.ensureNotFalsy)(state).connectionIds["delete"](connectionId); + instanceByFullName["delete"](fullName); + /** + * TODO how to notify the other ports on remove() ? + */ + } + + settings.send((0, _storageRemoteHelpers.createAnswer)(message, result)); + _context.next = 21; + break; + case 18: + _context.prev = 18; + _context.t0 = _context["catch"](5); + settings.send((0, _storageRemoteHelpers.createErrorAnswer)(message, _context.t0)); + case 21: + case "end": + return _context.stop(); + } + }, _callee, null, [[5, 18]]); + })); + return function (_x2) { + return _ref2.apply(this, arguments); }; - instanceByFullName.set(fullName, state); - }); - }, function (err) { - settings.send((0, _storageRemoteHelpers.createErrorAnswer)(msg, err)); - _exit = true; - }); - if (_temp && _temp.then) return _temp.then(function () {}); - } else { - if (!(0, _fastDeepEqual["default"])(params.schema, state.params.schema)) { - settings.send((0, _storageRemoteHelpers.createErrorAnswer)(msg, new Error('Remote storage: schema not equal to existing storage'))); - } + }())); + settings.send((0, _storageRemoteHelpers.createAnswer)(msg, 'ok')); + case 28: + case "end": + return _context2.stop(); } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } - }); + }, _callee2, null, [[7, 15]]); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); return { instanceByFullName: instanceByFullName }; diff --git a/dist/lib/plugins/storage-remote/remote.js.map b/dist/lib/plugins/storage-remote/remote.js.map index 1bf3d05ff50..87f022d193f 100644 --- a/dist/lib/plugins/storage-remote/remote.js.map +++ b/dist/lib/plugins/storage-remote/remote.js.map @@ -1 +1 @@ -{"version":3,"file":"remote.js","names":["body","recover","result","e","then","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","filter","msg","method","subscribe","state","connectionIds","add","connectionId","subs","push","storageInstance","changeStream","changes","message","answerTo","send","conflictResultionTasks","conflicts","subMsg","plainMessage","Array","isArray","params","ensureNotFalsy","size","createAnswer","forEach","sub","unsubscribe","fullName","err","createErrorAnswer","databaseName","collectionName","schema","version","join","get","storage","createStorageInstance","newRxStorageInstance","Set","set","deepEqual","Error"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNotFalsy\n} from '../../util';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeType\n} from './storage-remote-types';\nimport deepEqual from 'fast-deep-equal';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstance: RxStorageInstance;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n const connectionId = msg.connectionId;\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n const newRxStorageInstance = await settings.storage.createStorageInstance(params);\n state = {\n storageInstance: newRxStorageInstance,\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n /**\n * Automatically subscribe to the streams$\n * because we always need them.\n */\n subs.push(\n state.storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n\n settings.send(message);\n })\n );\n subs.push(\n state.storageInstance.conflictResultionTasks().subscribe(conflicts => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'conflictResultionTasks',\n method: 'conflictResultionTasks',\n return: conflicts\n };\n settings.send(message);\n })\n );\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (message.method === 'create') {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n result = await (ensureNotFalsy(state).storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":";;;;;;;AAAA;AAKA;AAGA;AAOA;AAmiBO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;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ACjB,MAAM,CAAC,iBAA3EkB,oBAAoB;cAC1BpC,KAAK,GAAG;gBACJM,eAAe,EAAE8B,oBAAoB;gBACrCnC,aAAa,EAAE,IAAIoC,GAAG,EAAE;gBACxBnB,MAAM,EAANA;cACJ,CAAC;cACD1B,kBAAkB,CAAC8C,GAAG,CAACb,QAAQ,EAAEzB,KAAK,CAAC;YAAC;UAC5C,CAAC,YAAQ0B,GAAQ,EAAE;YACfnC,QAAQ,CAACoB,IAAI,CAAC,IAAAgB,uCAAiB,EAAC9B,GAAG,EAAE6B,GAAG,CAAC,CAAC;YAAC;UAE/C,CAAC;UAAA;QAAA;UAAA,IAGG,CAAC,IAAAa,yBAAS,EAACrB,MAAM,CAACY,MAAM,EAAE9B,KAAK,CAACkB,MAAM,CAACY,MAAM,CAAC;YAC9CvC,QAAQ,CAACoB,IAAI,CAAC,IAAAgB,uCAAiB,EAAC9B,GAAG,EAAE,IAAI2C,KAAK,CAAC,sDAAsD,CAAC,CAAC,CAAC;UAAC;QAAA;MAAA;MAAA;IAoFrH,CAAC;MAAA;IAAA;EAAA,EAAC;EAEF,OAAO;IACHhD,kBAAkB,EAAlBA;EACJ,CAAC;AACL"} \ No newline at end of file +{"version":3,"file":"remote.js","names":["exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","filter","msg","method","subscribe","connectionId","Array","isArray","params","fullName","databaseName","collectionName","schema","version","join","state","get","storage","createStorageInstance","newRxStorageInstance","storageInstance","connectionIds","Set","set","send","createErrorAnswer","deepEqual","Error","add","subs","push","changeStream","changes","message","answerTo","conflictResultionTasks","conflicts","subMsg","plainMessage","ensureNotFalsy","size","createAnswer","forEach","sub","unsubscribe","result"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types';\nimport {\n ensureNotFalsy\n} from '../../plugins/utils';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeType\n} from './storage-remote-types';\nimport deepEqual from 'fast-deep-equal';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstance: RxStorageInstance;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n const connectionId = msg.connectionId;\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n const newRxStorageInstance = await settings.storage.createStorageInstance(params);\n state = {\n storageInstance: newRxStorageInstance,\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n /**\n * Automatically subscribe to the streams$\n * because we always need them.\n */\n subs.push(\n state.storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n\n settings.send(message);\n })\n );\n subs.push(\n state.storageInstance.conflictResultionTasks().subscribe(conflicts => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'conflictResultionTasks',\n method: 'conflictResultionTasks',\n return: conflicts\n };\n settings.send(message);\n })\n );\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (message.method === 'create') {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n result = await (ensureNotFalsy(state).storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":";;;;;;;;;AAAA;AAKA;AAGA;AAOA;AAEA;AACA;AACA;AACA;AACO,SAASA,qBAAqB,CAACC,QAAuC,EAA6B;EAMtG,IAAMC,kBAA8C,GAAG,IAAIC,GAAG,EAAE;EAGhEF,QAAQ,CAACG,SAAS,CAACC,IAAI,CACnB,IAAAC,YAAM,EAAC,UAAAC,GAAG;IAAA,OAAIA,GAAG,CAACC,MAAM,KAAK,QAAQ;EAAA,EAAC,CACzC,CAACC,SAAS;IAAA,yFAAC,kBAAOF,GAAG;MAAA;MAAA;QAAA;UAAA;YACZG,YAAY,GAAGH,GAAG,CAACG,YAAY;YACrC;AACR;AACA;AACA;AACA;YAJQ,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AC,IAAAiB,kCAAY,EAACvC,GAAG,EAAE,IAAI,CAAC,CAAC;UAAC;UAAA;YAAA;QAAA;MAAA;IAAA,CAC1C;IAAA;MAAA;IAAA;EAAA,IAAC;EAEF,OAAO;IACHL,kBAAkB,EAAlBA;EACJ,CAAC;AACL"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-remote/rx-storage-remote.js b/dist/lib/plugins/storage-remote/rx-storage-remote.js index 2f6892b622c..706f83bd3fb 100644 --- a/dist/lib/plugins/storage-remote/rx-storage-remote.js +++ b/dist/lib/plugins/storage-remote/rx-storage-remote.js @@ -1,17 +1,20 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RxStorageRemote = exports.RxStorageInstanceRemote = void 0; exports.getRxStorageRemote = getRxStorageRemote; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _eventReduceJs = require("event-reduce-js"); var _rxjs = require("rxjs"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var RxStorageRemote = /*#__PURE__*/function () { function RxStorageRemote(settings) { this.name = 'remote'; - this.requestIdSeed = (0, _util.randomCouchString)(10); + this.requestIdSeed = (0, _utils.randomCouchString)(10); this.lastRequestId = 0; this.settings = settings; this.statics = settings.statics; @@ -21,38 +24,53 @@ var RxStorageRemote = /*#__PURE__*/function () { var newId = this.lastRequestId++; return this.requestIdSeed + '|' + newId; }; - _proto.createStorageInstance = function createStorageInstance(params) { - try { - var _this = this; - var requestId = _this.getRequestId(); - var waitForOkPromise = (0, _rxjs.firstValueFrom)(_this.settings.messages$.pipe((0, _rxjs.filter)(function (msg) { - return msg.answerTo === requestId; - }))); - _this.settings.send({ - connectionId: _this.getRequestId(), - method: 'create', - requestId: requestId, - params: params - }); - return Promise.resolve(waitForOkPromise).then(function (waitForOkResult) { - if (waitForOkResult.error) { - throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error)); + _proto.createStorageInstance = /*#__PURE__*/function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var requestId, waitForOkPromise, waitForOkResult; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + requestId = this.getRequestId(); + waitForOkPromise = (0, _rxjs.firstValueFrom)(this.settings.messages$.pipe((0, _rxjs.filter)(function (msg) { + return msg.answerTo === requestId; + }))); + this.settings.send({ + connectionId: this.getRequestId(), + method: 'create', + requestId: requestId, + params: params + }); + _context.next = 5; + return waitForOkPromise; + case 5: + waitForOkResult = _context.sent; + if (!waitForOkResult.error) { + _context.next = 8; + break; + } + throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error)); + case 8: + return _context.abrupt("return", new RxStorageInstanceRemote(this, params.databaseName, params.collectionName, params.schema, { + params: params, + connectionId: (0, _eventReduceJs.ensureNotFalsy)(waitForOkResult.connectionId) + }, params.options)); + case 9: + case "end": + return _context.stop(); } - return new RxStorageInstanceRemote(_this, params.databaseName, params.collectionName, params.schema, { - params: params, - connectionId: (0, _eventReduceJs.ensureNotFalsy)(waitForOkResult.connectionId) - }, params.options); - }); - } catch (e) { - return Promise.reject(e); + }, _callee, this); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - }; + return createStorageInstance; + }(); return RxStorageRemote; }(); exports.RxStorageRemote = RxStorageRemote; var RxStorageInstanceRemote = /*#__PURE__*/function () { function RxStorageInstanceRemote(storage, databaseName, collectionName, schema, internals, options) { - var _this2 = this; + var _this = this; this.changes$ = new _rxjs.Subject(); this.conflicts$ = new _rxjs.Subject(); this.subs = []; @@ -64,43 +82,57 @@ var RxStorageInstanceRemote = /*#__PURE__*/function () { this.internals = internals; this.options = options; this.messages$ = this.storage.settings.messages$.pipe((0, _rxjs.filter)(function (msg) { - return msg.connectionId === _this2.internals.connectionId; + return msg.connectionId === _this.internals.connectionId; })); this.subs.push(this.messages$.subscribe(function (msg) { if (msg.method === 'changeStream') { - _this2.changes$.next(msg["return"]); + _this.changes$.next(msg["return"]); } if (msg.method === 'conflictResultionTasks') { - _this2.conflicts$.next(msg["return"]); + _this.conflicts$.next(msg["return"]); } })); } var _proto2 = RxStorageInstanceRemote.prototype; - _proto2.requestRemote = function requestRemote(methodName, params) { - try { - var _this3 = this; - var requestId = _this3.storage.getRequestId(); - var responsePromise = (0, _rxjs.firstValueFrom)(_this3.messages$.pipe((0, _rxjs.filter)(function (msg) { - return msg.answerTo === requestId; - }))); - var message = { - connectionId: _this3.internals.connectionId, - requestId: requestId, - method: methodName, - params: params - }; - _this3.storage.settings.send(message); - return Promise.resolve(responsePromise).then(function (response) { - if (response.error) { - throw new Error('could not requestRemote: ' + JSON.stringify(response.error)); - } else { - return response["return"]; + _proto2.requestRemote = /*#__PURE__*/function () { + var _requestRemote = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(methodName, params) { + var requestId, responsePromise, message, response; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + requestId = this.storage.getRequestId(); + responsePromise = (0, _rxjs.firstValueFrom)(this.messages$.pipe((0, _rxjs.filter)(function (msg) { + return msg.answerTo === requestId; + }))); + message = { + connectionId: this.internals.connectionId, + requestId: requestId, + method: methodName, + params: params + }; + this.storage.settings.send(message); + _context2.next = 6; + return responsePromise; + case 6: + response = _context2.sent; + if (!response.error) { + _context2.next = 11; + break; + } + throw new Error('could not requestRemote: ' + JSON.stringify(response.error)); + case 11: + return _context2.abrupt("return", response["return"]); + case 12: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); + }, _callee2, this); + })); + function requestRemote(_x2, _x3) { + return _requestRemote.apply(this, arguments); } - }; + return requestRemote; + }(); _proto2.bulkWrite = function bulkWrite(documentWrites, context) { return this.requestRemote('bulkWrite', [documentWrites, context]); }; @@ -125,42 +157,75 @@ var RxStorageInstanceRemote = /*#__PURE__*/function () { _proto2.cleanup = function cleanup(minDeletedTime) { return this.requestRemote('cleanup', [minDeletedTime]); }; - _proto2.close = function close() { - try { - var _this4 = this; - if (_this4.closed) { - return Promise.reject(new Error('already closed')); - } - _this4.closed = true; - _this4.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - _this4.changes$.complete(); - return Promise.resolve(_this4.requestRemote('close', [])).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto2.close = /*#__PURE__*/function () { + var _close = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!this.closed) { + _context3.next = 2; + break; + } + return _context3.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + this.changes$.complete(); + _context3.next = 7; + return this.requestRemote('close', []); + case 7: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function close() { + return _close.apply(this, arguments); } - }; - _proto2.remove = function remove() { - try { - var _this5 = this; - _this5.closed = true; - return Promise.resolve(_this5.requestRemote('remove', [])).then(function () {}); - } catch (e) { - return Promise.reject(e); + return close; + }(); + _proto2.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + this.closed = true; + _context4.next = 3; + return this.requestRemote('remove', []); + case 3: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _proto2.conflictResultionTasks = function conflictResultionTasks() { return this.conflicts$; }; - _proto2.resolveConflictResultionTask = function resolveConflictResultionTask(taskSolution) { - try { - var _this6 = this; - return Promise.resolve(_this6.requestRemote('resolveConflictResultionTask', [taskSolution])).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto2.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(taskSolution) { + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return this.requestRemote('resolveConflictResultionTask', [taskSolution]); + case 2: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function resolveConflictResultionTask(_x4) { + return _resolveConflictResultionTask.apply(this, arguments); } - }; + return resolveConflictResultionTask; + }(); return RxStorageInstanceRemote; }(); exports.RxStorageInstanceRemote = RxStorageInstanceRemote; diff --git a/dist/lib/plugins/storage-remote/rx-storage-remote.js.map b/dist/lib/plugins/storage-remote/rx-storage-remote.js.map index e9b44f38977..37846a03df8 100644 --- a/dist/lib/plugins/storage-remote/rx-storage-remote.js.map +++ b/dist/lib/plugins/storage-remote/rx-storage-remote.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-remote.js","names":["RxStorageRemote","settings","name","requestIdSeed","randomCouchString","lastRequestId","statics","getRequestId","newId","createStorageInstance","params","requestId","waitForOkPromise","firstValueFrom","messages$","pipe","filter","msg","answerTo","send","connectionId","method","waitForOkResult","error","Error","JSON","stringify","RxStorageInstanceRemote","databaseName","collectionName","schema","ensureNotFalsy","options","storage","internals","changes$","Subject","conflicts$","subs","closed","push","subscribe","next","requestRemote","methodName","responsePromise","message","response","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","close","Promise","reject","forEach","sub","unsubscribe","complete","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution","getRxStorageRemote"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import { ensureNotFalsy } from 'event-reduce-js';\nimport {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n RxStorageStatics\n} from '../../types';\nimport {\n randomCouchString\n} from '../../util';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types';\n\n\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly statics: RxStorageStatics;\n public readonly name: string = 'remote';\n private requestIdSeed: string = randomCouchString(10);\n private lastRequestId: number = 0;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n this.statics = settings.statics;\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.requestIdSeed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(this.settings.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n this.settings.send({\n connectionId: this.getRequestId(),\n method: 'create',\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId: ensureNotFalsy(waitForOkResult.connectionId)\n },\n params.options\n );\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.storage.settings.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(msg.return);\n }\n if (msg.method === 'conflictResultionTasks') {\n this.conflicts$.next(msg.return);\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n method: methodName,\n params\n };\n this.storage.settings.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify(response.error));\n } else {\n return response.return;\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n }\n async remove(): Promise {\n this.closed = true;\n await this.requestRemote('remove', []);\n }\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.requestRemote('resolveConflictResultionTask', [taskSolution]);\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n return new RxStorageRemote(settings);\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAwBA;AAEoB,IAWPA,eAAe;EAKxB,yBACoBC,QAAiC,EACnD;IAAA,KALcC,IAAI,GAAW,QAAQ;IAAA,KAC/BC,aAAa,GAAW,IAAAC,uBAAiB,EAAC,EAAE,CAAC;IAAA,KAC7CC,aAAa,GAAW,CAAC;IAAA,KAEbJ,QAAiC,GAAjCA,QAAiC;IAEjD,IAAI,CAACK,OAAO,GAAGL,QAAQ,CAACK,OAAO;EACnC;EAAC;EAAA,OAEMC,YAAY,GAAnB,wBAAsB;IAClB,IAAMC,KAAK,GAAG,IAAI,CAACH,aAAa,EAAE;IAClC,OAAO,IAAI,CAACF,aAAa,GAAG,GAAG,GAAGK,KAAK;EAC3C,CAAC;EAAA,OAEKC,qBAAqB,kCACvBC,MAAuD;IAAA,IACZ;MAAA,YAEzB,IAAI;MAAtB,IAAMC,SAAS,GAAG,MAAKJ,YAAY,EAAE;MACrC,IAAMK,gBAAgB,GAAG,IAAAC,oBAAc,EAAC,MAAKZ,QAAQ,CAACa,SAAS,CAACC,IAAI,CAChE,IAAAC,YAAM,EAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACC,QAAQ,KAAKP,SAAS;MAAA,EAAC,CAC5C,CAAC;MACF,MAAKV,QAAQ,CAACkB,IAAI,CAAC;QACfC,YAAY,EAAE,MAAKb,YAAY,EAAE;QACjCc,MAAM,EAAE,QAAQ;QAChBV,SAAS,EAATA,SAAS;QACTD,MAAM,EAANA;MACJ,CAAC,CAAC;MAAC,uBAE2BE,gBA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MAClB,OAAKD,IAAI,CAACgC,OAAO,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACC,WAAW,EAAE;MAAA,EAAC;MAC3C,OAAKrC,QAAQ,CAACsC,QAAQ,EAAE;MAAC,uBACnB,OAAK9B,aAAa,CAAC,OAAO,EAAE,EAAE,CAAC;IACzC,CAAC;MAAA;IAAA;EAAA;EAAA,QACK+B,MAAM;IAAA,IAAkB;MAAA,aAC1B,IAAI;MAAJ,OAAKnC,MAAM,GAAG,IAAI;MAAC,uBACb,OAAKI,aAAa,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC1C,CAAC;MAAA;IAAA;EAAA;EAAA,QACDgC,sBAAsB,GAAtB,kCAAyE;IACrE,OAAO,IAAI,CAACtC,UAAU;EAC1B,CAAC;EAAA,QACKuC,4BAA4B,yCAACC,YAAwD;IAAA,IAAiB;MAAA,aAClG,IAAI;MAAA,uBAAJ,OAAKlC,aAAa,CAAC,8BAA8B,EAAE,CAACkC,YAAY,CAAC,CAAC;IAC5E,CAAC;MAAA;IAAA;EAAA;EAAA;AAAA;AAAA;AAGE,SAASC,kBAAkB,CAAC7E,QAAiC,EAAmB;EACnF,OAAO,IAAID,eAAe,CAACC,QAAQ,CAAC;AACxC"} \ No newline at end of file +{"version":3,"file":"rx-storage-remote.js","names":["RxStorageRemote","settings","name","requestIdSeed","randomCouchString","lastRequestId","statics","getRequestId","newId","createStorageInstance","params","requestId","waitForOkPromise","firstValueFrom","messages$","pipe","filter","msg","answerTo","send","connectionId","method","waitForOkResult","error","Error","JSON","stringify","RxStorageInstanceRemote","databaseName","collectionName","schema","ensureNotFalsy","options","storage","internals","changes$","Subject","conflicts$","subs","closed","push","subscribe","next","requestRemote","methodName","responsePromise","message","response","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","close","Promise","reject","forEach","sub","unsubscribe","complete","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution","getRxStorageRemote"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import { ensureNotFalsy } from 'event-reduce-js';\nimport {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n RxStorageStatics\n} from '../../types';\nimport {\n randomCouchString\n} from '../../plugins/utils';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types';\n\n\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly statics: RxStorageStatics;\n public readonly name: string = 'remote';\n private requestIdSeed: string = randomCouchString(10);\n private lastRequestId: number = 0;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n this.statics = settings.statics;\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.requestIdSeed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(this.settings.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n this.settings.send({\n connectionId: this.getRequestId(),\n method: 'create',\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId: ensureNotFalsy(waitForOkResult.connectionId)\n },\n params.options\n );\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.storage.settings.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(msg.return);\n }\n if (msg.method === 'conflictResultionTasks') {\n this.conflicts$.next(msg.return);\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n method: methodName,\n params\n };\n this.storage.settings.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify(response.error));\n } else {\n return response.return;\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n }\n async remove(): Promise {\n this.closed = true;\n await this.requestRemote('remove', []);\n }\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.requestRemote('resolveConflictResultionTask', [taskSolution]);\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n return new RxStorageRemote(settings);\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AAwBA;AAE6B,IAWhBA,eAAe;EAKxB,yBACoBC,QAAiC,EACnD;IAAA,KALcC,IAAI,GAAW,QAAQ;IAAA,KAC/BC,aAAa,GAAW,IAAAC,wBAAiB,EAAC,EAAE,CAAC;IAAA,KAC7CC,aAAa,GAAW,CAAC;IAAA,KAEbJ,QAAiC,GAAjCA,QAAiC;IAEjD,IAAI,CAACK,OAAO,GAAGL,QAAQ,CAACK,OAAO;EACnC;EAAC;EAAA,OAEMC,YAAY,GAAnB,wBAAsB;IAClB,IAAMC,KAAK,GAAG,IAAI,CAACH,aAAa,EAAE;IAClC,OAAO,IAAI,CAACF,aAAa,GAAG,GAAG,GAAGK,KAAK;EAC3C,CAAC;EAAA,OAEKC,qBAAqB;IAAA,2GAA3B,iBACIC,MAAuD;MAAA;MAAA;QAAA;UAAA;YAGjDC,SAAS,GAAG,IAAI,CAACJ,YAAY,EAAE;YAC/BK,gBAAgB,GAAG,IAAAC,oBAAc,EAAC,IAAI,CAACZ,QAAQ,CAACa,SAAS,CAACC,IAAI,CAChE,IAAAC,YAAM,EAAC,UAAAC,GAAG;cAAA,OAAIA,GAAG,CAACC,QAAQ,KAAKP,SAAS;YAAA,EAAC,CAC5C,CAAC;YACF,IAAI,CAACV,QAAQ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OAAO,IAAID,eAAe,CAACC,QAAQ,CAAC;AACxC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-remote/storage-remote-helpers.js b/dist/lib/plugins/storage-remote/storage-remote-helpers.js index f55a9e92149..ffbdfccae41 100644 --- a/dist/lib/plugins/storage-remote/storage-remote-helpers.js +++ b/dist/lib/plugins/storage-remote/storage-remote-helpers.js @@ -5,13 +5,13 @@ Object.defineProperty(exports, "__esModule", { }); exports.createAnswer = createAnswer; exports.createErrorAnswer = createErrorAnswer; -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); function createErrorAnswer(msg, error) { return { connectionId: msg.connectionId, answerTo: msg.requestId, method: msg.method, - error: (0, _util.errorToPlainJson)(error) + error: (0, _utils.errorToPlainJson)(error) }; } function createAnswer(msg, ret) { diff --git a/dist/lib/plugins/storage-remote/storage-remote-helpers.js.map b/dist/lib/plugins/storage-remote/storage-remote-helpers.js.map index 6df259dab19..2e1ec95561c 100644 --- a/dist/lib/plugins/storage-remote/storage-remote-helpers.js.map +++ b/dist/lib/plugins/storage-remote/storage-remote-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"storage-remote-helpers.js","names":["createErrorAnswer","msg","error","connectionId","answerTo","requestId","method","errorToPlainJson","createAnswer","ret"],"sources":["../../../../src/plugins/storage-remote/storage-remote-helpers.ts"],"sourcesContent":["import type {\n RxError,\n RxTypeError\n} from '../../types';\nimport { errorToPlainJson } from '../../util';\nimport type {\n MessageFromRemote,\n MessageToRemote\n} from './storage-remote-types';\n\nexport function createErrorAnswer(\n msg: MessageToRemote,\n error: Error | TypeError | RxError | RxTypeError\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n error: errorToPlainJson(error)\n };\n}\n\nexport function createAnswer(\n msg: MessageToRemote,\n ret: any\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n return: ret\n };\n}\n"],"mappings":";;;;;;;AAIA;AAMO,SAASA,iBAAiB,CAC7BC,GAAoB,EACpBC,KAAgD,EAC/B;EACjB,OAAO;IACHC,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClBJ,KAAK,EAAE,IAAAK,sBAAgB,EAACL,KAAK;EACjC,CAAC;AACL;AAEO,SAASM,YAAY,CACxBP,GAAoB,EACpBQ,GAAQ,EACS;EACjB,OAAO;IACHN,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClB,UAAQG;EACZ,CAAC;AACL"} \ No newline at end of file +{"version":3,"file":"storage-remote-helpers.js","names":["createErrorAnswer","msg","error","connectionId","answerTo","requestId","method","errorToPlainJson","createAnswer","ret"],"sources":["../../../../src/plugins/storage-remote/storage-remote-helpers.ts"],"sourcesContent":["import type {\n RxError,\n RxTypeError\n} from '../../types';\nimport { errorToPlainJson } from '../../plugins/utils';\nimport type {\n MessageFromRemote,\n MessageToRemote\n} from './storage-remote-types';\n\nexport function createErrorAnswer(\n msg: MessageToRemote,\n error: Error | TypeError | RxError | RxTypeError\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n error: errorToPlainJson(error)\n };\n}\n\nexport function createAnswer(\n msg: MessageToRemote,\n ret: any\n): MessageFromRemote {\n return {\n connectionId: msg.connectionId,\n answerTo: msg.requestId,\n method: msg.method,\n return: ret\n };\n}\n"],"mappings":";;;;;;;AAIA;AAMO,SAASA,iBAAiB,CAC7BC,GAAoB,EACpBC,KAAgD,EAC/B;EACjB,OAAO;IACHC,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClBJ,KAAK,EAAE,IAAAK,uBAAgB,EAACL,KAAK;EACjC,CAAC;AACL;AAEO,SAASM,YAAY,CACxBP,GAAoB,EACpBQ,GAAQ,EACS;EACjB,OAAO;IACHN,YAAY,EAAEF,GAAG,CAACE,YAAY;IAC9BC,QAAQ,EAAEH,GAAG,CAACI,SAAS;IACvBC,MAAM,EAAEL,GAAG,CAACK,MAAM;IAClB,UAAQG;EACZ,CAAC;AACL"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-remote/websocket.js b/dist/lib/plugins/storage-remote/websocket.js index 95e2f1963fb..16db69fc3e5 100644 --- a/dist/lib/plugins/storage-remote/websocket.js +++ b/dist/lib/plugins/storage-remote/websocket.js @@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { exports.getRxStorageRemoteWebsocket = getRxStorageRemoteWebsocket; exports.startRxStorageRemoteWebsocketServer = startRxStorageRemoteWebsocketServer; var _rxjs = require("rxjs"); -var _util = require("../../util"); +var _utils = require("../../plugins/utils"); var _replicationWebsocket = require("../replication-websocket"); var _remote = require("./remote"); var _rxStorageRemote = require("./rx-storage-remote"); @@ -19,7 +19,7 @@ function startRxStorageRemoteWebsocketServer(options) { messages$: messages$.asObservable(), storage: options.storage, send: function send(msg) { - var ws = (0, _util.getFromMapOrThrow)(websocketByConnectionId, msg.connectionId); + var ws = (0, _utils.getFromMapOrThrow)(websocketByConnectionId, msg.connectionId); ws.send(JSON.stringify(msg)); } }; @@ -64,7 +64,7 @@ var WebsocketClientByUrl = new Map(); function getRxStorageRemoteWebsocket(options) { var identifier = options.url + 'rx-remote-storage-websocket'; var messages$ = new _rxjs.Subject(); - var websocketClientPromise = WebsocketClientByUrl.has(options.url) ? (0, _util.getFromMapOrThrow)(WebsocketClientByUrl, options.url) : (0, _replicationWebsocket.getWebSocket)(options.url, identifier); + var websocketClientPromise = WebsocketClientByUrl.has(options.url) ? (0, _utils.getFromMapOrThrow)(WebsocketClientByUrl, options.url) : (0, _replicationWebsocket.getWebSocket)(options.url, identifier); WebsocketClientByUrl.set(options.url, websocketClientPromise); var storage = (0, _rxStorageRemote.getRxStorageRemote)({ identifier: identifier, diff --git a/dist/lib/plugins/storage-remote/websocket.js.map b/dist/lib/plugins/storage-remote/websocket.js.map index 2faf450c6db..187d717b99a 100644 --- a/dist/lib/plugins/storage-remote/websocket.js.map +++ b/dist/lib/plugins/storage-remote/websocket.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket.js","names":["startRxStorageRemoteWebsocketServer","options","serverState","startSocketServer","websocketByConnectionId","Map","messages$","Subject","exposeSettings","asObservable","storage","send","msg","ws","getFromMapOrThrow","connectionId","JSON","stringify","exposeState","exposeRxStorageRemote","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","createErrorAnswer","Error","set","next","WebsocketClientByUrl","getRxStorageRemoteWebsocket","identifier","url","websocketClientPromise","getWebSocket","getRxStorageRemote","statics","then","websocketClient","socket","message$"],"sources":["../../../../src/plugins/storage-remote/websocket.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport type {\n RxStorage\n} from '../../types';\nimport {\n getFromMapOrThrow\n} from '../../util';\nimport {\n getWebSocket,\n startSocketServer,\n WebsocketWithRefCount\n} from '../replication-websocket';\nimport { exposeRxStorageRemote } from './remote';\nimport { getRxStorageRemote } from './rx-storage-remote';\nimport { createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './storage-remote-types';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (message.method !== 'create') {\n ws.send(JSON.stringify(createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))));\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\n\n\n/**\n * Reuse connections to the same url.\n * This makes testing easier because we do not run into a connection limit.\n * It might be better to instead track the amount of open storage instances\n * and open/close the websocket client depending on the counter.\n */\nconst WebsocketClientByUrl = new Map>();\n\nexport function getRxStorageRemoteWebsocket(options: RxStorageRemoteWebsocketClientOptions): RxStorage {\n const identifier = options.url + 'rx-remote-storage-websocket';\n const messages$ = new Subject();\n const websocketClientPromise = WebsocketClientByUrl.has(options.url) ?\n getFromMapOrThrow(WebsocketClientByUrl, options.url) :\n getWebSocket(options.url, identifier);\n WebsocketClientByUrl.set(options.url, websocketClientPromise);\n const storage = getRxStorageRemote({\n identifier,\n statics: options.statics,\n messages$,\n send(msg) {\n return websocketClientPromise\n .then(websocketClient => websocketClient.socket.send(JSON.stringify(msg)));\n }\n });\n websocketClientPromise.then((websocketClient) => {\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n });\n return storage;\n}\n"],"mappings":";;;;;;;AAAA;AAOA;AAGA;AAKA;AACA;AACA;AASO,SAASA,mCAAmC,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAG,IAAAC,uCAAiB,EAACF,OAAO,CAAC;EAG9C,IAAMG,uBAAuB,GAAG,IAAIC,GAAG,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,EAAC;EAClE,CAAC,CAAC;EACF,OAAOF,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"websocket.js","names":["startRxStorageRemoteWebsocketServer","options","serverState","startSocketServer","websocketByConnectionId","Map","messages$","Subject","exposeSettings","asObservable","storage","send","msg","ws","getFromMapOrThrow","connectionId","JSON","stringify","exposeState","exposeRxStorageRemote","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","createErrorAnswer","Error","set","next","WebsocketClientByUrl","getRxStorageRemoteWebsocket","identifier","url","websocketClientPromise","getWebSocket","getRxStorageRemote","statics","then","websocketClient","socket","message$"],"sources":["../../../../src/plugins/storage-remote/websocket.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport type {\n RxStorage\n} from '../../types';\nimport {\n getFromMapOrThrow\n} from '../../plugins/utils';\nimport {\n getWebSocket,\n startSocketServer,\n WebsocketWithRefCount\n} from '../replication-websocket';\nimport { exposeRxStorageRemote } from './remote';\nimport { getRxStorageRemote } from './rx-storage-remote';\nimport { createErrorAnswer } from './storage-remote-helpers';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './storage-remote-types';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (message.method !== 'create') {\n ws.send(JSON.stringify(createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))));\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\n\n\n/**\n * Reuse connections to the same url.\n * This makes testing easier because we do not run into a connection limit.\n * It might be better to instead track the amount of open storage instances\n * and open/close the websocket client depending on the counter.\n */\nconst WebsocketClientByUrl = new Map>();\n\nexport function getRxStorageRemoteWebsocket(options: RxStorageRemoteWebsocketClientOptions): RxStorage {\n const identifier = options.url + 'rx-remote-storage-websocket';\n const messages$ = new Subject();\n const websocketClientPromise = WebsocketClientByUrl.has(options.url) ?\n getFromMapOrThrow(WebsocketClientByUrl, options.url) :\n getWebSocket(options.url, identifier);\n WebsocketClientByUrl.set(options.url, websocketClientPromise);\n const storage = getRxStorageRemote({\n identifier,\n statics: options.statics,\n messages$,\n send(msg) {\n return websocketClientPromise\n .then(websocketClient => websocketClient.socket.send(JSON.stringify(msg)));\n }\n });\n websocketClientPromise.then((websocketClient) => {\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n });\n return storage;\n}\n"],"mappings":";;;;;;;AAAA;AAOA;AAGA;AAKA;AACA;AACA;AASO,SAASA,mCAAmC,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAG,IAAAC,uCAAiB,EAACF,OAAO,CAAC;EAG9C,IAAMG,uBAAuB,GAAG,IAAIC,GAAG,EAAqB;EAC5D,IAAMC,SAAS,GAAG,IAAIC,aAAO,EAAmB;EAChD,IAAMC,cAA6C,GAAG;IAClDF,SAAS,EAAEA,SAAS,CAACG,YAAY,EAAE;IACnCC,OAAO,EAAET,OAAO,CAACS,OAAO;IAC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;AAIA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMkB,oBAAoB,GAAG,IAAI/B,GAAG,EAA0C;AAEvE,SAASgC,2BAA2B,CAACpC,OAA8C,EAAuB;EAC7G,IAAMqC,UAAU,GAAGrC,OAAO,CAACsC,GAAG,GAAG,6BAA6B;EAC9D,IAAMjC,SAAS,GAAG,IAAIC,aAAO,EAAqB;EAClD,IAAMiC,sBAAsB,GAAGJ,oBAAoB,CAACN,GAAG,CAAC7B,OAAO,CAACsC,GAAG,CAAC,GAChE,IAAAzB,wBAAiB,EAACsB,oBAAoB,EAAEnC,OAAO,CAACsC,GAAG,CAAC,GACpD,IAAAE,kCAAY,EAACxC,OAAO,CAACsC,GAAG,EAAED,UAAU,CAAC;EACzCF,oBAAoB,CAACF,GAAG,CAACjC,OAAO,CAACsC,GAAG,EAAEC,sBAAsB,CAAC;EAC7D,IAAM9B,OAAO,GAAG,IAAAgC,mCAAkB,EAAC;IAC/BJ,UAAU,EAAVA,UAAU;IACVK,OAAO,EAAE1C,OAAO,CAAC0C,OAAO;IACxBrC,SAAS,EAATA,SAAS;IACTK,IAAI,gBAACC,GAAG,EAAE;MACN,OAAO4B,sBAAsB,CACxBI,IAAI,CAAC,UAAAC,eAAe;QAAA,OAAIA,eAAe,CAACC,MAAM,CAACnC,IAAI,CAACK,IAAI,CAACC,SAAS,CAACL,GAAG,CAAC,CAAC;MAAA,EAAC;IAClF;EACJ,CAAC,CAAC;EACF4B,sBAAsB,CAACI,IAAI,CAAC,UAACC,eAAe,EAAK;IAC7CA,eAAe,CAACE,QAAQ,CAAC1B,SAAS,CAAC,UAAAT,GAAG;MAAA,OAAIN,SAAS,CAAC6B,IAAI,CAACvB,GAAG,CAAC;IAAA,EAAC;EAClE,CAAC,CAAC;EACF,OAAOF,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/in-worker.js b/dist/lib/plugins/storage-worker/in-worker.js new file mode 100644 index 00000000000..3c035a814e9 --- /dev/null +++ b/dist/lib/plugins/storage-worker/in-worker.js @@ -0,0 +1,99 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.wrappedWorkerRxStorage = wrappedWorkerRxStorage; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _worker = require("threads/worker"); +var _utils = require("../utils"); +/** + * This file contains everything + * that is supposed to run inside of the worker. + */ + +function wrappedWorkerRxStorage(args) { + var nextId = 0; + var instanceById = new Map(); + var exposeMe = { + /** + * RxStorageInstance + */ + createStorageInstance: function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var instanceId, instance; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + instanceId = nextId++; + _context.next = 3; + return args.storage.createStorageInstance(params); + case 3: + instance = _context.sent; + instanceById.set(instanceId, instance); + return _context.abrupt("return", instanceId); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); + } + return createStorageInstance; + }(), + bulkWrite: function bulkWrite(instanceId, documentWrites, context) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.bulkWrite(documentWrites, context); + }, + findDocumentsById: function findDocumentsById(instanceId, ids, deleted) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.findDocumentsById(ids, deleted); + }, + query: function query(instanceId, preparedQuery) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.query(preparedQuery); + }, + count: function count(instanceId, preparedQuery) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.count(preparedQuery); + }, + getAttachmentData: function getAttachmentData(instanceId, documentId, attachmentId) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.getAttachmentData(documentId, attachmentId); + }, + getChangedDocumentsSince: function getChangedDocumentsSince(instanceId, limit, checkpoint) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.getChangedDocumentsSince(limit, checkpoint); + }, + changeStream: function changeStream(instanceId) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.changeStream(); + }, + cleanup: function cleanup(instanceId, minDeletedTime) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.cleanup(minDeletedTime); + }, + close: function close(instanceId) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.close(); + }, + remove: function remove(instanceId) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.remove(); + }, + conflictResultionTasks: function conflictResultionTasks(instanceId) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.conflictResultionTasks(); + }, + resolveConflictResultionTask: function resolveConflictResultionTask(instanceId, taskSolution) { + var instance = (0, _utils.getFromMapOrThrow)(instanceById, instanceId); + return instance.resolveConflictResultionTask(taskSolution); + } + }; + (0, _worker.expose)(exposeMe); +} +//# sourceMappingURL=in-worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/in-worker.js.map b/dist/lib/plugins/storage-worker/in-worker.js.map new file mode 100644 index 00000000000..62757982edc --- /dev/null +++ b/dist/lib/plugins/storage-worker/in-worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"in-worker.js","names":["wrappedWorkerRxStorage","args","nextId","instanceById","Map","exposeMe","createStorageInstance","params","instanceId","storage","instance","set","bulkWrite","documentWrites","context","getFromMapOrThrow","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","cleanup","minDeletedTime","close","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution","expose"],"sources":["../../../../src/plugins/storage-worker/in-worker.ts"],"sourcesContent":["/**\n * This file contains everything\n * that is supposed to run inside of the worker.\n */\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types';\nimport { expose } from 'threads/worker';\nimport { getFromMapOrThrow } from '../utils';\nimport { Observable } from 'rxjs';\n\n\nexport type InWorkerStorage = {\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise;\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise>;\n findDocumentsById(\n instanceId: number,\n ids: string[], deleted: boolean\n ): Promise>;\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise>;\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise;\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise;\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }>;\n changeStream(\n instanceById: number\n ): Observable>, CheckpointType>>;\n cleanup(instanceId: number, minDeletedTime: number): Promise;\n close(instanceId: number): Promise;\n remove(instanceId: number): Promise;\n\n conflictResultionTasks(\n instanceById: number\n ): Observable>;\n resolveConflictResultionTask(\n instanceById: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise;\n};\n\nexport function wrappedWorkerRxStorage(\n args: {\n storage: RxStorage;\n }\n) {\n let nextId = 0;\n const instanceById: Map = new Map();\n\n const exposeMe: InWorkerStorage = {\n /**\n * RxStorageInstance\n */\n async createStorageInstance(params) {\n const instanceId = nextId++;\n const instance = await args.storage.createStorageInstance(params);\n instanceById.set(instanceId, instance);\n return instanceId;\n },\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.bulkWrite(documentWrites, context);\n },\n findDocumentsById(\n instanceId: number,\n ids: string[],\n deleted: boolean\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.findDocumentsById(ids, deleted);\n },\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.query(preparedQuery);\n },\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.count(preparedQuery);\n },\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getAttachmentData(\n documentId,\n attachmentId\n );\n },\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint: any\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getChangedDocumentsSince(\n limit,\n checkpoint\n );\n },\n changeStream(\n instanceId: number\n ): Observable>, CheckpointType>> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.changeStream();\n },\n cleanup(\n instanceId: number,\n minDeletedTime: number\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.cleanup(minDeletedTime);\n },\n close(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.close();\n },\n remove(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.remove();\n },\n\n conflictResultionTasks(\n instanceId: number\n ): Observable> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.conflictResultionTasks();\n },\n resolveConflictResultionTask(\n instanceId: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.resolveConflictResultionTask(taskSolution);\n }\n };\n expose(exposeMe);\n}\n"],"mappings":";;;;;;;;;AAkBA;AACA;AAnBA;AACA;AACA;AACA;;AAsEO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,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACuB,sBAAsB,EAAE;IAC5C,CAAC;IACDC,4BAA4B,wCACxB1B,UAAkB,EAClB2B,YAAwD,EAC3C;MACb,IAAMzB,QAAQ,GAAG,IAAAK,wBAAiB,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACwB,4BAA4B,CAACC,YAAY,CAAC;IAC9D;EACJ,CAAC;EACD,IAAAC,cAAM,EAAC/B,QAAQ,CAAC;AACpB"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/index.js b/dist/lib/plugins/storage-worker/index.js similarity index 100% rename from dist/lib/plugins/worker/index.js rename to dist/lib/plugins/storage-worker/index.js diff --git a/dist/lib/plugins/storage-worker/index.js.map b/dist/lib/plugins/storage-worker/index.js.map new file mode 100644 index 00000000000..0b955fc1982 --- /dev/null +++ b/dist/lib/plugins/storage-worker/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/storage-worker/index.ts"],"sourcesContent":["export * from './in-worker';\nexport * from './non-worker';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/non-worker.js b/dist/lib/plugins/storage-worker/non-worker.js similarity index 52% rename from dist/lib/plugins/worker/non-worker.js rename to dist/lib/plugins/storage-worker/non-worker.js index aa311895391..8a5191c977c 100644 --- a/dist/lib/plugins/worker/non-worker.js +++ b/dist/lib/plugins/storage-worker/non-worker.js @@ -1,39 +1,17 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.RxStorageWorker = exports.RxStorageInstanceWorker = void 0; exports.getRxStorageWorker = getRxStorageWorker; -exports.removeWorkerRef = void 0; +exports.removeWorkerRef = removeWorkerRef; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _threads = require("threads"); -var _util = require("../../util"); -/** - * TODO we have a bug. - * When the exact same RxStorage opens and closes - * many RxStorage instances, then it might happen - * that some calls to createStorageInstance() time out, - * because the worker thread is in the closing state. - */ -var removeWorkerRef = function removeWorkerRef(instance) { - try { - var workerState = (0, _util.getFromMapOrThrow)(WORKER_BY_INSTANCE, instance.storage); - workerState.refs["delete"](instance); - var _temp = function () { - if (workerState.refs.size === 0) { - WORKER_BY_INSTANCE["delete"](instance.storage); - return Promise.resolve(workerState.workerPromise.then(function (worker) { - return _threads.Thread.terminate(worker); - })).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } -}; -exports.removeWorkerRef = removeWorkerRef; +var _utils = require("../../plugins/utils"); /** * We have no way to detect if a worker is no longer needed. * So we create the worker process on the first RxStorageInstance @@ -64,7 +42,7 @@ var RxStorageWorker = /*#__PURE__*/function () { instanceId: instanceId, worker: worker }, params.options); - (0, _util.ensureNotFalsy)(workerState).refs.add(instance); + (0, _utils.ensureNotFalsy)(workerState).refs.add(instance); return instance; }); }); @@ -122,45 +100,80 @@ var RxStorageInstanceWorker = /*#__PURE__*/function () { _proto2.cleanup = function cleanup(minDeletedTime) { return this.internals.worker.cleanup(this.internals.instanceId, minDeletedTime); }; - _proto2.close = function close() { - try { - var _this3 = this; - if (_this3.closed) { - return Promise.reject(new Error('already closed')); - } - _this3.closed = true; - _this3.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - return Promise.resolve(_this3.internals.worker.close(_this3.internals.instanceId)).then(function () { - return Promise.resolve(removeWorkerRef(_this3)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + _proto2.close = /*#__PURE__*/function () { + var _close = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!this.closed) { + _context.next = 2; + break; + } + return _context.abrupt("return", Promise.reject(new Error('already closed'))); + case 2: + this.closed = true; + this.subs.forEach(function (sub) { + return sub.unsubscribe(); + }); + _context.next = 6; + return this.internals.worker.close(this.internals.instanceId); + case 6: + _context.next = 8; + return removeWorkerRef(this); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function close() { + return _close.apply(this, arguments); } - }; - _proto2.remove = function remove() { - try { - var _this4 = this; - return Promise.resolve(_this4.internals.worker.remove(_this4.internals.instanceId)).then(function () { - _this4.closed = true; - return Promise.resolve(removeWorkerRef(_this4)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + return close; + }(); + _proto2.remove = /*#__PURE__*/function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.internals.worker.remove(this.internals.instanceId); + case 2: + this.closed = true; + _context2.next = 5; + return removeWorkerRef(this); + case 5: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); _proto2.conflictResultionTasks = function conflictResultionTasks() { return this.conflicts$; }; - _proto2.resolveConflictResultionTask = function resolveConflictResultionTask(taskSolution) { - try { - var _this5 = this; - return Promise.resolve(_this5.internals.worker.resolveConflictResultionTask(_this5.internals.instanceId, taskSolution)).then(function () {}); - } catch (e) { - return Promise.reject(e); + _proto2.resolveConflictResultionTask = /*#__PURE__*/function () { + var _resolveConflictResultionTask = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(taskSolution) { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.internals.worker.resolveConflictResultionTask(this.internals.instanceId, taskSolution); + case 2: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function resolveConflictResultionTask(_x) { + return _resolveConflictResultionTask.apply(this, arguments); } - }; + return resolveConflictResultionTask; + }(); return RxStorageInstanceWorker; }(); exports.RxStorageInstanceWorker = RxStorageInstanceWorker; @@ -168,4 +181,40 @@ function getRxStorageWorker(settings) { var storage = new RxStorageWorker(settings, settings.statics); return storage; } + +/** + * TODO we have a bug. + * When the exact same RxStorage opens and closes + * many RxStorage instances, then it might happen + * that some calls to createStorageInstance() time out, + * because the worker thread is in the closing state. + */ +function removeWorkerRef(_x2) { + return _removeWorkerRef.apply(this, arguments); +} +function _removeWorkerRef() { + _removeWorkerRef = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(instance) { + var workerState; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + workerState = (0, _utils.getFromMapOrThrow)(WORKER_BY_INSTANCE, instance.storage); + workerState.refs["delete"](instance); + if (!(workerState.refs.size === 0)) { + _context4.next = 6; + break; + } + WORKER_BY_INSTANCE["delete"](instance.storage); + _context4.next = 6; + return workerState.workerPromise.then(function (worker) { + return _threads.Thread.terminate(worker); + }); + case 6: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _removeWorkerRef.apply(this, arguments); +} //# sourceMappingURL=non-worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/non-worker.js.map b/dist/lib/plugins/storage-worker/non-worker.js.map new file mode 100644 index 00000000000..c96cfeaa207 --- /dev/null +++ b/dist/lib/plugins/storage-worker/non-worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"non-worker.js","names":["WORKER_BY_INSTANCE","Map","RxStorageWorker","settings","statics","name","createStorageInstance","params","workerState","get","workerPromise","spawn","Worker","workerInput","refs","Set","set","then","worker","instanceId","instance","RxStorageInstanceWorker","databaseName","collectionName","schema","rxStorage","options","ensureNotFalsy","add","storage","internals","changes$","Subject","conflicts$","subs","closed","push","changeStream","subscribe","ev","next","conflictResultionTasks","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","asObservable","cleanup","minDeletedTime","close","Promise","reject","Error","forEach","sub","unsubscribe","removeWorkerRef","remove","resolveConflictResultionTask","taskSolution","getRxStorageWorker","getFromMapOrThrow","size","Thread","terminate"],"sources":["../../../../src/plugins/storage-worker/non-worker.ts"],"sourcesContent":["import {\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n spawn,\n Worker,\n Thread\n} from 'threads';\nimport type {\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageInstance,\n BulkWriteRow,\n RxDocumentData,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageQueryResult,\n EventBulk,\n RxStorageStatics,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageCountResult\n} from '../../types';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from '../../plugins/utils';\nimport { InWorkerStorage } from './in-worker';\n\ndeclare type WorkerStorageInternals = {\n rxStorage: RxStorageWorker;\n instanceId: number;\n worker: InWorkerStorage;\n};\ndeclare type RxStorageWorkerSettings = {\n statics: RxStorageStatics;\n workerInput: any;\n};\n\n\n/**\n * We have no way to detect if a worker is no longer needed.\n * So we create the worker process on the first RxStorageInstance\n * and have to close it again of no more RxStorageInstances are non-closed.\n */\nconst WORKER_BY_INSTANCE: Map>;\n refs: Set>;\n}> = new Map();\n\nexport class RxStorageWorker implements RxStorage {\n public name = 'worker';\n\n constructor(\n public readonly settings: RxStorageWorkerSettings,\n public readonly statics: RxStorageStatics\n ) { }\n\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n let workerState = WORKER_BY_INSTANCE.get(this);\n if (!workerState) {\n workerState = {\n workerPromise: spawn>(new Worker(this.settings.workerInput)) as any,\n refs: new Set()\n };\n WORKER_BY_INSTANCE.set(this, workerState);\n }\n\n return workerState.workerPromise.then(worker => {\n return worker.createStorageInstance(params)\n .then(instanceId => {\n const instance = new RxStorageInstanceWorker(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n rxStorage: this,\n instanceId,\n worker\n },\n params.options\n );\n ensureNotFalsy(workerState).refs.add(instance);\n return instance;\n });\n });\n }\n}\n\n\nexport class RxStorageInstanceWorker implements RxStorageInstance {\n /**\n * threads.js uses observable-fns instead of rxjs\n * so we have to transform it.\n */\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n\n constructor(\n public readonly storage: RxStorageWorker,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: WorkerStorageInternals,\n public readonly options: Readonly\n ) {\n this.subs.push(\n this.internals.worker.changeStream(\n this.internals.instanceId\n ).subscribe(ev => this.changes$.next(ev as any))\n );\n this.subs.push(\n this.internals.worker.conflictResultionTasks(\n this.internals.instanceId\n ).subscribe(ev => this.conflicts$.next(ev as any))\n );\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.internals.worker.bulkWrite(\n this.internals.instanceId,\n documentWrites,\n context\n );\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.internals.worker.findDocumentsById(\n this.internals.instanceId,\n ids,\n deleted\n );\n }\n query(preparedQuery: any): Promise> {\n return this.internals.worker.query(\n this.internals.instanceId,\n preparedQuery\n );\n }\n count(preparedQuery: any): Promise {\n return this.internals.worker.count(\n this.internals.instanceId,\n preparedQuery\n );\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.internals.worker.getAttachmentData(\n this.internals.instanceId,\n documentId,\n attachmentId\n );\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ) {\n return this.internals.worker.getChangedDocumentsSince(\n this.internals.instanceId,\n limit,\n checkpoint\n );\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number) {\n return this.internals.worker.cleanup(\n this.internals.instanceId,\n minDeletedTime\n );\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n await this.internals.worker.close(\n this.internals.instanceId\n );\n await removeWorkerRef(this);\n }\n async remove(): Promise {\n await this.internals.worker.remove(\n this.internals.instanceId\n );\n this.closed = true;\n await removeWorkerRef(this);\n }\n\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.internals.worker.resolveConflictResultionTask(\n this.internals.instanceId,\n taskSolution\n );\n }\n\n}\n\nexport function getRxStorageWorker(\n settings: RxStorageWorkerSettings\n): RxStorageWorker {\n const storage = new RxStorageWorker(settings, settings.statics);\n return storage;\n}\n\n/**\n * TODO we have a bug.\n * When the exact same RxStorage opens and closes\n * many RxStorage instances, then it might happen\n * that some calls to createStorageInstance() time out,\n * because the worker thread is in the closing state.\n */\nexport async function removeWorkerRef(\n instance: RxStorageInstanceWorker\n) {\n const workerState = getFromMapOrThrow(WORKER_BY_INSTANCE, instance.storage);\n workerState.refs.delete(instance);\n if (workerState.refs.size === 0) {\n WORKER_BY_INSTANCE.delete(instance.storage);\n await workerState.workerPromise\n .then(worker => Thread.terminate(worker as any));\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAKA;AAsBA;AAiBA;AACA;AACA;AACA;AACA;AACA,IAAMA,kBAGJ,GAAG,IAAIC,GAAG,EAAE;AAAC,IAEFC,eAAe;EAGxB,yBACoBC,QAAiC,EACjCC,OAAyB,EAC3C;IAAA,KALKC,IAAI,GAAG,QAAQ;IAAA,KAGFF,QAAiC,GAAjCA,QAAiC;IAAA,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AAA;EAAA,iGAA9B,kBACH/C,QAAsC;IAAA;IAAA;MAAA;QAAA;UAEhCZ,WAAW,GAAG,IAAAgE,wBAAiB,EAACxE,kBAAkB,EAAEoB,QAAQ,CAACS,OAAO,CAAC;UAC3ErB,WAAW,CAACM,IAAI,UAAO,CAACM,QAAQ,CAAC;UAAC,MAC9BZ,WAAW,CAACM,IAAI,CAAC2D,IAAI,KAAK,CAAC;YAAA;YAAA;UAAA;UAC3BzE,kBAAkB,UAAO,CAACoB,QAAQ,CAACS,OAAO,CAAC;UAAC;UAAA,OACtCrB,WAAW,CAACE,aAAa,CAC1BO,IAAI,CAAC,UAAAC,MAAM;YAAA,OAAIwD,eAAM,CAACC,SAAS,CAACzD,MAAM,CAAQ;UAAA,EAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAE3D;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/dexie-memory.worker.js b/dist/lib/plugins/storage-worker/workers/dexie-memory.worker.js similarity index 51% rename from dist/lib/plugins/worker/workers/dexie-memory.worker.js rename to dist/lib/plugins/storage-worker/workers/dexie-memory.worker.js index 770794f5810..a0e15d48495 100644 --- a/dist/lib/plugins/worker/workers/dexie-memory.worker.js +++ b/dist/lib/plugins/storage-worker/workers/dexie-memory.worker.js @@ -1,13 +1,13 @@ "use strict"; -var _dexie = require("../../dexie"); -var _worker = require("../../worker"); +var _storageDexie = require("../../storage-dexie"); +var _storageWorker = require("../../storage-worker"); var _fakeIndexeddb = require("fake-indexeddb"); -var storage = (0, _dexie.getRxStorageDexie)({ +var storage = (0, _storageDexie.getRxStorageDexie)({ indexedDB: _fakeIndexeddb.indexedDB, IDBKeyRange: _fakeIndexeddb.IDBKeyRange }); -(0, _worker.wrappedWorkerRxStorage)({ +(0, _storageWorker.wrappedWorkerRxStorage)({ storage: storage }); //# sourceMappingURL=dexie-memory.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/dexie-memory.worker.js.map b/dist/lib/plugins/storage-worker/workers/dexie-memory.worker.js.map new file mode 100644 index 00000000000..f4abbfbcc92 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/dexie-memory.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-memory.worker.js","names":["storage","getRxStorageDexie","indexedDB","IDBKeyRange","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/storage-worker/workers/dexie-memory.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../storage-dexie';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nimport {\n indexedDB,\n IDBKeyRange\n} from 'fake-indexeddb';\n\nconst storage = getRxStorageDexie({\n indexedDB,\n IDBKeyRange\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA;AAKA,IAAMA,OAAO,GAAG,IAAAC,+BAAiB,EAAC;EAC9BC,SAAS,EAATA,wBAAS;EACTC,WAAW,EAAXA;AACJ,CAAC,CAAC;AACF,IAAAC,qCAAsB,EAAC;EACnBJ,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/dexie.worker.js b/dist/lib/plugins/storage-worker/workers/dexie.worker.js new file mode 100644 index 00000000000..968bb16f9c4 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/dexie.worker.js @@ -0,0 +1,9 @@ +"use strict"; + +var _storageDexie = require("../../storage-dexie"); +var _storageWorker = require("../../storage-worker"); +var storage = (0, _storageDexie.getRxStorageDexie)(); +(0, _storageWorker.wrappedWorkerRxStorage)({ + storage: storage +}); +//# sourceMappingURL=dexie.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/dexie.worker.js.map b/dist/lib/plugins/storage-worker/workers/dexie.worker.js.map new file mode 100644 index 00000000000..46741a193f6 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/dexie.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.worker.js","names":["storage","getRxStorageDexie","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/storage-worker/workers/dexie.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../storage-dexie';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nconst storage = getRxStorageDexie();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAMA,OAAO,GAAG,IAAAC,+BAAiB,GAAE;AACnC,IAAAC,qCAAsB,EAAC;EACnBF,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-fs.worker.js b/dist/lib/plugins/storage-worker/workers/lokijs-fs.worker.js new file mode 100644 index 00000000000..5b6f67e98f2 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-fs.worker.js @@ -0,0 +1,13 @@ +"use strict"; + +var _storageLokijs = require("../../storage-lokijs"); +var _storageWorker = require("../../storage-worker"); +var lfsa = require('lokijs/src/loki-fs-structured-adapter.js'); +var adapter = new lfsa(); +var storage = (0, _storageLokijs.getRxStorageLoki)({ + adapter: adapter +}); +(0, _storageWorker.wrappedWorkerRxStorage)({ + storage: storage +}); +//# sourceMappingURL=lokijs-fs.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-fs.worker.js.map b/dist/lib/plugins/storage-worker/workers/lokijs-fs.worker.js.map new file mode 100644 index 00000000000..e49b2a33188 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-fs.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-fs.worker.js","names":["lfsa","require","adapter","storage","getRxStorageLoki","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-fs.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nconst lfsa = require('lokijs/src/loki-fs-structured-adapter.js');\nconst adapter = new lfsa();\nconst storage = getRxStorageLoki({\n adapter\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAMA,IAAI,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAChE,IAAMC,OAAO,GAAG,IAAIF,IAAI,EAAE;AAC1B,IAAMG,OAAO,GAAG,IAAAC,+BAAgB,EAAC;EAC7BF,OAAO,EAAPA;AACJ,CAAC,CAAC;AACF,IAAAG,qCAAsB,EAAC;EACnBF,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js b/dist/lib/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js similarity index 54% rename from dist/lib/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js rename to dist/lib/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js index 72572e37143..c37f812f302 100644 --- a/dist/lib/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js +++ b/dist/lib/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js @@ -1,12 +1,12 @@ "use strict"; -var _lokijs = require("../../lokijs"); -var _worker = require("../../worker"); +var _storageLokijs = require("../../storage-lokijs"); +var _storageWorker = require("../../storage-worker"); var LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter'); -var storage = (0, _lokijs.getRxStorageLoki)({ +var storage = (0, _storageLokijs.getRxStorageLoki)({ adapter: new LokiIncrementalIndexedDBAdapter() }); -(0, _worker.wrappedWorkerRxStorage)({ +(0, _storageWorker.wrappedWorkerRxStorage)({ storage: storage }); //# sourceMappingURL=lokijs-incremental-indexeddb.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js.map b/dist/lib/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js.map new file mode 100644 index 00000000000..34ac0cda6c2 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-incremental-indexeddb.worker.js","names":["LokiIncrementalIndexedDBAdapter","require","storage","getRxStorageLoki","adapter","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\nconst LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIncrementalIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AACA,IAAMA,+BAA+B,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAE3F,IAAMC,OAAO,GAAG,IAAAC,+BAAgB,EAAC;EAC7BC,OAAO,EAAE,IAAIJ,+BAA+B;AAChD,CAAC,CAAC;AACF,IAAAK,qCAAsB,EAAC;EACnBH,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-indexeddb.worker.js b/dist/lib/plugins/storage-worker/workers/lokijs-indexeddb.worker.js new file mode 100644 index 00000000000..42a0896236e --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-indexeddb.worker.js @@ -0,0 +1,12 @@ +"use strict"; + +var _storageLokijs = require("../../storage-lokijs"); +var _storageWorker = require("../../storage-worker"); +var LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter'); +var storage = (0, _storageLokijs.getRxStorageLoki)({ + adapter: new LokiIndexedDBAdapter() +}); +(0, _storageWorker.wrappedWorkerRxStorage)({ + storage: storage +}); +//# sourceMappingURL=lokijs-indexeddb.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-indexeddb.worker.js.map b/dist/lib/plugins/storage-worker/workers/lokijs-indexeddb.worker.js.map new file mode 100644 index 00000000000..de9491f36fe --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-indexeddb.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-indexeddb.worker.js","names":["LokiIndexedDBAdapter","require","storage","getRxStorageLoki","adapter","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\nconst LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AACA,IAAMA,oBAAoB,GAAGC,OAAO,CAAC,iCAAiC,CAAC;AAEvE,IAAMC,OAAO,GAAG,IAAAC,+BAAgB,EAAC;EAC7BC,OAAO,EAAE,IAAIJ,oBAAoB;AACrC,CAAC,CAAC;AACF,IAAAK,qCAAsB,EAAC;EACnBH,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-memory.worker.js b/dist/lib/plugins/storage-worker/workers/lokijs-memory.worker.js new file mode 100644 index 00000000000..7c55a80ace3 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-memory.worker.js @@ -0,0 +1,9 @@ +"use strict"; + +var _storageLokijs = require("../../storage-lokijs"); +var _storageWorker = require("../../storage-worker"); +var storage = (0, _storageLokijs.getRxStorageLoki)(); +(0, _storageWorker.wrappedWorkerRxStorage)({ + storage: storage +}); +//# sourceMappingURL=lokijs-memory.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/storage-worker/workers/lokijs-memory.worker.js.map b/dist/lib/plugins/storage-worker/workers/lokijs-memory.worker.js.map new file mode 100644 index 00000000000..2ccfccc5b02 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/lokijs-memory.worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lokijs-memory.worker.js","names":["storage","getRxStorageLoki","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/storage-worker/workers/lokijs-memory.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../storage-lokijs';\nimport { wrappedWorkerRxStorage } from '../../storage-worker';\n\nconst storage = getRxStorageLoki();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAMA,OAAO,GAAG,IAAAC,+BAAgB,GAAE;AAClC,IAAAC,qCAAsB,EAAC;EACnBF,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/webpack.config.js b/dist/lib/plugins/storage-worker/workers/webpack.config.js similarity index 71% rename from dist/lib/plugins/worker/workers/webpack.config.js rename to dist/lib/plugins/storage-worker/workers/webpack.config.js index 29c027a7895..58a91cc92ca 100644 --- a/dist/lib/plugins/worker/workers/webpack.config.js +++ b/dist/lib/plugins/storage-worker/workers/webpack.config.js @@ -6,14 +6,12 @@ var projectRootPath = path.resolve(__dirname, '../../../../'); var babelConfig = require('../../../../babel.config'); module.exports = { entry: { - 'lokijs-incremental-indexeddb': './src/plugins/worker/workers/lokijs-incremental-indexeddb.worker.ts', - 'lokijs-indexeddb': './src/plugins/worker/workers/lokijs-indexeddb.worker.ts', - 'lokijs-memory': './src/plugins/worker/workers/lokijs-memory.worker.ts', - 'lokijs-fs': './src/plugins/worker/workers/lokijs-fs.worker.ts', - 'pouchdb-idb': './src/plugins/worker/workers/pouchdb-idb.worker.ts', - 'pouchdb-memory': './src/plugins/worker/workers/pouchdb-memory.worker.ts', - 'dexie': './src/plugins/worker/workers/dexie.worker.ts', - 'dexie-memory': './src/plugins/worker/workers/dexie-memory.worker.ts' + 'lokijs-incremental-indexeddb': './src/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.ts', + 'lokijs-indexeddb': './src/plugins/storage-worker/workers/lokijs-indexeddb.worker.ts', + 'lokijs-memory': './src/plugins/storage-worker/workers/lokijs-memory.worker.ts', + 'lokijs-fs': './src/plugins/storage-worker/workers/lokijs-fs.worker.ts', + 'dexie': './src/plugins/storage-worker/workers/dexie.worker.ts', + 'dexie-memory': './src/plugins/storage-worker/workers/dexie-memory.worker.ts' }, output: { filename: '[name].worker.js', diff --git a/dist/lib/plugins/storage-worker/workers/webpack.config.js.map b/dist/lib/plugins/storage-worker/workers/webpack.config.js.map new file mode 100644 index 00000000000..6c5683f8688 --- /dev/null +++ b/dist/lib/plugins/storage-worker/workers/webpack.config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webpack.config.js","names":["path","require","TerserPlugin","projectRootPath","resolve","__dirname","babelConfig","module","exports","entry","output","filename","clean","mode","cache","type","cacheDirectory","devtool","rules","test","exclude","use","loader","options","extensions","fallback","fs","optimization","moduleIds","minimize","minimizer","terserOptions","format","comments","extractComments"],"sources":["../../../../../src/plugins/storage-worker/workers/webpack.config.js"],"sourcesContent":["const path = require('path');\nconst TerserPlugin = require('terser-webpack-plugin');\n\nconst projectRootPath = path.resolve(\n __dirname,\n '../../../../'\n);\n\nconst babelConfig = require('../../../../babel.config');\nmodule.exports = {\n entry: {\n 'lokijs-incremental-indexeddb': './src/plugins/storage-worker/workers/lokijs-incremental-indexeddb.worker.ts',\n 'lokijs-indexeddb': './src/plugins/storage-worker/workers/lokijs-indexeddb.worker.ts',\n 'lokijs-memory': './src/plugins/storage-worker/workers/lokijs-memory.worker.ts',\n 'lokijs-fs': './src/plugins/storage-worker/workers/lokijs-fs.worker.ts',\n 'dexie': './src/plugins/storage-worker/workers/dexie.worker.ts',\n 'dexie-memory': './src/plugins/storage-worker/workers/dexie-memory.worker.ts'\n },\n output: {\n filename: '[name].worker.js',\n clean: true,\n path: path.resolve(\n projectRootPath,\n 'dist/workers'\n ),\n },\n mode: 'production',\n cache: {\n type: 'filesystem',\n cacheDirectory: path.resolve(\n projectRootPath,\n 'test_tmp',\n 'webpack-cache-worker'\n ),\n },\n devtool: 'source-map',\n module: {\n rules: [\n /**\n * We transpile the typscript via babel instead of ts-loader.\n * This ensures we have the exact same babel config\n * as the root RxDB project.\n */\n {\n test: /\\.tsx?$/,\n exclude: /(node_modules)/,\n use: {\n loader: 'babel-loader',\n options: babelConfig\n },\n }\n ],\n },\n resolve: {\n extensions: ['.tsx', '.ts', '.js'],\n /**\n * Fix LokiJS bundle error\n * @link https://rxdb.info/rx-storage-lokijs.html\n */\n fallback: {\n fs: false\n }\n },\n optimization: {\n moduleIds: 'deterministic',\n minimize: true,\n minimizer: [new TerserPlugin({\n terserOptions: {\n format: {\n comments: false,\n },\n },\n /**\n * Disable creating the license files.\n * @link https://github.com/webpack/webpack/issues/12506#issuecomment-789314176\n */\n extractComments: false,\n })],\n }\n};\n"],"mappings":";;AAAA,IAAMA,IAAI,GAAGC,OAAO,CAAC,MAAM,CAAC;AAC5B,IAAMC,YAAY,GAAGD,OAAO,CAAC,uBAAuB,CAAC;AAErD,IAAME,eAAe,GAAGH,IAAI,CAACI,OAAO,CAChCC,SAAS,EACT,cAAc,CACjB;AAED,IAAMC,WAAW,GAAGL,OAAO,CAAC,0BAA0B,CAAC;AACvDM,MAAM,CAACC,OAAO,GAAG;EACbC,KAAK,EAAE;IACH,8BAA8B,EAAE,6EAA6E;IAC7G,kBAAkB,EAAE,iEAAiE;IACrF,eAAe,EAAE,8DAA8D;IAC/E,WAAW,EAAE,0DAA0D;IACvE,OAAO,EAAE,sDAAsD;IAC/D,cAAc,EAAE;EACpB,CAAC;EACDC,MAAM,EAAE;IACJC,QAAQ,EAAE,kBAAkB;IAC5BC,KAAK,EAAE,IAAI;IACXZ,IAAI,EAAEA,IAAI,CAACI,OAAO,CACdD,eAAe,EACf,cAAc;EAEtB,CAAC;EACDU,IAAI,EAAE,YAAY;EAClBC,KAAK,EAAE;IACHC,IAAI,EAAE,YAAY;IAClBC,cAAc,EAAEhB,IAAI,CAACI,OAAO,CACxBD,eAAe,EACf,UAAU,EACV,sBAAsB;EAE9B,CAAC;EACDc,OAAO,EAAE,YAAY;EACrBV,MAAM,EAAE;IACJW,KAAK,EAAE;IACH;AACZ;AACA;AACA;AACA;IACY;MACIC,IAAI,EAAE,SAAS;MACfC,OAAO,EAAE,gBAAgB;MACzBC,GAAG,EAAE;QACDC,MAAM,EAAE,cAAc;QACtBC,OAAO,EAAEjB;MACb;IACJ,CAAC;EAET,CAAC;EACDF,OAAO,EAAE;IACLoB,UAAU,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC;IAClC;AACR;AACA;AACA;IACQC,QAAQ,EAAE;MACNC,EAAE,EAAE;IACR;EACJ,CAAC;EACDC,YAAY,EAAE;IACVC,SAAS,EAAE,eAAe;IAC1BC,QAAQ,EAAE,IAAI;IACdC,SAAS,EAAE,CAAC,IAAI5B,YAAY,CAAC;MACzB6B,aAAa,EAAE;QACXC,MAAM,EAAE;UACJC,QAAQ,EAAE;QACd;MACJ,CAAC;MACD;AACZ;AACA;AACA;MACYC,eAAe,EAAE;IACrB,CAAC,CAAC;EACN;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/update/index.js b/dist/lib/plugins/update/index.js index c5e62241f3d..991775f46f0 100644 --- a/dist/lib/plugins/update/index.js +++ b/dist/lib/plugins/update/index.js @@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.RxDBUpdatePlugin = void 0; exports.RxQueryUpdate = RxQueryUpdate; +exports.incrementalUpdate = incrementalUpdate; exports.update = update; var _modifyjs = _interopRequireDefault(require("modifyjs")); /** @@ -14,6 +15,12 @@ var _modifyjs = _interopRequireDefault(require("modifyjs")); * @link https://github.com/lgandecki/modifyjs */ +function incrementalUpdate(updateObj) { + return this.incrementalModify(function (docData) { + var newDocData = (0, _modifyjs["default"])(docData, updateObj); + return newDocData; + }); +} function update(updateObj) { var oldDocData = this._data; var newDocData = (0, _modifyjs["default"])(oldDocData, updateObj); @@ -44,6 +51,7 @@ var RxDBUpdatePlugin = { prototypes: { RxDocument: function RxDocument(proto) { proto.update = update; + proto.incrementalUpdate = incrementalUpdate; }, RxQuery: function RxQuery(proto) { proto.update = RxQueryUpdate; diff --git a/dist/lib/plugins/update/index.js.map b/dist/lib/plugins/update/index.js.map index f42bb120a1f..e8702ea2966 100644 --- a/dist/lib/plugins/update/index.js.map +++ b/dist/lib/plugins/update/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["update","updateObj","oldDocData","_data","newDocData","modifyjs","_saveData","RxQueryUpdate","exec","then","docs","Array","isArray","Promise","all","map","doc","RxDBUpdatePlugin","name","rxdb","prototypes","RxDocument","proto","RxQuery"],"sources":["../../../../src/plugins/update/index.ts"],"sourcesContent":["/**\n * this plugin allows delta-updates with mongo-like-syntax\n * It's using modifyjs internally\n * @link https://github.com/lgandecki/modifyjs\n */\nimport modifyjs from 'modifyjs';\nimport type {\n RxDocument,\n RxQuery,\n RxPlugin,\n UpdateQuery\n} from '../../types';\n\nexport function update(this: RxDocument, updateObj: any) {\n const oldDocData = this._data;\n const newDocData = modifyjs(oldDocData, updateObj);\n return this._saveData(newDocData, oldDocData);\n}\n\nexport function RxQueryUpdate(\n this: RxQuery,\n updateObj: UpdateQuery\n): Promise {\n return this.exec()\n .then(docs => {\n if (!docs) {\n return null;\n }\n if (Array.isArray(docs)) {\n return Promise.all(\n docs.map(doc => doc.update(updateObj))\n ).then(() => docs);\n } else {\n // via findOne()\n return docs.update(updateObj).then(() => docs);\n }\n });\n}\n\n\nexport const RxDBUpdatePlugin: RxPlugin = {\n name: 'update',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.update = update;\n },\n RxQuery: (proto: any) => {\n proto.update = RxQueryUpdate;\n }\n }\n};\n"],"mappings":";;;;;;;;;AAKA;AALA;AACA;AACA;AACA;AACA;;AASO,SAASA,MAAM,CAAmBC,SAAc,EAAE;EACrD,IAAMC,UAAU,GAAG,IAAI,CAACC,KAAK;EAC7B,IAAMC,UAAU,GAAG,IAAAC,oBAAQ,EAACH,UAAU,EAAED,SAAS,CAAC;EAClD,OAAO,IAAI,CAACK,SAAS,CAACF,UAAU,EAAEF,UAAU,CAAC;AACjD;AAEO,SAASK,aAAa,CAEzBN,SAA2B,EACf;EACZ,OAAO,IAAI,CAACO,IAAI,EAAE,CACbC,IAAI,CAAC,UAAAC,IAAI,EAAI;IACV,IAAI,CAACA,IAAI,EAAE;MACP,OAAO,IAAI;IACf;IACA,IAAIC,KAAK,CAACC,OAAO,CAACF,IAAI,CAAC,EAAE;MACrB,OAAOG,OAAO,CAACC,GAAG,CACdJ,IAAI,CAACK,GAAG,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAAChB,MAAM,CAACC,SAAS,CAAC;MAAA,EAAC,CACzC,CAACQ,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IACtB,CAAC,MAAM;MACH;MACA,OAAOA,IAAI,CAACV,MAAM,CAACC,SAAS,CAAC,CAACQ,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IAClD;EACJ,CAAC,CAAC;AACV;AAGO,IAAMO,gBAA0B,GAAG;EACtCC,IAAI,EAAE,QAAQ;EACdC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACtB,MAAM,GAAGA,MAAM;IACzB,CAAC;IACDuB,OAAO,EAAE,iBAACD,KAAU,EAAK;MACrBA,KAAK,CAACtB,MAAM,GAAGO,aAAa;IAChC;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["incrementalUpdate","updateObj","incrementalModify","docData","newDocData","modifyjs","update","oldDocData","_data","_saveData","RxQueryUpdate","exec","then","docs","Array","isArray","Promise","all","map","doc","RxDBUpdatePlugin","name","rxdb","prototypes","RxDocument","proto","RxQuery"],"sources":["../../../../src/plugins/update/index.ts"],"sourcesContent":["/**\n * this plugin allows delta-updates with mongo-like-syntax\n * It's using modifyjs internally\n * @link https://github.com/lgandecki/modifyjs\n */\nimport modifyjs from 'modifyjs';\nimport type {\n RxDocument,\n RxQuery,\n RxPlugin,\n UpdateQuery\n} from '../../types';\n\nexport function incrementalUpdate(\n this: RxDocument,\n updateObj: UpdateQuery\n): Promise> {\n return this.incrementalModify((docData) => {\n const newDocData = modifyjs(docData, updateObj);\n return newDocData;\n });\n}\n\nexport function update(\n this: RxDocument,\n updateObj: UpdateQuery\n): Promise> {\n const oldDocData = this._data;\n const newDocData = modifyjs(oldDocData, updateObj);\n return this._saveData(newDocData, oldDocData);\n}\n\nexport function RxQueryUpdate(\n this: RxQuery,\n updateObj: UpdateQuery\n): Promise {\n return this.exec()\n .then(docs => {\n if (!docs) {\n return null;\n }\n if (Array.isArray(docs)) {\n return Promise.all(\n docs.map(doc => doc.update(updateObj))\n ).then(() => docs);\n } else {\n // via findOne()\n return docs.update(updateObj).then(() => docs);\n }\n });\n}\n\n\nexport const RxDBUpdatePlugin: RxPlugin = {\n name: 'update',\n rxdb: true,\n prototypes: {\n RxDocument: (proto: any) => {\n proto.update = update;\n proto.incrementalUpdate = incrementalUpdate;\n },\n RxQuery: (proto: any) => {\n proto.update = RxQueryUpdate;\n }\n }\n};\n"],"mappings":";;;;;;;;;;AAKA;AALA;AACA;AACA;AACA;AACA;;AASO,SAASA,iBAAiB,CAE7BC,SAAiC,EACH;EAC9B,OAAO,IAAI,CAACC,iBAAiB,CAAC,UAACC,OAAO,EAAK;IACvC,IAAMC,UAAU,GAAG,IAAAC,oBAAQ,EAACF,OAAO,EAAEF,SAAS,CAAC;IAC/C,OAAOG,UAAU;EACrB,CAAC,CAAC;AACN;AAEO,SAASE,MAAM,CAElBL,SAAiC,EACH;EAC9B,IAAMM,UAAU,GAAG,IAAI,CAACC,KAAK;EAC7B,IAAMJ,UAAU,GAAG,IAAAC,oBAAQ,EAACE,UAAU,EAAEN,SAAS,CAAC;EAClD,OAAO,IAAI,CAACQ,SAAS,CAACL,UAAU,EAAEG,UAAU,CAAC;AACjD;AAEO,SAASG,aAAa,CAEzBT,SAA2B,EACf;EACZ,OAAO,IAAI,CAACU,IAAI,EAAE,CACbC,IAAI,CAAC,UAAAC,IAAI,EAAI;IACV,IAAI,CAACA,IAAI,EAAE;MACP,OAAO,IAAI;IACf;IACA,IAAIC,KAAK,CAACC,OAAO,CAACF,IAAI,CAAC,EAAE;MACrB,OAAOG,OAAO,CAACC,GAAG,CACdJ,IAAI,CAACK,GAAG,CAAC,UAAAC,GAAG;QAAA,OAAIA,GAAG,CAACb,MAAM,CAACL,SAAS,CAAC;MAAA,EAAC,CACzC,CAACW,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IACtB,CAAC,MAAM;MACH;MACA,OAAOA,IAAI,CAACP,MAAM,CAACL,SAAS,CAAC,CAACW,IAAI,CAAC;QAAA,OAAMC,IAAI;MAAA,EAAC;IAClD;EACJ,CAAC,CAAC;AACV;AAGO,IAAMO,gBAA0B,GAAG;EACtCC,IAAI,EAAE,QAAQ;EACdC,IAAI,EAAE,IAAI;EACVC,UAAU,EAAE;IACRC,UAAU,EAAE,oBAACC,KAAU,EAAK;MACxBA,KAAK,CAACnB,MAAM,GAAGA,MAAM;MACrBmB,KAAK,CAACzB,iBAAiB,GAAGA,iBAAiB;IAC/C,CAAC;IACD0B,OAAO,EAAE,iBAACD,KAAU,EAAK;MACrBA,KAAK,CAACnB,MAAM,GAAGI,aAAa;IAChC;EACJ;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/index.js b/dist/lib/plugins/utils/index.js new file mode 100644 index 00000000000..54cf901808c --- /dev/null +++ b/dist/lib/plugins/utils/index.js @@ -0,0 +1,138 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _utilsArray = require("./utils-array"); +Object.keys(_utilsArray).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsArray[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsArray[key]; + } + }); +}); +var _utilsBlobBuffer = require("./utils-blob-buffer"); +Object.keys(_utilsBlobBuffer).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsBlobBuffer[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsBlobBuffer[key]; + } + }); +}); +var _utilsBase = require("./utils-base64"); +Object.keys(_utilsBase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsBase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsBase[key]; + } + }); +}); +var _utilsRevision = require("./utils-revision"); +Object.keys(_utilsRevision).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsRevision[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsRevision[key]; + } + }); +}); +var _utilsDocument = require("./utils-document"); +Object.keys(_utilsDocument).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsDocument[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsDocument[key]; + } + }); +}); +var _utilsHash = require("./utils-hash"); +Object.keys(_utilsHash).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsHash[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsHash[key]; + } + }); +}); +var _utilsPromise = require("./utils-promise"); +Object.keys(_utilsPromise).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsPromise[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsPromise[key]; + } + }); +}); +var _utilsString = require("./utils-string"); +Object.keys(_utilsString).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsString[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsString[key]; + } + }); +}); +var _utilsObject = require("./utils-object"); +Object.keys(_utilsObject).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsObject[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsObject[key]; + } + }); +}); +var _utilsError = require("./utils-error"); +Object.keys(_utilsError).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsError[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsError[key]; + } + }); +}); +var _utilsTime = require("./utils-time"); +Object.keys(_utilsTime).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsTime[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsTime[key]; + } + }); +}); +var _utilsOther = require("./utils-other"); +Object.keys(_utilsOther).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsOther[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsOther[key]; + } + }); +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/index.js.map b/dist/lib/plugins/utils/index.js.map new file mode 100644 index 00000000000..47e69f52ad9 --- /dev/null +++ b/dist/lib/plugins/utils/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/utils/index.ts"],"sourcesContent":["export * from './utils-array';\nexport * from './utils-blob-buffer';\nexport * from './utils-base64';\nexport * from './utils-revision';\nexport * from './utils-document';\nexport * from './utils-hash';\nexport * from './utils-promise';\nexport * from './utils-string';\nexport * from './utils-object';\nexport * from './utils-error';\nexport * from './utils-time';\nexport * from './utils-other';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-array.js b/dist/lib/plugins/utils/utils-array.js new file mode 100644 index 00000000000..3ad1641c6d0 --- /dev/null +++ b/dist/lib/plugins/utils/utils-array.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.arrayFilterNotEmpty = arrayFilterNotEmpty; +exports.batchArray = batchArray; +exports.isMaybeReadonlyArray = isMaybeReadonlyArray; +exports.lastOfArray = lastOfArray; +exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; +exports.shuffleArray = shuffleArray; +exports.toArray = toArray; +function lastOfArray(ar) { + return ar[ar.length - 1]; +} + +/** + * shuffle the given array + */ +function shuffleArray(arr) { + return arr.sort(function () { + return Math.random() - 0.5; + }); +} +function toArray(input) { + return Array.isArray(input) ? input.slice(0) : [input]; +} + +/** + * Split array with items into smaller arrays with items + * @link https://stackoverflow.com/a/7273794/3443137 + */ +function batchArray(array, batchSize) { + array = array.slice(0); + var ret = []; + while (array.length) { + var batch = array.splice(0, batchSize); + ret.push(batch); + } + return ret; +} + +/** + * @link https://stackoverflow.com/a/15996017 + */ +function removeOneFromArrayIfMatches(ar, condition) { + ar = ar.slice(); + var i = ar.length; + var done = false; + while (i-- && !done) { + if (condition(ar[i])) { + done = true; + ar.splice(i, 1); + } + } + return ar; +} + +/** + * returns true if the supplied argument is either an Array or a Readonly> + */ +function isMaybeReadonlyArray(x) { + // While this looks strange, it's a workaround for an issue in TypeScript: + // https://github.com/microsoft/TypeScript/issues/17002 + // + // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array, + // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`. + // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while + // still performing runtime type inspection. + return Array.isArray(x); +} + +/** + * Use this in array.filter() to remove all empty slots + * and have the correct typings afterwards. + * @link https://stackoverflow.com/a/46700791/3443137 + */ +function arrayFilterNotEmpty(value) { + if (value === null || value === undefined) { + return false; + } + return true; +} +//# sourceMappingURL=utils-array.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-array.js.map b/dist/lib/plugins/utils/utils-array.js.map new file mode 100644 index 00000000000..f32ead1da8f --- /dev/null +++ b/dist/lib/plugins/utils/utils-array.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-array.js","names":["lastOfArray","ar","length","shuffleArray","arr","sort","Math","random","toArray","input","Array","isArray","slice","batchArray","array","batchSize","ret","batch","splice","push","removeOneFromArrayIfMatches","condition","i","done","isMaybeReadonlyArray","x","arrayFilterNotEmpty","value","undefined"],"sources":["../../../../src/plugins/utils/utils-array.ts"],"sourcesContent":["import type {\n MaybeReadonly\n} from '../../types';\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.sort(() => (Math.random() - 0.5));\n}\n\nexport function toArray(input: T | T[] | Readonly | Readonly): T[] {\n return Array.isArray(input) ? (input as any[]).slice(0) : [input];\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;;;;;;AAIO,SAASA,WAAW,CAAIC,EAAO,EAAiB;EACnD,OAAOA,EAAE,CAACA,EAAE,CAACC,MAAM,GAAG,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACO,SAASC,YAAY,CAAIC,GAAQ,EAAO;EAC3C,OAAOA,GAAG,CAACC,IAAI,CAAC;IAAA,OAAOC,IAAI,CAACC,MAAM,EAAE,GAAG,GAAG;EAAA,CAAC,CAAC;AAChD;AAEO,SAASC,OAAO,CAAIC,K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\ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-base64.js b/dist/lib/plugins/utils/utils-base64.js new file mode 100644 index 00000000000..afcd74978de --- /dev/null +++ b/dist/lib/plugins/utils/utils-base64.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.arrayBufferToBase64 = arrayBufferToBase64; +exports.b64DecodeUnicode = b64DecodeUnicode; +exports.b64EncodeUnicode = b64EncodeUnicode; +var _jsBase = require("js-base64"); +/** + * NO! We cannot just use btoa() and atob() + * because they do not work correctly with binary data. + * @link https://stackoverflow.com/q/30106476/3443137 + */ + +/** + * atob() and btoa() do not work well with non ascii chars, + * so we have to use these helper methods instead. + * @link https://stackoverflow.com/a/30106551/3443137 + */ +// Encoding UTF8 -> base64 +function b64EncodeUnicode(str) { + return (0, _jsBase.encode)(str); +} + +// Decoding base64 -> UTF8 +function b64DecodeUnicode(str) { + return (0, _jsBase.decode)(str); +} + +/** + * @link https://stackoverflow.com/a/9458996/3443137 + */ +function arrayBufferToBase64(buffer) { + var binary = ''; + var bytes = new Uint8Array(buffer); + var len = bytes.byteLength; + for (var i = 0; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} +//# sourceMappingURL=utils-base64.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-base64.js.map b/dist/lib/plugins/utils/utils-base64.js.map new file mode 100644 index 00000000000..826cafa6aa5 --- /dev/null +++ b/dist/lib/plugins/utils/utils-base64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-base64.js","names":["b64EncodeUnicode","str","encode","b64DecodeUnicode","decode","arrayBufferToBase64","buffer","binary","bytes","Uint8Array","len","byteLength","i","String","fromCharCode","btoa"],"sources":["../../../../src/plugins/utils/utils-base64.ts"],"sourcesContent":["\n/**\n * NO! We cannot just use btoa() and atob()\n * because they do not work correctly with binary data.\n * @link https://stackoverflow.com/q/30106476/3443137\n */\nimport { encode, decode } from 'js-base64';\n\n/**\n * atob() and btoa() do not work well with non ascii chars,\n * so we have to use these helper methods instead.\n * @link https://stackoverflow.com/a/30106551/3443137\n */\n// Encoding UTF8 -> base64\nexport function b64EncodeUnicode(str: string) {\n return encode(str);\n}\n\n// Decoding base64 -> UTF8\nexport function b64DecodeUnicode(str: string) {\n return decode(str);\n}\n\n/**\n * @link https://stackoverflow.com/a/9458996/3443137\n */\nexport function arrayBufferToBase64(buffer: ArrayBuffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n"],"mappings":";;;;;;;;AAMA;AALA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,gBAAgB,CAACC,GAAW,EAAE;EAC1C,OAAO,IAAAC,cAAM,EAACD,GAAG,CAAC;AACtB;;AAEA;AACO,SAASE,gBAAgB,CAACF,GAAW,EAAE;EAC1C,OAAO,IAAAG,cAAM,EAACH,GAAG,CAAC;AACtB;;AAEA;AACA;AACA;AACO,SAASI,mBAAmB,CAACC,MAAmB,EAAE;EACrD,IAAIC,MAAM,GAAG,EAAE;EACf,IAAMC,KAAK,GAAG,IAAIC,UAAU,CAACH,MAAM,CAAC;EACpC,IAAMI,GAAG,GAAGF,KAAK,CAACG,UAAU;EAC5B,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,GAAG,EAAEE,CAAC,EAAE,EAAE;IAC1BL,MAAM,IAAIM,MAAM,CAACC,YAAY,CAACN,KAAK,CAACI,CAAC,CAAC,CAAC;EAC3C;EACA,OAAOG,IAAI,CAACR,MAAM,CAAC;AACvB"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-blob-buffer.js b/dist/lib/plugins/utils/utils-blob-buffer.js new file mode 100644 index 00000000000..01bd05e9312 --- /dev/null +++ b/dist/lib/plugins/utils/utils-blob-buffer.js @@ -0,0 +1,124 @@ +"use strict"; + +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.blobBufferUtil = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utilsBase = require("./utils-base64"); +/** + * This is an abstraction over the Blob/Buffer data structure. + * We need this because it behaves different in different JavaScript runtimes. + * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support + * the Blob data structure which is also supported by the browsers. + */ +var blobBufferUtil = { + /** + * depending if we are on node or browser, + * we have to use Buffer(node) or Blob(browser) + */ + createBlobBuffer: function createBlobBuffer(data, type) { + var blobBuffer = new Blob([data], { + type: type + }); + return blobBuffer; + }, + /** + * depending if we are on node or browser, + * we have to use Buffer(node) or Blob(browser) + */ + createBlobBufferFromBase64: function () { + var _createBlobBufferFromBase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(base64String, type) { + var base64Response, blob; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return fetch("data:" + type + ";base64," + base64String); + case 2: + base64Response = _context.sent; + _context.next = 5; + return base64Response.blob(); + case 5: + blob = _context.sent; + return _context.abrupt("return", blob); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createBlobBufferFromBase64(_x, _x2) { + return _createBlobBufferFromBase.apply(this, arguments); + } + return createBlobBufferFromBase64; + }(), + isBlobBuffer: function isBlobBuffer(data) { + if (data instanceof Blob || typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) { + return true; + } else { + return false; + } + }, + toString: function toString(blobBuffer) { + /** + * in the electron-renderer we have a typed array insteaf of a blob + * so we have to transform it. + * @link https://github.com/pubkey/rxdb/issues/1371 + */ + var blobBufferType = Object.prototype.toString.call(blobBuffer); + if (blobBufferType === '[object Uint8Array]') { + blobBuffer = new Blob([blobBuffer]); + } + if (typeof blobBuffer === 'string') { + return Promise.resolve(blobBuffer); + } + return blobBuffer.text(); + }, + toBase64String: function () { + var _toBase64String = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(blobBuffer) { + var blobBufferType, arrayBuffer; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(typeof blobBuffer === 'string')) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", blobBuffer); + case 2: + /** + * in the electron-renderer we have a typed array insteaf of a blob + * so we have to transform it. + * @link https://github.com/pubkey/rxdb/issues/1371 + */ + blobBufferType = Object.prototype.toString.call(blobBuffer); + if (blobBufferType === '[object Uint8Array]') { + blobBuffer = new Blob([blobBuffer]); + } + _context2.next = 6; + return fetch(URL.createObjectURL(blobBuffer)).then(function (res) { + return res.arrayBuffer(); + }); + case 6: + arrayBuffer = _context2.sent; + return _context2.abrupt("return", (0, _utilsBase.arrayBufferToBase64)(arrayBuffer)); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function toBase64String(_x3) { + return _toBase64String.apply(this, arguments); + } + return toBase64String; + }(), + size: function size(blobBuffer) { + return blobBuffer.size; + } +}; +exports.blobBufferUtil = blobBufferUtil; +//# sourceMappingURL=utils-blob-buffer.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-blob-buffer.js.map b/dist/lib/plugins/utils/utils-blob-buffer.js.map new file mode 100644 index 00000000000..3fda2cc2280 --- /dev/null +++ b/dist/lib/plugins/utils/utils-blob-buffer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-blob-buffer.js","names":["blobBufferUtil","createBlobBuffer","data","type","blobBuffer","Blob","createBlobBufferFromBase64","base64String","fetch","base64Response","blob","isBlobBuffer","Buffer","isBuffer","toString","blobBufferType","Object","prototype","call","Promise","resolve","text","toBase64String","URL","createObjectURL","then","res","arrayBuffer","arrayBufferToBase64","size"],"sources":["../../../../src/plugins/utils/utils-blob-buffer.ts"],"sourcesContent":["import type {\n BlobBuffer\n} from '../../types';\nimport { arrayBufferToBase64 } from './utils-base64';\n\n/**\n * This is an abstraction over the Blob/Buffer data structure.\n * We need this because it behaves different in different JavaScript runtimes.\n * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support\n * the Blob data structure which is also supported by the browsers.\n */\nexport const blobBufferUtil = {\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n createBlobBuffer(\n data: string,\n type: string\n ): BlobBuffer {\n const blobBuffer = new Blob([data], {\n type\n });\n return blobBuffer;\n },\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n async createBlobBufferFromBase64(\n base64String: string,\n type: string\n ): Promise {\n const base64Response = await fetch(`data:${type};base64,${base64String}`);\n const blob = await base64Response.blob();\n return blob;\n\n },\n isBlobBuffer(data: any): boolean {\n if (data instanceof Blob || (typeof Buffer !== 'undefined' && Buffer.isBuffer(data))) {\n return true;\n } else {\n return false;\n }\n },\n toString(blobBuffer: BlobBuffer | string): Promise {\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n if (typeof blobBuffer === 'string') {\n return Promise.resolve(blobBuffer);\n }\n\n return (blobBuffer as Blob).text();\n },\n async toBase64String(blobBuffer: BlobBuffer | string): Promise {\n if (typeof blobBuffer === 'string') {\n return blobBuffer;\n }\n\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n\n const arrayBuffer = await fetch(URL.createObjectURL(blobBuffer as Blob)).then(res => res.arrayBuffer());\n return arrayBufferToBase64(arrayBuffer);\n },\n size(blobBuffer: BlobBuffer): number {\n return (blobBuffer as Blob).size;\n }\n};\n"],"mappings":";;;;;;;;;AAGA;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMA,cAAc,GAAG;EAC1B;AACJ;AACA;AACA;EACIC,gBAAgB,4BACZC,IAAY,EACZC,IAAY,EACF;IACV,IAAMC,UAAU,GAAG,IAAIC,IAAI,CAAC,CAACH,IAAI,CAAC,EAAE;MAChCC,IAAI,EAAJA;IACJ,CAAC,CAAC;IACF,OAAOC,UAAU;EACrB,CAAC;EACD;AACJ;AACA;AACA;EACUE,0BAA0B;IAAA,+HAC5BC,YAAoB,EACpBJ,IAAY;MAAA;MAAA;QAAA;UAAA;YAAA;YAAA,OAEiBK,KAAK,WAASL,IAAI,gBAAWI,YAAY,CAAG;UAAA;YAAnEE,cAAc;YAAA;YAAA,OACDA,cAAc,CAACC,IAAI,EAAE;UAAA;YAAlCA,IAAI;YAAA,iCACHA,IAAI;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA;IAAA;MAAA;IAAA;IAAA;EAAA;EAGfC,YAAY,wBAACT,IAAS,EAAW;IAC7B,IAAIA,IAAI,YAAYG,IAAI,IAAK,OAAOO,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACC,QAAQ,CAACX,IAAI,CAAE,EAAE;MAClF,OAAO,IAAI;IACf,CAAC,MAAM;MACH,OAAO,KAAK;IAChB;EACJ,CAAC;EACDY,QAAQ,oBAACV,UAA+B,EAAmB;IACvD;AACR;AACA;AACA;AACA;IACQ,IAAMW,cAAc,GAAGC,MAAM,CAACC,SAAS,CAACH,QAAQ,CAACI,IAAI,CAACd,UAAU,CAAC;IACjE,IAAIW,cAAc,KAAK,qBAAqB,EAAE;MAC1CX,UAAU,GAAG,IAAIC,IAAI,CAAC,CAACD,UAAU,CAAC,CAAC;IACvC;IACA,IAAI,OAAOA,UAAU,KAAK,QAAQ,EAAE;MAChC,OAAOe,OAAO,CAACC,OAAO,CAAChB,UAAU,CAAC;IACtC;IAEA,OAAQA,UAAU,CAAUiB,IAAI,EAAE;EACtC,CAAC;EACKC,cAAc;IAAA,sHAAClB,UAA+B;MAAA;MAAA;QAAA;UAAA;YAAA,MAC5C,OAAOA,UAAU,KAAK,QAAQ;cAAA;cAAA;YAAA;YAAA,kCACvBA,UAAU;UAAA;YAGrB;AACR;AACA;AACA;AACA;YACcW,cAAc,GAAGC,MAAM,CAACC,SAAS,CAACH,QAAQ,CAACI,IAAI,CAACd,UAAU,CAAC;YACjE,IAAIW,cAAc,KAAK,qBAAqB,EAAE;cAC1CX,UAAU,GAAG,IAAIC,IAAI,CAAC,CAACD,UAAU,CAAC,CAAC;YACvC;YAAC;YAAA,OAEyBI,KAAK,CAACe,GAAG,CAACC,eAAe,CAACpB,UAAU,CAAS,CAAC,CAACqB,IAAI,CAAC,UAAAC,GAAG;cAAA,OAAIA,GAAG,CAACC,WAAW,EAAE;YAAA,EAAC;UAAA;YAAjGA,WAAW;YAAA,kCACV,IAAAC,8BAAmB,EAACD,WAAW,CAAC;UAAA;UAAA;YAAA;QAAA;MAAA;IAAA;IAAA;MAAA;IAAA;IAAA;EAAA;EAE3CE,IAAI,gBAACzB,UAAsB,EAAU;IACjC,OAAQA,UAAU,CAAUyB,IAAI;EACpC;AACJ,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-document.js b/dist/lib/plugins/utils/utils-document.js new file mode 100644 index 00000000000..390217e767f --- /dev/null +++ b/dist/lib/plugins/utils/utils-document.js @@ -0,0 +1,90 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RX_META_LWT_MINIMUM = void 0; +exports.areRxDocumentArraysEqual = areRxDocumentArraysEqual; +exports.getDefaultRevision = getDefaultRevision; +exports.getDefaultRxDocumentMeta = getDefaultRxDocumentMeta; +exports.getSortDocumentsByLastWriteTimeComparator = getSortDocumentsByLastWriteTimeComparator; +exports.sortDocumentsByLastWriteTime = sortDocumentsByLastWriteTime; +exports.stripMetaDataFromDocument = stripMetaDataFromDocument; +/** + * We use 1 as minimum so that the value is never falsy. + * This const is used in several places because querying + * with a value lower then the minimum could give false results. + */ +var RX_META_LWT_MINIMUM = 1; +exports.RX_META_LWT_MINIMUM = RX_META_LWT_MINIMUM; +function getDefaultRxDocumentMeta() { + return { + /** + * Set this to 1 to not waste performance + * while calling new Date().. + * The storage wrappers will anyway update + * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage() + */ + lwt: RX_META_LWT_MINIMUM + }; +} + +/** + * Returns a revision that is not valid. + * Use this to have correct typings + * while the storage wrapper anyway will overwrite the revision. + */ +function getDefaultRevision() { + /** + * Use a non-valid revision format, + * to ensure that the RxStorage will throw + * when the revision is not replaced downstream. + */ + return ''; +} +function stripMetaDataFromDocument(docData) { + return Object.assign({}, docData, { + _meta: undefined, + _deleted: undefined, + _rev: undefined + }); +} + +/** + * Faster way to check the equalness of document lists + * compared to doing a deep-equal. + * Here we only check the ids and revisions. + */ +function areRxDocumentArraysEqual(primaryPath, ar1, ar2) { + if (ar1.length !== ar2.length) { + return false; + } + var i = 0; + var len = ar1.length; + while (i < len) { + var row1 = ar1[i]; + var row2 = ar2[i]; + i++; + if (row1._rev !== row2._rev || row1[primaryPath] !== row2[primaryPath]) { + return false; + } + } + return true; +} +function getSortDocumentsByLastWriteTimeComparator(primaryPath) { + return function (a, b) { + if (a._meta.lwt === b._meta.lwt) { + if (b[primaryPath] < a[primaryPath]) { + return 1; + } else { + return -1; + } + } else { + return a._meta.lwt - b._meta.lwt; + } + }; +} +function sortDocumentsByLastWriteTime(primaryPath, docs) { + return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath)); +} +//# sourceMappingURL=utils-document.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-document.js.map b/dist/lib/plugins/utils/utils-document.js.map new file mode 100644 index 00000000000..ce2ce8dab54 --- /dev/null +++ b/dist/lib/plugins/utils/utils-document.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-document.js","names":["RX_META_LWT_MINIMUM","getDefaultRxDocumentMeta","lwt","getDefaultRevision","stripMetaDataFromDocument","docData","Object","assign","_meta","undefined","_deleted","_rev","areRxDocumentArraysEqual","primaryPath","ar1","ar2","length","i","len","row1","row2","getSortDocumentsByLastWriteTimeComparator","a","b","sortDocumentsByLastWriteTime","docs","sort"],"sources":["../../../../src/plugins/utils/utils-document.ts"],"sourcesContent":["import type {\n RxDocumentData,\n RxDocumentMeta,\n StringKeys\n} from '../../types';\n/**\n * We use 1 as minimum so that the value is never falsy.\n * This const is used in several places because querying\n * with a value lower then the minimum could give false results.\n */\nexport const RX_META_LWT_MINIMUM = 1;\n\nexport function getDefaultRxDocumentMeta(): RxDocumentMeta {\n return {\n /**\n * Set this to 1 to not waste performance\n * while calling new Date()..\n * The storage wrappers will anyway update\n * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage()\n */\n lwt: RX_META_LWT_MINIMUM\n };\n}\n\n/**\n * Returns a revision that is not valid.\n * Use this to have correct typings\n * while the storage wrapper anyway will overwrite the revision.\n */\nexport function getDefaultRevision(): string {\n /**\n * Use a non-valid revision format,\n * to ensure that the RxStorage will throw\n * when the revision is not replaced downstream.\n */\n return '';\n}\n\n\nexport function stripMetaDataFromDocument(docData: RxDocumentData): RxDocType {\n return Object.assign({}, docData, {\n _meta: undefined,\n _deleted: undefined,\n _rev: undefined\n });\n}\n\n\n/**\n * Faster way to check the equalness of document lists\n * compared to doing a deep-equal.\n * Here we only check the ids and revisions.\n */\nexport function areRxDocumentArraysEqual(\n primaryPath: StringKeys>,\n ar1: RxDocumentData[],\n ar2: RxDocumentData[]\n): boolean {\n if (ar1.length !== ar2.length) {\n return false;\n }\n let i = 0;\n const len = ar1.length;\n while (i < len) {\n const row1 = ar1[i];\n const row2 = ar2[i];\n i++;\n\n if (\n row1._rev !== row2._rev ||\n row1[primaryPath] !== row2[primaryPath]\n ) {\n return false;\n }\n }\n return true;\n}\n\n\n\nexport function getSortDocumentsByLastWriteTimeComparator(primaryPath: string) {\n return (a: RxDocumentData, b: RxDocumentData) => {\n if (a._meta.lwt === b._meta.lwt) {\n if ((b as any)[primaryPath] < (a as any)[primaryPath]) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return a._meta.lwt - b._meta.lwt;\n }\n };\n}\nexport function sortDocumentsByLastWriteTime(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData[] {\n return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath));\n}\n"],"mappings":";;;;;;;;;;;;AAKA;AACA;AACA;AACA;AACA;AACO,IAAMA,mBAAmB,GAAG,CAAC;AAAC;AAE9B,SAASC,wBAAwB,GAAmB;EACvD,OAAO;IACH;AACR;AACA;AACA;AACA;AACA;IACQC,GAAG,EAAEF;EACT,CAAC;AACL;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASG,kBAAkB,GAAW;EACzC;AACJ;AACA;AACA;AACA;EACI,OAAO,EAAE;AACb;AAGO,SAASC,yBAAyB,CAAYC,OAAkC,EAAa;EAChG,OAAOC,MAAM,CAACC,MAAM,CAAC,CAAC,CAAC,EAAEF,OAAO,EAAE;IAC9BG,KAAK,EAAEC,SAAS;IAChBC,QAAQ,EAAED,SAAS;IACnBE,IAAI,EAAEF;EACV,CAAC,CAAC;AACN;;AAGA;AACA;AACA;AACA;AACA;AACO,SAASG,wBAAwB,CACpCC,WAAkD,EAClDC,GAAgC,EAChCC,GAAgC,EACzB;EACP,IAAID,GAAG,CAACE,MAAM,KAAKD,GAAG,CAACC,MAAM,EAAE;IAC3B,OAAO,KAAK;EAChB;EACA,IAAIC,CAAC,GAAG,CAAC;EACT,IAAMC,GAAG,GAAGJ,GAAG,CAACE,MAAM;EACtB,OAAOC,CAAC,GAAGC,GAAG,EAAE;IACZ,IAAMC,IAAI,GAAGL,GAAG,CAACG,CAAC,CAAC;IACnB,IAAMG,IAAI,GAAGL,GAAG,CAACE,CAAC,CAAC;IACnBA,CAAC,EAAE;IAEH,IACIE,IAAI,CAACR,IAAI,KAAKS,IAAI,CAACT,IAAI,IACvBQ,IAAI,CAACN,WAAW,CAAC,KAAKO,IAAI,CAACP,WAAW,CAAC,EACzC;MACE,OAAO,KAAK;IAChB;EACJ;EACA,OAAO,IAAI;AACf;AAIO,SAASQ,yCAAyC,CAAYR,WAAmB,EAAE;EACtF,OAAO,UAACS,CAA4B,EAAEC,CAA4B,EAAK;IACnE,IAAID,CAAC,CAACd,KAAK,CAACN,GAAG,KAAKqB,CAAC,CAACf,KAAK,CAACN,GAAG,EAAE;MAC7B,IAAKqB,CAAC,CAASV,WAAW,CAAC,GAAIS,CAAC,CAAST,WAAW,CAAC,EAAE;QACnD,OAAO,CAAC;MACZ,CAAC,MAAM;QACH,OAAO,CAAC,CAAC;MACb;IACJ,CAAC,MAAM;MACH,OAAOS,CAAC,CAACd,KAAK,CAACN,GAAG,GAAGqB,CAAC,CAACf,KAAK,CAACN,GAAG;IACpC;EACJ,CAAC;AACL;AACO,SAASsB,4BAA4B,CACxCX,WAAmB,EACnBY,IAAiC,EACN;EAC3B,OAAOA,IAAI,CAACC,IAAI,CAACL,yCAAyC,CAACR,WAAW,CAAC,CAAC;AAC5E"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-error.js b/dist/lib/plugins/utils/utils-error.js new file mode 100644 index 00000000000..61a24ce2a37 --- /dev/null +++ b/dist/lib/plugins/utils/utils-error.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.errorToPlainJson = errorToPlainJson; +exports.pluginMissing = pluginMissing; +var _utilsString = require("./utils-string"); +/** + * Returns an error that indicates that a plugin is missing + * We do not throw a RxError because this should not be handled + * programmatically but by using the correct import + */ +function pluginMissing(pluginKey) { + var keyParts = pluginKey.split('-'); + var pluginName = 'RxDB'; + keyParts.forEach(function (part) { + pluginName += (0, _utilsString.ucfirst)(part); + }); + pluginName += 'Plugin'; + return new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { " + pluginName + " } from 'rxdb/plugins/" + pluginKey + "';\n addRxPlugin(" + pluginName + ");\n "); +} +function errorToPlainJson(err) { + var ret = { + name: err.name, + message: err.message, + rxdb: err.rxdb, + parameters: err.parameters, + code: err.code, + // stack must be last to make it easier to read the json in a console. + stack: err.stack + }; + return ret; +} +//# sourceMappingURL=utils-error.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-error.js.map b/dist/lib/plugins/utils/utils-error.js.map new file mode 100644 index 00000000000..f571966ac6c --- /dev/null +++ b/dist/lib/plugins/utils/utils-error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-error.js","names":["pluginMissing","pluginKey","keyParts","split","pluginName","forEach","part","ucfirst","Error","errorToPlainJson","err","ret","name","message","rxdb","parameters","code","stack"],"sources":["../../../../src/plugins/utils/utils-error.ts"],"sourcesContent":["import type {\n PlainJsonError,\n RxError,\n RxTypeError\n} from '../../types';\nimport { ucfirst } from './utils-string';\n\n\n\n/**\n * Returns an error that indicates that a plugin is missing\n * We do not throw a RxError because this should not be handled\n * programmatically but by using the correct import\n */\nexport function pluginMissing(\n pluginKey: string\n): Error {\n const keyParts = pluginKey.split('-');\n let pluginName = 'RxDB';\n keyParts.forEach(part => {\n pluginName += ucfirst(part);\n });\n pluginName += 'Plugin';\n return new Error(\n `You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { ${pluginName} } from 'rxdb/plugins/${pluginKey}';\n addRxPlugin(${pluginName});\n `\n );\n}\n\n\n\nexport function errorToPlainJson(err: Error | TypeError | RxError | RxTypeError): PlainJsonError {\n const ret: PlainJsonError = {\n name: err.name,\n message: err.message,\n rxdb: (err as any).rxdb,\n parameters: (err as RxError).parameters,\n code: (err as RxError).code,\n // stack must be last to make it easier to read the json in a console.\n stack: err.stack\n };\n return ret;\n}\n"],"mappings":";;;;;;;AAKA;AAIA;AACA;AACA;AACA;AACA;AACO,SAASA,aAAa,CACzBC,SAAiB,EACZ;EACL,IAAMC,QAAQ,GAAGD,SAAS,CAACE,KAAK,CAAC,GAAG,CAAC;EACrC,IAAIC,UAAU,GAAG,MAAM;EACvBF,QAAQ,CAACG,OAAO,CAAC,UAAAC,IAAI,EAAI;IACrBF,UAAU,IAAI,IAAAG,oBAAO,EAACD,IAAI,CAAC;EAC/B,CAAC,CAAC;EACFF,UAAU,IAAI,QAAQ;EACtB,OAAO,IAAII,KAAK,iLAGGJ,UAAU,8BAAyBH,SAAS,oCACzCG,UAAU,kBAE/B;AACL;AAIO,SAASK,gBAAgB,CAACC,GAA8C,EAAkB;EAC7F,IAAMC,GAAmB,GAAG;IACxBC,IAAI,EAAEF,GAAG,CAACE,IAAI;IACdC,OAAO,EAAEH,GAAG,CAACG,OAAO;IACpBC,IAAI,EAAGJ,GAAG,CAASI,IAAI;IACvBC,UAAU,EAAGL,GAAG,CAAaK,UAAU;IACvCC,IAAI,EAAGN,GAAG,CAAaM,IAAI;IAC3B;IACAC,KAAK,EAAEP,GAAG,CAACO;EACf,CAAC;EACD,OAAON,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-hash.js b/dist/lib/plugins/utils/utils-hash.js new file mode 100644 index 00000000000..39a0497e134 --- /dev/null +++ b/dist/lib/plugins/utils/utils-hash.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.defaultHashFunction = defaultHashFunction; +exports.fastUnsecureHash = fastUnsecureHash; +/** + * This is a very fast hash method + * but it is not cryptographically secure. + * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int). + * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery + * @return a string as hash-result + */ +function fastUnsecureHash(inputString, +// used to test the polyfill +doNotUseTextEncoder) { + var hashValue = 0, + i, + chr, + len; + + /** + * For better performance we first transform all + * chars into their ascii numbers at once. + * + * This is what makes the murmurhash implementation such fast. + * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4 + */ + var encoded; + + /** + * All modern browsers support the TextEncoder + * @link https://caniuse.com/textencoder + * But to make RxDB work in other JavaScript runtimes, + * like when using it in flutter or QuickJS, we need to + * make it work even when there is no TextEncoder. + */ + if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) { + encoded = new TextEncoder().encode(inputString); + } else { + encoded = []; + for (var j = 0; j < inputString.length; j++) { + encoded.push(inputString.charCodeAt(j)); + } + } + for (i = 0, len = inputString.length; i < len; i++) { + chr = encoded[i]; + hashValue = (hashValue << 5) - hashValue + chr; + hashValue |= 0; // Convert to 32bit integer + } + + if (hashValue < 0) { + hashValue = hashValue * -1; + } + + /** + * To make the output smaller + * but still have it to represent the same value, + * we use the biggest radix of 36 instead of just + * transforming it into a hex string. + */ + return hashValue.toString(36); +} + +/** + * Default hash method used to create revision hashes + * that do not have to be cryptographically secure. + * IMPORTANT: Changing the default hashing method + * requires a BREAKING change! + */ +function defaultHashFunction(input) { + return fastUnsecureHash(input); +} +//# sourceMappingURL=utils-hash.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-hash.js.map b/dist/lib/plugins/utils/utils-hash.js.map new file mode 100644 index 00000000000..16adc8b6742 --- /dev/null +++ b/dist/lib/plugins/utils/utils-hash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-hash.js","names":["fastUnsecureHash","inputString","doNotUseTextEncoder","hashValue","i","chr","len","encoded","TextEncoder","encode","j","length","push","charCodeAt","toString","defaultHashFunction","input"],"sources":["../../../../src/plugins/utils/utils-hash.ts"],"sourcesContent":["/**\n * This is a very fast hash method\n * but it is not cryptographically secure.\n * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int).\n * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery\n * @return a string as hash-result\n */\nexport function fastUnsecureHash(\n inputString: string,\n // used to test the polyfill\n doNotUseTextEncoder?: boolean\n): string {\n let hashValue = 0,\n i, chr, len;\n\n /**\n * For better performance we first transform all\n * chars into their ascii numbers at once.\n *\n * This is what makes the murmurhash implementation such fast.\n * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4\n */\n let encoded: Uint8Array | number[];\n\n /**\n * All modern browsers support the TextEncoder\n * @link https://caniuse.com/textencoder\n * But to make RxDB work in other JavaScript runtimes,\n * like when using it in flutter or QuickJS, we need to\n * make it work even when there is no TextEncoder.\n */\n if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) {\n encoded = new TextEncoder().encode(inputString);\n } else {\n encoded = [];\n for (let j = 0; j < inputString.length; j++) {\n encoded.push(inputString.charCodeAt(j));\n }\n }\n\n for (i = 0, len = inputString.length; i < len; i++) {\n chr = encoded[i];\n hashValue = ((hashValue << 5) - hashValue) + chr;\n hashValue |= 0; // Convert to 32bit integer\n }\n if (hashValue < 0) {\n hashValue = hashValue * -1;\n }\n\n /**\n * To make the output smaller\n * but still have it to represent the same value,\n * we use the biggest radix of 36 instead of just\n * transforming it into a hex string.\n */\n return hashValue.toString(36);\n}\n\n/**\n * Default hash method used to create revision hashes\n * that do not have to be cryptographically secure.\n * IMPORTANT: Changing the default hashing method\n * requires a BREAKING change!\n */\nexport function defaultHashFunction(input: string): string {\n return fastUnsecureHash(input);\n}\n"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,gBAAgB,CAC5BC,WAAmB;AACnB;AACAC,mBAA6B,EACvB;EACN,IAAIC,SAAS,GAAG,CAAC;IACbC,CAAC;IAAEC,GAAG;IAAEC,GAAG;;EAEf;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAIC,OAA8B;;EAElC;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAI,OAAOC,WAAW,KAAK,WAAW,IAAI,CAACN,mBAAmB,EAAE;IAC5DK,OAAO,GAAG,IAAIC,WAAW,EAAE,CAACC,MAAM,CAACR,WAAW,CAAC;EACnD,CAAC,MAAM;IACHM,OAAO,GAAG,EAAE;IACZ,KAAK,IAAIG,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGT,WAAW,CAACU,MAAM,EAAED,CAAC,EAAE,EAAE;MACzCH,OAAO,CAACK,IAAI,CAACX,WAAW,CAACY,UAAU,CAACH,CAAC,CAAC,CAAC;IAC3C;EACJ;EAEA,KAAKN,CAAC,GAAG,CAAC,EAAEE,GAAG,GAAGL,WAAW,CAACU,MAAM,EAAEP,CAAC,GAAGE,GAAG,EAAEF,CAAC,EAAE,EAAE;IAChDC,GAAG,GAAGE,OAAO,CAACH,CAAC,CAAC;IAChBD,SAAS,GAAI,CAACA,SAAS,IAAI,CAAC,IAAIA,SAAS,GAAIE,GAAG;IAChDF,SAAS,IAAI,CAAC,CAAC,CAAC;EACpB;;EACA,IAAIA,SAAS,GAAG,CAAC,EAAE;IACfA,SAAS,GAAGA,SAAS,GAAG,CAAC,CAAC;EAC9B;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACI,OAAOA,SAAS,CAACW,QAAQ,CAAC,EAAE,CAAC;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,mBAAmB,CAACC,KAAa,EAAU;EACvD,OAAOhB,gBAAgB,CAACgB,KAAK,CAAC;AAClC"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-object.js b/dist/lib/plugins/utils/utils-object.js new file mode 100644 index 00000000000..5b3db628f6d --- /dev/null +++ b/dist/lib/plugins/utils/utils-object.js @@ -0,0 +1,211 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.clone = void 0; +exports.deepFreeze = deepFreeze; +exports.firstPropertyNameOfObject = firstPropertyNameOfObject; +exports.firstPropertyValueOfObject = firstPropertyValueOfObject; +exports.flatClone = flatClone; +exports.flattenObject = flattenObject; +exports.getFromObjectOrThrow = getFromObjectOrThrow; +exports.objectPathMonad = objectPathMonad; +exports.overwriteGetterForCaching = overwriteGetterForCaching; +exports.sortObject = sortObject; +exports.stringifyFilter = stringifyFilter; +function deepFreeze(o) { + Object.freeze(o); + Object.getOwnPropertyNames(o).forEach(function (prop) { + if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop])) { + deepFreeze(o[prop]); + } + }); + return o; +} + +/** + * To get specific nested path values from objects, + * RxDB normally uses the 'object-path' npm module. + * But when performance is really relevant, this is not fast enough. + * Instead we use a monad that can prepare some stuff up front + * and we can re-use the generated function. + */ + +function objectPathMonad(objectPath) { + var split = objectPath.split('.'); + + /** + * Performance shortcut, + * if no nested path is used, + * directly return the field of the object. + */ + if (split.length === 1) { + return function (obj) { + return obj[objectPath]; + }; + } + return function (obj) { + var currentVal = obj; + var t = 0; + while (t < split.length) { + var subPath = split[t]; + currentVal = currentVal[subPath]; + if (typeof currentVal === 'undefined') { + return currentVal; + } + t++; + } + return currentVal; + }; +} +function getFromObjectOrThrow(obj, key) { + var val = obj[key]; + if (!val) { + throw new Error('missing value from object ' + key); + } + return val; +} + +/** + * returns a flattened object + * @link https://gist.github.com/penguinboy/762197 + */ +function flattenObject(ob) { + var toReturn = {}; + for (var i in ob) { + if (!ob.hasOwnProperty(i)) continue; + if (typeof ob[i] === 'object') { + var flatObject = flattenObject(ob[i]); + for (var x in flatObject) { + if (!flatObject.hasOwnProperty(x)) continue; + toReturn[i + '.' + x] = flatObject[x]; + } + } else { + toReturn[i] = ob[i]; + } + } + return toReturn; +} + +/** + * does a flat copy on the objects, + * is about 3 times faster then using deepClone + * @link https://jsperf.com/object-rest-spread-vs-clone/2 + */ +function flatClone(obj) { + return Object.assign({}, obj); +} + +/** + * @link https://stackoverflow.com/a/11509718/3443137 + */ +function firstPropertyNameOfObject(obj) { + return Object.keys(obj)[0]; +} +function firstPropertyValueOfObject(obj) { + var key = Object.keys(obj)[0]; + return obj[key]; +} + +/** + * deep-sort an object so its attributes are in lexical order. + * Also sorts the arrays inside of the object if no-array-sort not set + */ +function sortObject(obj) { + var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (!obj) return obj; // do not sort null, false or undefined + + // array + if (!noArraySort && Array.isArray(obj)) { + return obj.sort(function (a, b) { + if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b); + if (typeof a === 'object') return 1;else return -1; + }).map(function (i) { + return sortObject(i, noArraySort); + }); + } + + // object + // array is also of type object + if (typeof obj === 'object' && !Array.isArray(obj)) { + if (obj instanceof RegExp) { + return obj; + } + var out = {}; + Object.keys(obj).sort(function (a, b) { + return a.localeCompare(b); + }).forEach(function (key) { + out[key] = sortObject(obj[key], noArraySort); + }); + return out; + } + + // everything else + return obj; +} + +/** + * Deep clone a plain json object. + * Does not work with recursive stuff + * or non-plain-json. + * IMPORANT: Performance of this is very important, + * do not change it without running performance tests! + * + * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts + */ +function deepClone(src) { + if (!src) { + return src; + } + if (src === null || typeof src !== 'object') { + return src; + } + if (Array.isArray(src)) { + var ret = new Array(src.length); + var i = ret.length; + while (i--) { + ret[i] = deepClone(src[i]); + } + return ret; + } + var dest = {}; + // eslint-disable-next-line guard-for-in + for (var key in src) { + // TODO we should not be required to deep clone RegEx objects, + // this must be fixed in RxDB. + if (src[key] instanceof RegExp) { + dest[key] = src[key]; + } else { + dest[key] = deepClone(src[key]); + } + } + return dest; +} +var clone = deepClone; + +/** + * overwrites the getter with the actual value + * Mostly used for caching stuff on the first run + */ +exports.clone = clone; +function overwriteGetterForCaching(obj, getterName, value) { + Object.defineProperty(obj, getterName, { + get: function get() { + return value; + } + }); + return value; +} + +/** + * used to JSON.stringify() objects that contain a regex + * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs! + */ +function stringifyFilter(key, value) { + if (value instanceof RegExp) { + return value.toString(); + } + return value; +} +//# sourceMappingURL=utils-object.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-object.js.map b/dist/lib/plugins/utils/utils-object.js.map new file mode 100644 index 00000000000..2e2984f07a3 --- /dev/null +++ b/dist/lib/plugins/utils/utils-object.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-object.js","names":["deepFreeze","o","Object","freeze","getOwnPropertyNames","forEach","prop","hasOwnProperty","isFrozen","objectPathMonad","objectPath","split","length","obj","currentVal","t","subPath","getFromObjectOrThrow","key","val","Error","flattenObject","ob","toReturn","i","flatObject","x","flatClone","assign","firstPropertyNameOfObject","keys","firstPropertyValueOfObject","sortObject","noArraySort","Array","isArray","sort","a","b","localeCompare","map","RegExp","out","deepClone","src","ret","dest","clone","overwriteGetterForCaching","getterName","value","defineProperty","get","stringifyFilter","toString"],"sources":["../../../../src/plugins/utils/utils-object.ts"],"sourcesContent":["import type {\n DeepReadonlyObject\n} from '../../types';\n\nexport function deepFreeze(o: T): T {\n Object.freeze(o);\n Object.getOwnPropertyNames(o).forEach(function (prop) {\n if (\n (o as any).hasOwnProperty(prop)\n &&\n (o as any)[prop] !== null\n &&\n (\n typeof (o as any)[prop] === 'object'\n ||\n typeof (o as any)[prop] === 'function'\n )\n &&\n !Object.isFrozen((o as any)[prop])\n ) {\n deepFreeze((o as any)[prop]);\n }\n });\n return o;\n}\n\n\n/**\n * To get specific nested path values from objects,\n * RxDB normally uses the 'object-path' npm module.\n * But when performance is really relevant, this is not fast enough.\n * Instead we use a monad that can prepare some stuff up front\n * and we can re-use the generated function.\n */\nexport type ObjectPathMonadFunction = (obj: T) => R;\nexport function objectPathMonad(objectPath: string): ObjectPathMonadFunction {\n const split = objectPath.split('.');\n\n /**\n * Performance shortcut,\n * if no nested path is used,\n * directly return the field of the object.\n */\n if (split.length === 1) {\n return (obj: T) => (obj as any)[objectPath];\n }\n\n\n return (obj: T) => {\n let currentVal: any = obj;\n let t = 0;\n while (t < split.length) {\n const subPath = split[t];\n currentVal = currentVal[subPath];\n if (typeof currentVal === 'undefined') {\n return currentVal;\n }\n t++;\n }\n return currentVal;\n };\n}\n\n\nexport function getFromObjectOrThrow(\n obj: { [k: string]: V; },\n key: string\n): V {\n const val = obj[key];\n if (!val) {\n throw new Error('missing value from object ' + key);\n }\n return val;\n}\n\n/**\n * returns a flattened object\n * @link https://gist.github.com/penguinboy/762197\n */\nexport function flattenObject(ob: any) {\n const toReturn: any = {};\n\n for (const i in ob) {\n if (!ob.hasOwnProperty(i)) continue;\n\n if ((typeof ob[i]) === 'object') {\n const flatObject = flattenObject(ob[i]);\n for (const x in flatObject) {\n if (!flatObject.hasOwnProperty(x)) continue;\n\n toReturn[i + '.' + x] = flatObject[x];\n }\n } else {\n toReturn[i] = ob[i];\n }\n }\n return toReturn;\n}\n\n\n/**\n * does a flat copy on the objects,\n * is about 3 times faster then using deepClone\n * @link https://jsperf.com/object-rest-spread-vs-clone/2\n */\nexport function flatClone(obj: T | DeepReadonlyObject | Readonly): T {\n return Object.assign({}, obj) as any;\n}\n\n/**\n * @link https://stackoverflow.com/a/11509718/3443137\n */\nexport function firstPropertyNameOfObject(obj: any): string {\n return Object.keys(obj)[0];\n}\nexport function firstPropertyValueOfObject(obj: { [k: string]: T; }): T {\n const key = Object.keys(obj)[0];\n return obj[key];\n}\n\n\n/**\n * deep-sort an object so its attributes are in lexical order.\n * Also sorts the arrays inside of the object if no-array-sort not set\n */\nexport function sortObject(obj: any, noArraySort = false): any {\n if (!obj) return obj; // do not sort null, false or undefined\n\n // array\n if (!noArraySort && Array.isArray(obj)) {\n return obj\n .sort((a, b) => {\n if (typeof a === 'string' && typeof b === 'string')\n return a.localeCompare(b);\n\n if (typeof a === 'object') return 1;\n else return -1;\n })\n .map(i => sortObject(i, noArraySort));\n }\n\n // object\n // array is also of type object\n if (typeof obj === 'object' && !Array.isArray(obj)) {\n if (obj instanceof RegExp) {\n return obj;\n }\n\n const out: any = {};\n Object.keys(obj)\n .sort((a, b) => a.localeCompare(b))\n .forEach(key => {\n out[key] = sortObject(obj[key], noArraySort);\n });\n return out;\n }\n\n // everything else\n return obj;\n}\n\n\n\n/**\n * Deep clone a plain json object.\n * Does not work with recursive stuff\n * or non-plain-json.\n * IMPORANT: Performance of this is very important,\n * do not change it without running performance tests!\n *\n * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts\n */\nfunction deepClone(src: T | DeepReadonlyObject): T {\n if (!src) {\n return src;\n }\n if (src === null || typeof (src) !== 'object') {\n return src;\n }\n if (Array.isArray(src)) {\n const ret = new Array(src.length);\n let i = ret.length;\n while (i--) {\n ret[i] = deepClone(src[i]);\n }\n return ret as any;\n }\n const dest: any = {};\n // eslint-disable-next-line guard-for-in\n for (const key in src) {\n // TODO we should not be required to deep clone RegEx objects,\n // this must be fixed in RxDB.\n if (src[key] instanceof RegExp) {\n dest[key] = src[key];\n } else {\n dest[key] = deepClone(src[key]);\n }\n }\n return dest;\n}\nexport const clone = deepClone;\n\n\n\n/**\n * overwrites the getter with the actual value\n * Mostly used for caching stuff on the first run\n */\nexport function overwriteGetterForCaching(\n obj: any,\n getterName: string,\n value: ValueType\n): ValueType {\n Object.defineProperty(obj, getterName, {\n get: function () {\n return value;\n }\n });\n return value;\n}\n\n\n\n/**\n * used to JSON.stringify() objects that contain a regex\n * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs!\n */\nexport function stringifyFilter(key: string, value: any) {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n}\n\n\n"],"mappings":";;;;;;;;;;;;;;;;AAIO,SAASA,UAAU,CAAIC,CAAI,EAAK;EACnCC,MAAM,CAACC,MAAM,CAACF,CAAC,CAAC;EAChBC,MAAM,CAACE,mBAAmB,CAACH,CAAC,CAAC,CAACI,OAAO,CAAC,UAAUC,IAAI,EAAE;IAClD,IACKL,CAAC,CAASM,cAAc,CAACD,IAAI,CAAC,IAE9BL,CAAC,CAASK,IAAI,CAAC,KAAK,IAAI,KAGrB,OAAQL,CAAC,CAASK,IAAI,CAAC,KAAK,QAAQ,IAEpC,OAAQL,CAAC,CAASK,IAAI,CAAC,KAAK,UAAU,CACzC,IAED,CAACJ,MAAM,CAACM,QAAQ,CA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,CAAC,GAAGqB,GAAG,CAACjC,MAAM;IAClB,OAAOY,CAAC,EAAE,EAAE;MACRqB,GAAG,CAACrB,CAAC,CAAC,GAAGmB,SAAS,CAACC,GAAG,CAACpB,CAAC,CAAC,CAAC;IAC9B;IACA,OAAOqB,GAAG;EACd;EACA,IAAMC,IAAS,GAAG,CAAC,CAAC;EACpB;EACA,KAAK,IAAM5B,GAAG,IAAI0B,GAAG,EAAE;IACnB;IACA;IACA,IAAIA,GAAG,CAAC1B,GAAG,CAAC,YAAYuB,MAAM,EAAE;MAC5BK,IAAI,CAAC5B,GAAG,CAAC,GAAG0B,GAAG,CAAC1B,GAAG,CAAC;IACxB,CAAC,MAAM;MACH4B,IAAI,CAAC5B,GAAG,CAAC,GAAGyB,SAAS,CAACC,GAAG,CAAC1B,GAAG,CAAC,CAAC;IACnC;EACJ;EACA,OAAO4B,IAAI;AACf;AACO,IAAMC,KAAK,GAAGJ,SAAS;;AAI9B;AACA;AACA;AACA;AAHA;AAIO,SAASK,yBAAyB,CACrCnC,GAAQ,EACRoC,UAAkB,EAClBC,KAAgB,EACP;EACThD,MAAM,CAACiD,cAAc,CAACtC,GAAG,EAAEoC,UAAU,EAAE;IACnCG,GAAG,EAAE,eAAY;MACb,OAAOF,KAAK;IAChB;EACJ,CAAC,CAAC;EACF,OAAOA,KAAK;AAChB;;AAIA;AACA;AACA;AACA;AACO,SAASG,eAAe,CAACnC,GAAW,EAAEgC,KAAU,EAAE;EACrD,IAAIA,KAAK,YAAYT,MAAM,EAAE;IACzB,OAAOS,KAAK,CAACI,QAAQ,EAAE;EAC3B;EACA,OAAOJ,KAAK;AAChB"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-other.js b/dist/lib/plugins/utils/utils-other.js new file mode 100644 index 00000000000..e28716e5e6c --- /dev/null +++ b/dist/lib/plugins/utils/utils-other.js @@ -0,0 +1,56 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RXJS_SHARE_REPLAY_DEFAULTS = void 0; +exports.ensureInteger = ensureInteger; +exports.ensureNotFalsy = ensureNotFalsy; +exports.getFromMapOrFill = getFromMapOrFill; +exports.getFromMapOrThrow = getFromMapOrThrow; +exports.runXTimes = runXTimes; +function runXTimes(xTimes, fn) { + new Array(xTimes).fill(0).forEach(function (_v, idx) { + return fn(idx); + }); +} +function ensureNotFalsy(obj) { + if (!obj) { + throw new Error('ensureNotFalsy() is falsy'); + } + return obj; +} +function ensureInteger(obj) { + if (!Number.isInteger(obj)) { + throw new Error('ensureInteger() is falsy'); + } + return obj; +} +function getFromMapOrThrow(map, key) { + var val = map.get(key); + if (typeof val === 'undefined') { + throw new Error('missing value from map ' + key); + } + return val; +} +function getFromMapOrFill(map, key, fillerFunction) { + var value = map.get(key); + if (!value) { + value = fillerFunction(); + map.set(key, value); + } + return value; +} + +/** + * Using shareReplay() without settings will not unsubscribe + * if there are no more subscribers. + * So we use these defaults. + * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95 + */ +var RXJS_SHARE_REPLAY_DEFAULTS = { + bufferSize: 1, + refCount: true +}; +exports.RXJS_SHARE_REPLAY_DEFAULTS = RXJS_SHARE_REPLAY_DEFAULTS; +//# sourceMappingURL=utils-other.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-other.js.map b/dist/lib/plugins/utils/utils-other.js.map new file mode 100644 index 00000000000..61aa7992050 --- /dev/null +++ b/dist/lib/plugins/utils/utils-other.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-other.js","names":["runXTimes","xTimes","fn","Array","fill","forEach","_v","idx","ensureNotFalsy","obj","Error","ensureInteger","Number","isInteger","getFromMapOrThrow","map","key","val","get","getFromMapOrFill","fillerFunction","value","set","RXJS_SHARE_REPLAY_DEFAULTS","bufferSize","refCount"],"sources":["../../../../src/plugins/utils/utils-other.ts"],"sourcesContent":["export function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null): T {\n if (!obj) {\n throw new Error('ensureNotFalsy() is falsy');\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n\nexport function getFromMapOrThrow(map: Map | WeakMap, key: K): V {\n const val = map.get(key);\n if (typeof val === 'undefined') {\n throw new Error('missing value from map ' + key);\n }\n return val;\n}\n\nexport function getFromMapOrFill(\n map: Map | WeakMap,\n key: K,\n fillerFunction: () => V\n): V {\n let value = map.get(key);\n if (!value) {\n value = fillerFunction();\n map.set(key, value);\n }\n return value;\n}\n\n\n\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n"],"mappings":";;;;;;;;;;;AAAO,SAASA,SAAS,CAACC,MAAc,EAAEC,EAAyB,EAAE;EACjE,IAAIC,KAAK,CAACF,MAAM,CAAC,CAACG,IAAI,CAAC,CAAC,CAAC,CAACC,OAAO,CAAC,UAACC,EAAE,EAAEC,GAAG;IAAA,OAAKL,EAAE,CAACK,GAAG,CAAC;EAAA,EAAC;AAC3D;AAEO,SAASC,cAAc,CAAIC,GAAiC,EAAK;EACpE,IAAI,CAACA,GAAG,EAAE;IACN,MAAM,IAAIC,KAAK,CAAC,2BAA2B,CAAC;EAChD;EACA,OAAOD,GAAG;AACd;AAEO,SAASE,aAAa,CAACF,GAAY,EAAU;EAChD,IAAI,CAACG,MAAM,CAACC,SAAS,CAACJ,GAAG,CAAC,EAAE;IACxB,MAAM,IAAIC,KAAK,CAAC,0BAA0B,CAAC;EAC/C;EACA,OAAOD,GAAG;AACd;AAGO,SAASK,iBAAiB,CAAOC,GAAgC,EAAEC,GAAM,EAAK;EACjF,IAAMC,GAAG,GAAGF,GAAG,CAACG,GAAG,CAACF,GAAG,CAAC;EACxB,IAAI,OAAOC,GAAG,KAAK,WAAW,EAAE;IAC5B,MAAM,IAAIP,KAAK,CAAC,yBAAyB,GAAGM,GAAG,CAAC;EACpD;EACA,OAAOC,GAAG;AACd;AAEO,SAASE,gBAAgB,CAC5BJ,GAAgC,EAChCC,GAAM,EACNI,cAAuB,EACtB;EACD,IAAIC,KAAK,GAAGN,GAAG,CAACG,GAAG,CAACF,GAAG,CAAC;EACxB,IAAI,CAACK,KAAK,EAAE;IACRA,KAAK,GAAGD,cAAc,EAAE;IACxBL,GAAG,CAACO,GAAG,CAACN,GAAG,EAAEK,KAAK,CAAC;EACvB;EACA,OAAOA,KAAK;AAChB;;AAKA;AACA;AACA;AACA;AACA;AACA;AACO,IAAME,0BAA0B,GAAG;EACtCC,UAAU,EAAE,CAAC;EACbC,QAAQ,EAAE;AACd,CAAC;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-promise.js b/dist/lib/plugins/utils/utils-promise.js new file mode 100644 index 00000000000..a8b0525126a --- /dev/null +++ b/dist/lib/plugins/utils/utils-promise.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PROMISE_RESOLVE_VOID = exports.PROMISE_RESOLVE_TRUE = exports.PROMISE_RESOLVE_NULL = exports.PROMISE_RESOLVE_FALSE = void 0; +exports.nextTick = nextTick; +exports.promiseSeries = promiseSeries; +exports.promiseWait = promiseWait; +exports.requestIdleCallbackIfAvailable = requestIdleCallbackIfAvailable; +exports.requestIdlePromise = requestIdlePromise; +exports.toPromise = toPromise; +/** + * returns a promise that resolves on the next tick + */ +function nextTick() { + return new Promise(function (res) { + return setTimeout(res, 0); + }); +} +function promiseWait() { + var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + return new Promise(function (res) { + return setTimeout(res, ms); + }); +} +function toPromise(maybePromise) { + if (maybePromise && typeof maybePromise.then === 'function') { + // is promise + return maybePromise; + } else { + return Promise.resolve(maybePromise); + } +} +var PROMISE_RESOLVE_TRUE = Promise.resolve(true); +exports.PROMISE_RESOLVE_TRUE = PROMISE_RESOLVE_TRUE; +var PROMISE_RESOLVE_FALSE = Promise.resolve(false); +exports.PROMISE_RESOLVE_FALSE = PROMISE_RESOLVE_FALSE; +var PROMISE_RESOLVE_NULL = Promise.resolve(null); +exports.PROMISE_RESOLVE_NULL = PROMISE_RESOLVE_NULL; +var PROMISE_RESOLVE_VOID = Promise.resolve(); +exports.PROMISE_RESOLVE_VOID = PROMISE_RESOLVE_VOID; +function requestIdlePromise() { + var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + if (typeof window === 'object' && window['requestIdleCallback']) { + return new Promise(function (res) { + return window['requestIdleCallback'](res, { + timeout: timeout + }); + }); + } else { + return promiseWait(0); + } +} + +/** + * run the callback if requestIdleCallback available + * do nothing if not + * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback + */ +function requestIdleCallbackIfAvailable(fun) { + if (typeof window === 'object' && window['requestIdleCallback']) window['requestIdleCallback'](fun); +} + +/** + * like Promise.all() but runs in series instead of parallel + * @link https://github.com/egoist/promise.series/blob/master/index.js + * @param tasks array with functions that return a promise + */ +function promiseSeries(tasks, initial) { + return tasks.reduce(function (current, next) { + return current.then(next); + }, Promise.resolve(initial)); +} +//# sourceMappingURL=utils-promise.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-promise.js.map b/dist/lib/plugins/utils/utils-promise.js.map new file mode 100644 index 00000000000..9261573aaeb --- /dev/null +++ b/dist/lib/plugins/utils/utils-promise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-promise.js","names":["nextTick","Promise","res","setTimeout","promiseWait","ms","toPromise","maybePromise","then","resolve","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_NULL","PROMISE_RESOLVE_VOID","requestIdlePromise","timeout","window","requestIdleCallbackIfAvailable","fun","promiseSeries","tasks","initial","reduce","current","next"],"sources":["../../../../src/plugins/utils/utils-promise.ts"],"sourcesContent":["/**\n * returns a promise that resolves on the next tick\n */\nexport function nextTick(): Promise {\n return new Promise(res => setTimeout(res, 0));\n}\n\nexport function promiseWait(ms: number = 0): Promise {\n return new Promise(res => setTimeout(res, ms));\n}\n\nexport function toPromise(maybePromise: Promise | T): Promise {\n if (maybePromise && typeof (maybePromise as any).then === 'function') {\n // is promise\n return maybePromise as any;\n } else {\n return Promise.resolve(maybePromise);\n }\n}\n\n\nexport const PROMISE_RESOLVE_TRUE: Promise = Promise.resolve(true);\nexport const PROMISE_RESOLVE_FALSE: Promise = Promise.resolve(false);\nexport const PROMISE_RESOLVE_NULL: Promise = Promise.resolve(null);\nexport const PROMISE_RESOLVE_VOID: Promise = Promise.resolve();\n\n\nexport function requestIdlePromise(timeout: number | null = null) {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) {\n return new Promise(\n res => (window as any)['requestIdleCallback'](res, {\n timeout\n })\n );\n } else {\n return promiseWait(0);\n }\n}\n\n\n/**\n * run the callback if requestIdleCallback available\n * do nothing if not\n * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback\n */\nexport function requestIdleCallbackIfAvailable(fun: Function): void {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) (window as any)['requestIdleCallback'](fun);\n}\n\n\n/**\n * like Promise.all() but runs in series instead of parallel\n * @link https://github.com/egoist/promise.series/blob/master/index.js\n * @param tasks array with functions that return a promise\n */\nexport function promiseSeries(\n tasks: Function[],\n initial?: any\n): Promise {\n return tasks\n .reduce(\n (current, next) => (current as any).then(next),\n Promise.resolve(initial)\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AACA;AACA;AACO,SAASA,QAAQ,GAAkB;EACtC,OAAO,IAAIC,OAAO,CAAC,UAAAC,GAAG;IAAA,OAAIC,UAAU,CAACD,GAAG,EAAE,CAAC,CAA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;AAGA;AACA;AACA;AACA;AACA;AACO,SAASC,aAAa,CACzBC,KAAiB,EACjBC,OAAa,EACC;EACd,OAAOD,KAAK,CACPE,MAAM,CACH,UAACC,OAAO,EAAEC,IAAI;IAAA,OAAMD,OAAO,CAASf,IAAI,CAACgB,IAAI,CAAC;EAAA,GAC9CvB,OAAO,CAACQ,OAAO,CAACY,OAAO,CAAC,CAC3B;AACT"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-revision.js b/dist/lib/plugins/utils/utils-revision.js new file mode 100644 index 00000000000..bbcdf6d9ba9 --- /dev/null +++ b/dist/lib/plugins/utils/utils-revision.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createRevision = createRevision; +exports.getHeightOfRevision = getHeightOfRevision; +exports.parseRevision = parseRevision; +function parseRevision(revision) { + var split = revision.split('-'); + return { + height: parseInt(split[0], 10), + hash: split[1] + }; +} +function getHeightOfRevision(revision) { + return parseRevision(revision).height; +} + +/** + * Creates the next write revision for a given document. + */ +function createRevision(databaseInstanceToken, previousDocData) { + var previousRevision = previousDocData ? previousDocData._rev : null; + var previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0; + var newRevisionHeight = previousRevisionHeigth + 1; + return newRevisionHeight + '-' + databaseInstanceToken; +} +//# sourceMappingURL=utils-revision.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-revision.js.map b/dist/lib/plugins/utils/utils-revision.js.map new file mode 100644 index 00000000000..3448b3e0eab --- /dev/null +++ b/dist/lib/plugins/utils/utils-revision.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-revision.js","names":["parseRevision","revision","split","height","parseInt","hash","getHeightOfRevision","createRevision","databaseInstanceToken","previousDocData","previousRevision","_rev","previousRevisionHeigth","newRevisionHeight"],"sources":["../../../../src/plugins/utils/utils-revision.ts"],"sourcesContent":["import type {\n RxDocumentData\n} from '../../types';\n\nexport function parseRevision(revision: string): { height: number; hash: string; } {\n const split = revision.split('-');\n return {\n height: parseInt(split[0], 10),\n hash: split[1]\n };\n}\n\nexport function getHeightOfRevision(revision: string): number {\n return parseRevision(revision).height;\n}\n\n/**\n * Creates the next write revision for a given document.\n */\nexport function createRevision(\n databaseInstanceToken: string,\n previousDocData?: RxDocumentData\n): string {\n const previousRevision = previousDocData ? previousDocData._rev : null;\n const previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0;\n const newRevisionHeight = previousRevisionHeigth + 1;\n return newRevisionHeight + '-' + databaseInstanceToken;\n}\n\n"],"mappings":";;;;;;;;AAIO,SAASA,aAAa,CAACC,QAAgB,EAAqC;EAC/E,IAAMC,KAAK,GAAGD,QAAQ,CAACC,KAAK,CAAC,GAAG,CAAC;EACjC,OAAO;IACHC,MAAM,EAAEC,QAAQ,CAACF,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAC9BG,IAAI,EAAEH,KAAK,CAAC,CAAC;EACjB,CAAC;AACL;AAEO,SAASI,mBAAmB,CAACL,QAAgB,EAAU;EAC1D,OAAOD,aAAa,CAACC,QAAQ,CAAC,CAACE,MAAM;AACzC;;AAEA;AACA;AACA;AACO,SAASI,cAAc,CAC1BC,qBAA6B,EAC7BC,eAA2C,EACrC;EACN,IAAMC,gBAAgB,GAAGD,eAAe,GAAGA,eAAe,CAACE,IAAI,GAAG,IAAI;EACtE,IAAMC,sBAAsB,GAAGF,gBAAgB,GAAGV,aAAa,CAACU,gBAAgB,CAAC,CAACP,MAAM,GAAG,CAAC;EAC5F,IAAMU,iBAAiB,GAAGD,sBAAsB,GAAG,CAAC;EACpD,OAAOC,iBAAiB,GAAG,GAAG,GAAGL,qBAAqB;AAC1D"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-string.js b/dist/lib/plugins/utils/utils-string.js new file mode 100644 index 00000000000..321228a5c71 --- /dev/null +++ b/dist/lib/plugins/utils/utils-string.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RANDOM_STRING = void 0; +exports.isFolderPath = isFolderPath; +exports.randomCouchString = randomCouchString; +exports.trimDots = trimDots; +exports.ucfirst = ucfirst; +/** + * get a random string which can be used with couchdb + * @link http://stackoverflow.com/a/1349426/3443137 + */ +function randomCouchString() { + var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; + var text = ''; + var possible = 'abcdefghijklmnopqrstuvwxyz'; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} + +/** + * A random string that is never inside of any storage + */ +var RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX'; + +/** + * uppercase first char + */ +exports.RANDOM_STRING = RANDOM_STRING; +function ucfirst(str) { + str += ''; + var f = str.charAt(0).toUpperCase(); + return f + str.substr(1); +} + +/** + * removes trailing and ending dots from the string + */ +function trimDots(str) { + // start + while (str.charAt(0) === '.') str = str.substr(1); + + // end + while (str.slice(-1) === '.') str = str.slice(0, -1); + return str; +} + +/** + * returns true if the given name is likely a folder path + */ +function isFolderPath(name) { + // do not check, if foldername is given + if (name.includes('/') || + // unix + name.includes('\\') // windows + ) { + return true; + } else { + return false; + } +} +//# sourceMappingURL=utils-string.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-string.js.map b/dist/lib/plugins/utils/utils-string.js.map new file mode 100644 index 00000000000..5a116bae162 --- /dev/null +++ b/dist/lib/plugins/utils/utils-string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-string.js","names":["randomCouchString","length","text","possible","i","charAt","Math","floor","random","RANDOM_STRING","ucfirst","str","f","toUpperCase","substr","trimDots","slice","isFolderPath","name","includes"],"sources":["../../../../src/plugins/utils/utils-string.ts"],"sourcesContent":["/**\n * get a random string which can be used with couchdb\n * @link http://stackoverflow.com/a/1349426/3443137\n */\nexport function randomCouchString(length: number = 10): string {\n let text = '';\n const possible = 'abcdefghijklmnopqrstuvwxyz';\n\n for (let i = 0; i < length; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n\n return text;\n}\n\n\n/**\n * A random string that is never inside of any storage\n */\nexport const RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX';\n\n/**\n * uppercase first char\n */\nexport function ucfirst(str: string): string {\n str += '';\n const f = str.charAt(0)\n .toUpperCase();\n return f + str.substr(1);\n}\n\n/**\n * removes trailing and ending dots from the string\n */\nexport function trimDots(str: string): string {\n // start\n while (str.charAt(0) === '.')\n str = str.substr(1);\n\n // end\n while (str.slice(-1) === '.')\n str = str.slice(0, -1);\n\n return str;\n}\n\n/**\n * returns true if the given name is likely a folder path\n */\nexport function isFolderPath(name: string) {\n // do not check, if foldername is given\n if (\n name.includes('/') || // unix\n name.includes('\\\\') // windows\n ) {\n return true;\n } else {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACA;AACO,SAASA,iBAAiB,GAA8B;EAAA,IAA7BC,MAAc,uEAAG,EAAE;EACjD,IAAIC,IAAI,GAAG,EAAE;EACb,IAAMC,QAAQ,GAAG,4BAA4B;EAE7C,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGH,MAAM,EAAEG,CAAC,EAAE,EAAE;IAC7BF,IAAI,IAAIC,QAAQ,CAACE,MAAM,CAACC,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,MAAM,EAAE,GAAGL,QAAQ,CAACF,MAAM,CAAC,CAAC;EACxE;EAEA,OAAOC,IAAI;AACf;;AAGA;AACA;AACA;AACO,IAAMO,aAAa,GAAG,kCAAkC;;AAE/D;AACA;AACA;AAFA;AAGO,SAASC,OAAO,CAACC,GAAW,EAAU;EACzCA,GAAG,IAAI,EAAE;EACT,IAAMC,CAAC,GAAGD,GAAG,CAACN,MAAM,CAAC,CAAC,CAAC,CAClBQ,WAAW,EAAE;EAClB,OAAOD,CAAC,GAAGD,GAAG,CAACG,MAAM,CAAC,CAAC,CAAC;AAC5B;;AAEA;AACA;AACA;AACO,SAASC,QAAQ,CAACJ,GAAW,EAAU;EAC1C;EACA,OAAOA,GAAG,CAACN,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EACxBM,GAAG,GAAGA,GAAG,CAACG,MAAM,CAAC,CAAC,CAAC;;EAEvB;EACA,OAAOH,GAAG,CAACK,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EACxBL,GAAG,GAAGA,GAAG,CAACK,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EAE1B,OAAOL,GAAG;AACd;;AAEA;AACA;AACA;AACO,SAASM,YAAY,CAACC,IAAY,EAAE;EACvC;EACA,IACIA,IAAI,CAACC,QAAQ,CAAC,GAAG,CAAC;EAAI;EACtBD,IAAI,CAACC,QAAQ,CAAC,IAAI,CAAC,CAAC;EAAA,EACtB;IACE,OAAO,IAAI;EACf,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-time.js b/dist/lib/plugins/utils/utils-time.js new file mode 100644 index 00000000000..484230cdb89 --- /dev/null +++ b/dist/lib/plugins/utils/utils-time.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.now = now; +/** + * Returns the current unix time in milliseconds (with two decmials!) + * Because the accuracy of getTime() in javascript is bad, + * and we cannot rely on performance.now() on all platforms, + * this method implements a way to never return the same value twice. + * This ensures that when now() is called often, we do not loose the information + * about which call came first and which came after. + * + * We had to move from having no decimals, to having two decimal + * because it turned out that some storages are such fast that + * calling this method too often would return 'the future'. + */ +var _lastNow = 0; +/** + * Returns the current time in milliseconds, + * also ensures to not return the same value twice. + */ +function now() { + var ret = new Date().getTime(); + ret = ret + 0.01; + if (ret <= _lastNow) { + ret = _lastNow + 0.01; + } + + /** + * Strip the returned number to max two decimals. + * In theory we would not need this but + * in practice JavaScript has no such good number precision + * so rounding errors could add another decimal place. + */ + var twoDecimals = parseFloat(ret.toFixed(2)); + _lastNow = twoDecimals; + return twoDecimals; +} +//# sourceMappingURL=utils-time.js.map \ No newline at end of file diff --git a/dist/lib/plugins/utils/utils-time.js.map b/dist/lib/plugins/utils/utils-time.js.map new file mode 100644 index 00000000000..f1bb9c58e9b --- /dev/null +++ b/dist/lib/plugins/utils/utils-time.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-time.js","names":["_lastNow","now","ret","Date","getTime","twoDecimals","parseFloat","toFixed"],"sources":["../../../../src/plugins/utils/utils-time.ts"],"sourcesContent":["\n/**\n * Returns the current unix time in milliseconds (with two decmials!)\n * Because the accuracy of getTime() in javascript is bad,\n * and we cannot rely on performance.now() on all platforms,\n * this method implements a way to never return the same value twice.\n * This ensures that when now() is called often, we do not loose the information\n * about which call came first and which came after.\n *\n * We had to move from having no decimals, to having two decimal\n * because it turned out that some storages are such fast that\n * calling this method too often would return 'the future'.\n */\nlet _lastNow: number = 0;\n/**\n * Returns the current time in milliseconds,\n * also ensures to not return the same value twice.\n */\nexport function now(): number {\n let ret = new Date().getTime();\n ret = ret + 0.01;\n if (ret <= _lastNow) {\n ret = _lastNow + 0.01;\n }\n\n /**\n * Strip the returned number to max two decimals.\n * In theory we would not need this but\n * in practice JavaScript has no such good number precision\n * so rounding errors could add another decimal place.\n */\n const twoDecimals = parseFloat(ret.toFixed(2));\n\n _lastNow = twoDecimals;\n return twoDecimals;\n}\n"],"mappings":";;;;;;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIA,QAAgB,GAAG,CAAC;AACxB;AACA;AACA;AACA;AACO,SAASC,GAAG,GAAW;EAC1B,IAAIC,GAAG,GAAG,IAAIC,IAAI,EAAE,CAACC,OAAO,EAAE;EAC9BF,GAAG,GAAGA,GAAG,GAAG,IAAI;EAChB,IAAIA,GAAG,IAAIF,QAAQ,EAAE;IACjBE,GAAG,GAAGF,QAAQ,GAAG,IAAI;EACzB;;EAEA;AACJ;AACA;AACA;AACA;AACA;EACI,IAAMK,WAAW,GAAGC,UAAU,CAACJ,GAAG,CAACK,OAAO,CAAC,CAAC,CAAC,CAAC;EAE9CP,QAAQ,GAAGK,WAAW;EACtB,OAAOA,WAAW;AACtB"} \ No newline at end of file diff --git a/dist/lib/plugins/validate-ajv/index.js b/dist/lib/plugins/validate-ajv/index.js index 954e0491483..97fef23ac9c 100644 --- a/dist/lib/plugins/validate-ajv/index.js +++ b/dist/lib/plugins/validate-ajv/index.js @@ -7,7 +7,6 @@ Object.defineProperty(exports, "__esModule", { exports.getValidator = getValidator; exports.wrappedValidateAjvStorage = void 0; var _ajv = _interopRequireDefault(require("ajv")); -var _rxError = require("../../rx-error"); var _pluginHelpers = require("../../plugin-helpers"); /** * this plugin validates documents before they can be inserted into the RxCollection. @@ -22,12 +21,10 @@ function getValidator(schema) { var validator = ajv.compile(schema); return function (docData) { var isValid = validator(docData); - if (!isValid) { - throw (0, _rxError.newRxError)('VD2', { - errors: validator.errors, - document: docData, - schema: schema - }); + if (isValid) { + return []; + } else { + return validator.errors; } }; } diff --git a/dist/lib/plugins/validate-ajv/index.js.map b/dist/lib/plugins/validate-ajv/index.js.map index da3f9ed85d8..f0335d799c6 100644 --- a/dist/lib/plugins/validate-ajv/index.js.map +++ b/dist/lib/plugins/validate-ajv/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ajv","Ajv","strict","getValidator","schema","validator","compile","docData","isValid","newRxError","errors","document","wrappedValidateAjvStorage","wrappedValidateStorageFactory"],"sources":["../../../../src/plugins/validate-ajv/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using ajv as jsonschema-validator\n * @link https://github.com/epoberezkin/ajv\n */\nimport Ajv from 'ajv';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nconst ajv = new Ajv({\n strict: false\n});\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = ajv.compile(schema);\n return (docData: RxDocumentData) => {\n const isValid = validator(docData);\n if (!isValid) {\n throw newRxError('VD2', {\n errors: validator.errors as any,\n document: docData,\n schema\n });\n }\n };\n}\n\nexport const wrappedValidateAjvStorage = wrappedValidateStorageFactory(\n getValidator,\n 'ajv'\n);\n"],"mappings":";;;;;;;;AAKA;AACA;AAOA;AAbA;AACA;AACA;AACA;AACA;;AAYA,IAAMA,GAAG,GAAG,IAAIC,eAAG,CAAC;EAChBC,MAAM,EAAE;AACZ,CAAC,CAAC;AAGK,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAGL,GAAG,CAACM,OAAO,CAACF,MAAM,CAAC;EACrC,OAAO,UAACG,OAA4B,EAAK;IACrC,IAAMC,OAAO,GAAGH,SAAS,CAACE,OAAO,CAAC;IAClC,IAAI,CAACC,OAAO,EAAE;MACV,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;QACpBC,MAAM,EAAEL,SAAS,CAACK,MAAa;QAC/BC,QAAQ,EAAEJ,OAAO;QACjBH,MAAM,EAANA;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;AACL;AAEO,IAAMQ,yBAAyB,GAAG,IAAAC,4CAA6B,EAClEV,YAAY,EACZ,KAAK,CACR;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ajv","Ajv","strict","getValidator","schema","validator","compile","docData","isValid","errors","wrappedValidateAjvStorage","wrappedValidateStorageFactory"],"sources":["../../../../src/plugins/validate-ajv/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using ajv as jsonschema-validator\n * @link https://github.com/epoberezkin/ajv\n */\nimport Ajv from 'ajv';\nimport type {\n RxDocumentData,\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nconst ajv = new Ajv({\n strict: false\n});\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = ajv.compile(schema);\n return (docData: RxDocumentData) => {\n const isValid = validator(docData);\n if (isValid) {\n return [];\n } else {\n return validator.errors as any;\n }\n };\n}\n\nexport const wrappedValidateAjvStorage = wrappedValidateStorageFactory(\n getValidator,\n 'ajv'\n);\n"],"mappings":";;;;;;;;AAKA;AAKA;AAVA;AACA;AACA;AACA;AACA;;AASA,IAAMA,GAAG,GAAG,IAAIC,eAAG,CAAC;EAChBC,MAAM,EAAE;AACZ,CAAC,CAAC;AAGK,SAASC,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAGL,GAAG,CAACM,OAAO,CAACF,MAAM,CAAC;EACrC,OAAO,UAACG,OAA4B,EAAK;IACrC,IAAMC,OAAO,GAAGH,SAAS,CAACE,OAAO,CAAC;IAClC,IAAIC,OAAO,EAAE;MACT,OAAO,EAAE;IACb,CAAC,MAAM;MACH,OAAOH,SAAS,CAACI,MAAM;IAC3B;EACJ,CAAC;AACL;AAEO,IAAMC,yBAAyB,GAAG,IAAAC,4CAA6B,EAClER,YAAY,EACZ,KAAK,CACR;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/validate-is-my-json-valid/index.js b/dist/lib/plugins/validate-is-my-json-valid/index.js index 698f66c6eeb..fc805a6b61b 100644 --- a/dist/lib/plugins/validate-is-my-json-valid/index.js +++ b/dist/lib/plugins/validate-is-my-json-valid/index.js @@ -7,7 +7,6 @@ Object.defineProperty(exports, "__esModule", { exports.getValidator = getValidator; exports.wrappedValidateIsMyJsonValidStorage = void 0; var _isMyJsonValid = _interopRequireDefault(require("is-my-json-valid")); -var _rxError = require("../../rx-error"); var _pluginHelpers = require("../../plugin-helpers"); /** * this plugin validates documents before they can be inserted into the RxCollection. @@ -19,12 +18,10 @@ function getValidator(schema) { var validator = (0, _isMyJsonValid["default"])(schema); return function (docData) { var isValid = validator(docData); - if (!isValid) { - throw (0, _rxError.newRxError)('VD2', { - errors: validator.errors, - document: docData, - schema: schema - }); + if (isValid) { + return []; + } else { + return validator.errors; } }; } diff --git a/dist/lib/plugins/validate-is-my-json-valid/index.js.map b/dist/lib/plugins/validate-is-my-json-valid/index.js.map index c74c0cbecb6..f0b8b55bf5f 100644 --- a/dist/lib/plugins/validate-is-my-json-valid/index.js.map +++ b/dist/lib/plugins/validate-is-my-json-valid/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["getValidator","schema","validator","isMyJsonValid","docData","isValid","newRxError","errors","document","wrappedValidateIsMyJsonValidStorage","wrappedValidateStorageFactory"],"sources":["../../../../src/plugins/validate-is-my-json-valid/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using is-my-json-valid as jsonschema-validator\n * @link https://github.com/mafintosh/is-my-json-valid\n */\nimport isMyJsonValid from 'is-my-json-valid';\nimport {\n newRxError\n} from '../../rx-error';\nimport type {\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = isMyJsonValid(schema as any);\n return (docData: any) => {\n const isValid = validator(docData);\n if (!isValid) {\n throw newRxError('VD2', {\n errors: validator.errors,\n document: docData,\n schema\n });\n }\n };\n}\n\nexport const wrappedValidateIsMyJsonValidStorage = wrappedValidateStorageFactory(\n getValidator,\n 'is-my-json-valid'\n);\n"],"mappings":";;;;;;;;AAKA;AACA;AAMA;AAZA;AACA;AACA;AACA;AACA;;AAWO,SAASA,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAG,IAAAC,yBAAa,EAACF,MAAM,CAAQ;EAC9C,OAAO,UAACG,OAAY,EAAK;IACrB,IAAMC,OAAO,GAAGH,SAAS,CAACE,OAAO,CAAC;IAClC,IAAI,CAACC,OAAO,EAAE;MACV,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;QACpBC,MAAM,EAAEL,SAAS,CAACK,MAAM;QACxBC,QAAQ,EAAEJ,OAAO;QACjBH,MAAM,EAANA;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;AACL;AAEO,IAAMQ,mCAAmC,GAAG,IAAAC,4CAA6B,EAC5EV,YAAY,EACZ,kBAAkB,CACrB;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["getValidator","schema","validator","isMyJsonValid","docData","isValid","errors","wrappedValidateIsMyJsonValidStorage","wrappedValidateStorageFactory"],"sources":["../../../../src/plugins/validate-is-my-json-valid/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using is-my-json-valid as jsonschema-validator\n * @link https://github.com/mafintosh/is-my-json-valid\n */\nimport isMyJsonValid from 'is-my-json-valid';\nimport type {\n RxJsonSchema\n} from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validator = isMyJsonValid(schema as any);\n return (docData: any) => {\n const isValid = validator(docData);\n if (isValid) {\n return [];\n } else {\n return validator.errors as any;\n }\n };\n}\n\nexport const wrappedValidateIsMyJsonValidStorage = wrappedValidateStorageFactory(\n getValidator,\n 'is-my-json-valid'\n);\n"],"mappings":";;;;;;;;AAKA;AAIA;AATA;AACA;AACA;AACA;AACA;;AAQO,SAASA,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,SAAS,GAAG,IAAAC,yBAAa,EAACF,MAAM,CAAQ;EAC9C,OAAO,UAACG,OAAY,EAAK;IACrB,IAAMC,OAAO,GAAGH,SAAS,CAACE,OAAO,CAAC;IAClC,IAAIC,OAAO,EAAE;MACT,OAAO,EAAE;IACb,CAAC,MAAM;MACH,OAAOH,SAAS,CAACI,MAAM;IAC3B;EACJ,CAAC;AACL;AAEO,IAAMC,mCAAmC,GAAG,IAAAC,4CAA6B,EAC5ER,YAAY,EACZ,kBAAkB,CACrB;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/validate-z-schema/index.js b/dist/lib/plugins/validate-z-schema/index.js index f81f6de0a5a..c32a010abae 100644 --- a/dist/lib/plugins/validate-z-schema/index.js +++ b/dist/lib/plugins/validate-z-schema/index.js @@ -7,7 +7,6 @@ Object.defineProperty(exports, "__esModule", { exports.getValidator = getValidator; exports.wrappedValidateZSchemaStorage = void 0; var _zSchema = _interopRequireDefault(require("z-schema")); -var _rxError = require("../../rx-error"); var _pluginHelpers = require("../../plugin-helpers"); /** * this plugin validates documents before they can be inserted into the RxCollection. @@ -38,11 +37,9 @@ function getValidator(schema) { message: message }; }); - throw (0, _rxError.newRxError)('VD2', { - errors: formattedZSchemaErrors, - document: docData, - schema: schema - }); + return formattedZSchemaErrors; + } else { + return []; } }; } diff --git a/dist/lib/plugins/validate-z-schema/index.js.map b/dist/lib/plugins/validate-z-schema/index.js.map index f06bb6fd597..a8b53bdbbb6 100644 --- a/dist/lib/plugins/validate-z-schema/index.js.map +++ b/dist/lib/plugins/validate-z-schema/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["getValidator","schema","validatorInstance","ZSchema","validator","obj","validate","docData","useValidator","errors","getLastErrors","formattedZSchemaErrors","map","title","description","message","newRxError","document","wrappedValidateZSchemaStorage","wrappedValidateStorageFactory"],"sources":["../../../../src/plugins/validate-z-schema/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using z-schema as jsonschema-validator\n * @link https://github.com/zaggino/z-schema\n */\nimport ZSchema from 'z-schema';\nimport {\n newRxError\n} from '../../rx-error';\nimport type { RxJsonSchema } from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validatorInstance = new (ZSchema as any)();\n const validator = (obj: any) => {\n validatorInstance.validate(obj, schema);\n return validatorInstance;\n };\n return (docData: any) => {\n const useValidator = validator(docData);\n if (useValidator === true) {\n return;\n }\n const errors: ZSchema.SchemaErrorDetail[] = (useValidator as any).getLastErrors();\n if (errors) {\n const formattedZSchemaErrors = (errors as any).map(({\n title,\n description,\n message\n }: any) => ({\n title,\n description,\n message\n }));\n throw newRxError('VD2', {\n errors: formattedZSchemaErrors,\n document: docData,\n schema\n });\n }\n };\n}\n\nexport const wrappedValidateZSchemaStorage = wrappedValidateStorageFactory(\n getValidator,\n 'z-schema'\n);\n"],"mappings":";;;;;;;;AAKA;AACA;AAIA;AAVA;AACA;AACA;AACA;AACA;;AASO,SAASA,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,iBAAiB,GAAG,IAAKC,mBAAO,EAAU;EAChD,IAAMC,SAAS,GAAG,SAAZA,SAAS,CAAIC,GAAQ,EAAK;IAC5BH,iBAAiB,CAACI,QAAQ,CAACD,GAAG,EAAEJ,MAAM,CAAC;IACvC,OAAOC,iBAAiB;EAC5B,CAAC;EACD,OAAO,UAACK,OAAY,EAAK;IACrB,IAAMC,YAAY,GAAGJ,SAAS,CAACG,OAAO,CAAC;IACvC,IAAIC,YAAY,KAAK,IAAI,EAAE;MACvB;IACJ;IACA,IAAMC,MAAmC,GAAID,YAAY,CAASE,aAAa,EAAE;IACjF,IAAID,MAAM,EAAE;MACR,IAAME,sBAAsB,GAAIF,MAAM,CAASG,GAAG,CAAC;QAAA,IAC/CC,KAAK,QAALA,KAAK;UACLC,WAAW,QAAXA,WAAW;UACXC,OAAO,QAAPA,OAAO;QAAA,OACC;UACRF,KAAK,EAALA,KAAK;UACLC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA;QACJ,CAAC;MAAA,CAAC,CAAC;MACH,MAAM,IAAAC,mBAAU,EAAC,KAAK,EAAE;QACpBP,MAAM,EAAEE,sBAAsB;QAC9BM,QAAQ,EAAEV,OAAO;QACjBN,MAAM,EAANA;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;AACL;AAEO,IAAMiB,6BAA6B,GAAG,IAAAC,4CAA6B,EACtEnB,YAAY,EACZ,UAAU,CACb;AAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["getValidator","schema","validatorInstance","ZSchema","validator","obj","validate","docData","useValidator","errors","getLastErrors","formattedZSchemaErrors","map","title","description","message","wrappedValidateZSchemaStorage","wrappedValidateStorageFactory"],"sources":["../../../../src/plugins/validate-z-schema/index.ts"],"sourcesContent":["/**\n * this plugin validates documents before they can be inserted into the RxCollection.\n * It's using z-schema as jsonschema-validator\n * @link https://github.com/zaggino/z-schema\n */\nimport ZSchema from 'z-schema';\nimport type { RxJsonSchema } from '../../types';\nimport { wrappedValidateStorageFactory } from '../../plugin-helpers';\n\n\nexport function getValidator(\n schema: RxJsonSchema\n) {\n const validatorInstance = new (ZSchema as any)();\n const validator = (obj: any) => {\n validatorInstance.validate(obj, schema);\n return validatorInstance;\n };\n return (docData: any) => {\n const useValidator = validator(docData);\n if (useValidator === true) {\n return;\n }\n const errors: ZSchema.SchemaErrorDetail[] = (useValidator as any).getLastErrors();\n if (errors) {\n const formattedZSchemaErrors = (errors as any).map(({\n title,\n description,\n message\n }: any) => ({\n title,\n description,\n message\n }));\n return formattedZSchemaErrors;\n } else {\n return [];\n }\n };\n}\n\nexport const wrappedValidateZSchemaStorage = wrappedValidateStorageFactory(\n getValidator,\n 'z-schema'\n);\n"],"mappings":";;;;;;;;AAKA;AAEA;AAPA;AACA;AACA;AACA;AACA;;AAMO,SAASA,YAAY,CACxBC,MAAyB,EAC3B;EACE,IAAMC,iBAAiB,GAAG,IAAKC,mBAAO,EAAU;EAChD,IAAMC,SAAS,GAAG,SAAZA,SAAS,CAAIC,GAAQ,EAAK;IAC5BH,iBAAiB,CAACI,QAAQ,CAACD,GAAG,EAAEJ,MAAM,CAAC;IACvC,OAAOC,iBAAiB;EAC5B,CAAC;EACD,OAAO,UAACK,OAAY,EAAK;IACrB,IAAMC,YAAY,GAAGJ,SAAS,CAACG,OAAO,CAAC;IACvC,IAAIC,YAAY,KAAK,IAAI,EAAE;MACvB;IACJ;IACA,IAAMC,MAAmC,GAAID,YAAY,CAASE,aAAa,EAAE;IACjF,IAAID,MAAM,EAAE;MACR,IAAME,sBAAsB,GAAIF,MAAM,CAASG,GAAG,CAAC;QAAA,IAC/CC,KAAK,QAALA,KAAK;UACLC,WAAW,QAAXA,WAAW;UACXC,OAAO,QAAPA,OAAO;QAAA,OACC;UACRF,KAAK,EAALA,KAAK;UACLC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA;QACJ,CAAC;MAAA,CAAC,CAAC;MACH,OAAOJ,sBAAsB;IACjC,CAAC,MAAM;MACH,OAAO,EAAE;IACb;EACJ,CAAC;AACL;AAEO,IAAMK,6BAA6B,GAAG,IAAAC,4CAA6B,EACtEjB,YAAY,EACZ,UAAU,CACb;AAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/in-worker.js b/dist/lib/plugins/worker/in-worker.js deleted file mode 100644 index 2cc5d6314cc..00000000000 --- a/dist/lib/plugins/worker/in-worker.js +++ /dev/null @@ -1,83 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wrappedWorkerRxStorage = wrappedWorkerRxStorage; -var _worker = require("threads/worker"); -var _util = require("../../util"); -/** - * This file contains everything - * that is supposed to run inside of the worker. - */ - -function wrappedWorkerRxStorage(args) { - var nextId = 0; - var instanceById = new Map(); - var exposeMe = { - /** - * RxStorageInstance - */ - createStorageInstance: function createStorageInstance(params) { - try { - var _instanceId = nextId++; - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (instance) { - instanceById.set(_instanceId, instance); - return _instanceId; - }); - } catch (e) { - return Promise.reject(e); - } - }, - bulkWrite: function bulkWrite(instanceId, documentWrites, context) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.bulkWrite(documentWrites, context); - }, - findDocumentsById: function findDocumentsById(instanceId, ids, deleted) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.findDocumentsById(ids, deleted); - }, - query: function query(instanceId, preparedQuery) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.query(preparedQuery); - }, - count: function count(instanceId, preparedQuery) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.count(preparedQuery); - }, - getAttachmentData: function getAttachmentData(instanceId, documentId, attachmentId) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.getAttachmentData(documentId, attachmentId); - }, - getChangedDocumentsSince: function getChangedDocumentsSince(instanceId, limit, checkpoint) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.getChangedDocumentsSince(limit, checkpoint); - }, - changeStream: function changeStream(instanceId) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.changeStream(); - }, - cleanup: function cleanup(instanceId, minDeletedTime) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.cleanup(minDeletedTime); - }, - close: function close(instanceId) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.close(); - }, - remove: function remove(instanceId) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.remove(); - }, - conflictResultionTasks: function conflictResultionTasks(instanceId) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.conflictResultionTasks(); - }, - resolveConflictResultionTask: function resolveConflictResultionTask(instanceId, taskSolution) { - var instance = (0, _util.getFromMapOrThrow)(instanceById, instanceId); - return instance.resolveConflictResultionTask(taskSolution); - } - }; - (0, _worker.expose)(exposeMe); -} -//# sourceMappingURL=in-worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/in-worker.js.map b/dist/lib/plugins/worker/in-worker.js.map deleted file mode 100644 index 67ee1b6fa50..00000000000 --- a/dist/lib/plugins/worker/in-worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"in-worker.js","names":["wrappedWorkerRxStorage","args","nextId","instanceById","Map","exposeMe","createStorageInstance","params","instanceId","storage","instance","set","bulkWrite","documentWrites","context","getFromMapOrThrow","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","changeStream","cleanup","minDeletedTime","close","remove","conflictResultionTasks","resolveConflictResultionTask","taskSolution","expose"],"sources":["../../../../src/plugins/worker/in-worker.ts"],"sourcesContent":["/**\n * This file contains everything\n * that is supposed to run inside of the worker.\n */\nimport type {\n BulkWriteRow,\n EventBulk,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxDocumentDataById,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types';\nimport { expose } from 'threads/worker';\nimport { getFromMapOrThrow } from '../../util';\nimport { Observable } from 'rxjs';\n\n\nexport type InWorkerStorage = {\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise;\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise>;\n findDocumentsById(\n instanceId: number,\n ids: string[], deleted: boolean\n ): Promise>;\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise>;\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise;\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise;\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }>;\n changeStream(\n instanceById: number\n ): Observable>, CheckpointType>>;\n cleanup(instanceId: number, minDeletedTime: number): Promise;\n close(instanceId: number): Promise;\n remove(instanceId: number): Promise;\n\n conflictResultionTasks(\n instanceById: number\n ): Observable>;\n resolveConflictResultionTask(\n instanceById: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise;\n};\n\nexport function wrappedWorkerRxStorage(\n args: {\n storage: RxStorage;\n }\n) {\n let nextId = 0;\n const instanceById: Map = new Map();\n\n const exposeMe: InWorkerStorage = {\n /**\n * RxStorageInstance\n */\n async createStorageInstance(params) {\n const instanceId = nextId++;\n const instance = await args.storage.createStorageInstance(params);\n instanceById.set(instanceId, instance);\n return instanceId;\n },\n bulkWrite(\n instanceId: number,\n documentWrites: BulkWriteRow[],\n context: string\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.bulkWrite(documentWrites, context);\n },\n findDocumentsById(\n instanceId: number,\n ids: string[],\n deleted: boolean\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.findDocumentsById(ids, deleted);\n },\n query(\n instanceId: number,\n preparedQuery: any\n ): Promise> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.query(preparedQuery);\n },\n count(\n instanceId: number,\n preparedQuery: any\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.count(preparedQuery);\n },\n getAttachmentData(\n instanceId: number,\n documentId: string,\n attachmentId: string\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getAttachmentData(\n documentId,\n attachmentId\n );\n },\n getChangedDocumentsSince(\n instanceId: number,\n limit: number,\n checkpoint: any\n ): Promise<{\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.getChangedDocumentsSince(\n limit,\n checkpoint\n );\n },\n changeStream(\n instanceId: number\n ): Observable>, CheckpointType>> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.changeStream();\n },\n cleanup(\n instanceId: number,\n minDeletedTime: number\n ) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.cleanup(minDeletedTime);\n },\n close(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.close();\n },\n remove(instanceId: number) {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.remove();\n },\n\n conflictResultionTasks(\n instanceId: number\n ): Observable> {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.conflictResultionTasks();\n },\n resolveConflictResultionTask(\n instanceId: number,\n taskSolution: RxConflictResultionTaskSolution\n ): Promise {\n const instance = getFromMapOrThrow(instanceById, instanceId);\n return instance.resolveConflictResultionTask(taskSolution);\n }\n };\n expose(exposeMe);\n}\n"],"mappings":";;;;;;AAkBA;AACA;AAnBA;AACA;AACA;AACA;;AAsEO,SAASA,sBAAsB,CAClCC,IAEC,EACH;EACE,IAAIC,MAAM,GAAG,CAAC;EACd,IAAMC,YAA8B,GAAG,IAAIC,GAAG,EAAE;EAEhD,IAAMC,QAA8C,GAAG;IACnD;AACR;AACA;IACcC,qBAAqB,iCAACC,MAAM;MAAA,IAAE;QAChC,IAAMC,WAAU,GAAGN,MAAM,EAAE;QAAC,uBACLD,IAAI,CAACQ,OAAO,CAACH,qBAAqB,CAACC,MAAM,CAAC,iBAA3DG,QAAQ;UACdP,YAAY,CAACQ,GAAG,CAACH,WAAU,EAAEE,QAAQ,CAAC;UACtC,OAAOF,WAAU;QAAC;MACtB,CAAC;QAAA;MAAA;IAAA;IACDI,SAAS,qBACLJ,UAAkB,EAClBK,cAA4C,EAC5CC,OAAe,EACjB;MACE,IAAMJ,QAAQ,GAAG,IAAAK,uBAAiB,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACE,SAAS,CAACC,cAAc,EAAEC,OAAO,CAAC;IACtD,CAAC;IACDE,iBAAiB,6BACbR,UAAkB,EAClBS,GAAa,EACbC,OAAgB,EACyB;MACzC,IAAMR,QAAQ,GAAG,IAAAK,uBAAiB,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACM,iBAAiB,CAACC,GAAG,EAAEC,OAAO,CAAC;IACnD,CAAC;IACDC,KAAK,iBACDX,UAAkB,EAClBY,aAAkB,EACyB;MAC3C,IAAMV,QAAQ,GAAG,IAAAK,uBAAiB,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACS,KAAK,CAACC,aAAa,CAAC;IACxC,CAAC;IACDC,KAAK,iBACDb,UAAkB,EAClBY,aAAkB,EACW;MAC7B,IAAMV,QA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,sBAAsB,kCAClBzB,UAAkB,EAC4B;MAC9C,IAAME,QAAQ,GAAG,IAAAK,uBAAiB,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACuB,sBAAsB,EAAE;IAC5C,CAAC;IACDC,4BAA4B,wCACxB1B,UAAkB,EAClB2B,YAAwD,EAC3C;MACb,IAAMzB,QAAQ,GAAG,IAAAK,uBAAiB,EAACZ,YAAY,EAAEK,UAAU,CAAC;MAC5D,OAAOE,QAAQ,CAACwB,4BAA4B,CAACC,YAAY,CAAC;IAC9D;EACJ,CAAC;EACD,IAAAC,cAAM,EAAC/B,QAAQ,CAAC;AACpB"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/index.js.map b/dist/lib/plugins/worker/index.js.map deleted file mode 100644 index 8571397e9a6..00000000000 --- a/dist/lib/plugins/worker/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","names":[],"sources":["../../../../src/plugins/worker/index.ts"],"sourcesContent":["export * from './in-worker';\nexport * from './non-worker';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/non-worker.js.map b/dist/lib/plugins/worker/non-worker.js.map deleted file mode 100644 index a740dcb3342..00000000000 --- a/dist/lib/plugins/worker/non-worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"non-worker.js","names":["removeWorkerRef","instance","workerState","getFromMapOrThrow","WORKER_BY_INSTANCE","storage","refs","size","workerPromise","then","worker","Thread","terminate","Map","RxStorageWorker","settings","statics","name","createStorageInstance","params","get","spawn","Worker","workerInput","Set","set","instanceId","RxStorageInstanceWorker","databaseName","collectionName","schema","rxStorage","options","ensureNotFalsy","add","internals","changes$","Subject","conflicts$","subs","closed","push","changeStream","subscribe","ev","next","conflictResultionTasks","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","getChangedDocumentsSince","limit","checkpoint","asObservable","cleanup","minDeletedTime","close","Promise","reject","Error","forEach","sub","unsubscribe","remove","resolveConflictResultionTask","taskSolution","getRxStorageWorker"],"sources":["../../../../src/plugins/worker/non-worker.ts"],"sourcesContent":["import {\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport {\n spawn,\n Worker,\n Thread\n} from 'threads';\nimport type {\n RxJsonSchema,\n RxStorage,\n RxStorageInstanceCreationParams,\n RxStorageInstance,\n BulkWriteRow,\n RxDocumentData,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageQueryResult,\n EventBulk,\n RxStorageStatics,\n RxDocumentDataById,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxStorageCountResult\n} from '../../types';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from '../../util';\nimport { InWorkerStorage } from './in-worker';\n\ndeclare type WorkerStorageInternals = {\n rxStorage: RxStorageWorker;\n instanceId: number;\n worker: InWorkerStorage;\n};\ndeclare type RxStorageWorkerSettings = {\n statics: RxStorageStatics;\n workerInput: any;\n};\n\n\n/**\n * We have no way to detect if a worker is no longer needed.\n * So we create the worker process on the first RxStorageInstance\n * and have to close it again of no more RxStorageInstances are non-closed.\n */\nconst WORKER_BY_INSTANCE: Map>;\n refs: Set>;\n}> = new Map();\n\nexport class RxStorageWorker implements RxStorage {\n public name = 'worker';\n\n constructor(\n public readonly settings: RxStorageWorkerSettings,\n public readonly statics: RxStorageStatics\n ) { }\n\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n let workerState = WORKER_BY_INSTANCE.get(this);\n if (!workerState) {\n workerState = {\n workerPromise: spawn>(new Worker(this.settings.workerInput)) as any,\n refs: new Set()\n };\n WORKER_BY_INSTANCE.set(this, workerState);\n }\n\n return workerState.workerPromise.then(worker => {\n return worker.createStorageInstance(params)\n .then(instanceId => {\n const instance = new RxStorageInstanceWorker(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n rxStorage: this,\n instanceId,\n worker\n },\n params.options\n );\n ensureNotFalsy(workerState).refs.add(instance);\n return instance;\n });\n });\n }\n}\n\n\nexport class RxStorageInstanceWorker implements RxStorageInstance {\n /**\n * threads.js uses observable-fns instead of rxjs\n * so we have to transform it.\n */\n private changes$: Subject>, any>> = new Subject();\n private conflicts$: Subject> = new Subject();\n private subs: Subscription[] = [];\n\n private closed: boolean = false;\n\n constructor(\n public readonly storage: RxStorageWorker,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: WorkerStorageInternals,\n public readonly options: Readonly\n ) {\n this.subs.push(\n this.internals.worker.changeStream(\n this.internals.instanceId\n ).subscribe(ev => this.changes$.next(ev as any))\n );\n this.subs.push(\n this.internals.worker.conflictResultionTasks(\n this.internals.instanceId\n ).subscribe(ev => this.conflicts$.next(ev as any))\n );\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.internals.worker.bulkWrite(\n this.internals.instanceId,\n documentWrites,\n context\n );\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise> {\n return this.internals.worker.findDocumentsById(\n this.internals.instanceId,\n ids,\n deleted\n );\n }\n query(preparedQuery: any): Promise> {\n return this.internals.worker.query(\n this.internals.instanceId,\n preparedQuery\n );\n }\n count(preparedQuery: any): Promise {\n return this.internals.worker.count(\n this.internals.instanceId,\n preparedQuery\n );\n }\n getAttachmentData(documentId: string, attachmentId: string): Promise {\n return this.internals.worker.getAttachmentData(\n this.internals.instanceId,\n documentId,\n attachmentId\n );\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ) {\n return this.internals.worker.getChangedDocumentsSince(\n this.internals.instanceId,\n limit,\n checkpoint\n );\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number) {\n return this.internals.worker.cleanup(\n this.internals.instanceId,\n minDeletedTime\n );\n }\n async close(): Promise {\n if (this.closed) {\n return Promise.reject(new Error('already closed'));\n }\n this.closed = true;\n this.subs.forEach(sub => sub.unsubscribe());\n await this.internals.worker.close(\n this.internals.instanceId\n );\n await removeWorkerRef(this);\n }\n async remove(): Promise {\n await this.internals.worker.remove(\n this.internals.instanceId\n );\n this.closed = true;\n await removeWorkerRef(this);\n }\n\n conflictResultionTasks(): Observable> {\n return this.conflicts$;\n }\n async resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise {\n await this.internals.worker.resolveConflictResultionTask(\n this.internals.instanceId,\n taskSolution\n );\n }\n\n}\n\nexport function getRxStorageWorker(\n settings: RxStorageWorkerSettings\n): RxStorageWorker {\n const storage = new RxStorageWorker(settings, settings.statics);\n return storage;\n}\n\n/**\n * TODO we have a bug.\n * When the exact same RxStorage opens and closes\n * many RxStorage instances, then it might happen\n * that some calls to createStorageInstance() time out,\n * because the worker thread is in the closing state.\n */\nexport async function removeWorkerRef(\n instance: RxStorageInstanceWorker\n) {\n const workerState = getFromMapOrThrow(WORKER_BY_INSTANCE, instance.storage);\n workerState.refs.delete(instance);\n if (workerState.refs.size === 0) {\n WORKER_BY_INSTANCE.delete(instance.storage);\n await workerState.workerPromise\n .then(worker => Thread.terminate(worker as any));\n }\n}\n"],"mappings":";;;;;;;;AAAA;AAKA;AAsBA;AAkMA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOsBA,eAAe,YAAfA,eAAe,CACjCC,QAAsC;EAAA,IACxC;IACE,IAAMC,WAAW,GAAG,IAAAC,uBAAiB,EAACC,kBAAkB,EAAEH,QAAQ,CAACI,OAAO,CAAC;IAC3EH,WAAW,CAACI,IAAI,UAAO,CAACL,QAAQ,CAAC;IAAC;MAAA,IAC9BC,WAAW,CAACI,IAAI,CAACC,IAAI,KAAK,CAAC;QAC3BH,kBAAkB,UAAO,CAACH,QAAQ,CAACI,OAAO,CAAC;QAAC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AAG,IAAIS,eAAe,CAACC,QAAQ,EAAEA,QAAQ,CAACC,OAAO,CAAC;EAC/D,OAAOX,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/dexie-memory.worker.js.map b/dist/lib/plugins/worker/workers/dexie-memory.worker.js.map deleted file mode 100644 index ffadf03d47c..00000000000 --- a/dist/lib/plugins/worker/workers/dexie-memory.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie-memory.worker.js","names":["storage","getRxStorageDexie","indexedDB","IDBKeyRange","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/dexie-memory.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../dexie';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nimport {\n indexedDB,\n IDBKeyRange\n} from 'fake-indexeddb';\n\nconst storage = getRxStorageDexie({\n indexedDB,\n IDBKeyRange\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA;AAKA,IAAMA,OAAO,GAAG,IAAAC,wBAAiB,EAAC;EAC9BC,SAAS,EAATA,wBAAS;EACTC,WAAW,EAAXA;AACJ,CAAC,CAAC;AACF,IAAAC,8BAAsB,EAAC;EACnBJ,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/dexie.worker.js b/dist/lib/plugins/worker/workers/dexie.worker.js deleted file mode 100644 index ef5c8b1252e..00000000000 --- a/dist/lib/plugins/worker/workers/dexie.worker.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -var _dexie = require("../../dexie"); -var _worker = require("../../worker"); -var storage = (0, _dexie.getRxStorageDexie)(); -(0, _worker.wrappedWorkerRxStorage)({ - storage: storage -}); -//# sourceMappingURL=dexie.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/dexie.worker.js.map b/dist/lib/plugins/worker/workers/dexie.worker.js.map deleted file mode 100644 index c0b4b250854..00000000000 --- a/dist/lib/plugins/worker/workers/dexie.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dexie.worker.js","names":["storage","getRxStorageDexie","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/dexie.worker.ts"],"sourcesContent":["import { getRxStorageDexie } from '../../dexie';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nconst storage = getRxStorageDexie();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAMA,OAAO,GAAG,IAAAC,wBAAiB,GAAE;AACnC,IAAAC,8BAAsB,EAAC;EACnBF,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-fs.worker.js b/dist/lib/plugins/worker/workers/lokijs-fs.worker.js deleted file mode 100644 index 22e621beff6..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-fs.worker.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; - -var _lokijs = require("../../lokijs"); -var _worker = require("../../worker"); -var lfsa = require('lokijs/src/loki-fs-structured-adapter.js'); -var adapter = new lfsa(); -var storage = (0, _lokijs.getRxStorageLoki)({ - adapter: adapter -}); -(0, _worker.wrappedWorkerRxStorage)({ - storage: storage -}); -//# sourceMappingURL=lokijs-fs.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-fs.worker.js.map b/dist/lib/plugins/worker/workers/lokijs-fs.worker.js.map deleted file mode 100644 index 8cba969bee4..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-fs.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-fs.worker.js","names":["lfsa","require","adapter","storage","getRxStorageLoki","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/lokijs-fs.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nconst lfsa = require('lokijs/src/loki-fs-structured-adapter.js');\nconst adapter = new lfsa();\nconst storage = getRxStorageLoki({\n adapter\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAMA,IAAI,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAChE,IAAMC,OAAO,GAAG,IAAIF,IAAI,EAAE;AAC1B,IAAMG,OAAO,GAAG,IAAAC,wBAAgB,EAAC;EAC7BF,OAAO,EAAPA;AACJ,CAAC,CAAC;AACF,IAAAG,8BAAsB,EAAC;EACnBF,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js.map b/dist/lib/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js.map deleted file mode 100644 index b486b3f42c3..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-incremental-indexeddb.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-incremental-indexeddb.worker.js","names":["LokiIncrementalIndexedDBAdapter","require","storage","getRxStorageLoki","adapter","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/lokijs-incremental-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\nconst LokiIncrementalIndexedDBAdapter = require('lokijs/src/incremental-indexeddb-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIncrementalIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AACA,IAAMA,+BAA+B,GAAGC,OAAO,CAAC,0CAA0C,CAAC;AAE3F,IAAMC,OAAO,GAAG,IAAAC,wBAAgB,EAAC;EAC7BC,OAAO,EAAE,IAAIJ,+BAA+B;AAChD,CAAC,CAAC;AACF,IAAAK,8BAAsB,EAAC;EACnBH,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-indexeddb.worker.js b/dist/lib/plugins/worker/workers/lokijs-indexeddb.worker.js deleted file mode 100644 index dec7486fa0f..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-indexeddb.worker.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -var _lokijs = require("../../lokijs"); -var _worker = require("../../worker"); -var LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter'); -var storage = (0, _lokijs.getRxStorageLoki)({ - adapter: new LokiIndexedDBAdapter() -}); -(0, _worker.wrappedWorkerRxStorage)({ - storage: storage -}); -//# sourceMappingURL=lokijs-indexeddb.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-indexeddb.worker.js.map b/dist/lib/plugins/worker/workers/lokijs-indexeddb.worker.js.map deleted file mode 100644 index 31f399f29b4..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-indexeddb.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-indexeddb.worker.js","names":["LokiIndexedDBAdapter","require","storage","getRxStorageLoki","adapter","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/lokijs-indexeddb.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\nconst LokiIndexedDBAdapter = require('lokijs/src/loki-indexed-adapter');\n\nconst storage = getRxStorageLoki({\n adapter: new LokiIndexedDBAdapter()\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AACA,IAAMA,oBAAoB,GAAGC,OAAO,CAAC,iCAAiC,CAAC;AAEvE,IAAMC,OAAO,GAAG,IAAAC,wBAAgB,EAAC;EAC7BC,OAAO,EAAE,IAAIJ,oBAAoB;AACrC,CAAC,CAAC;AACF,IAAAK,8BAAsB,EAAC;EACnBH,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-memory.worker.js b/dist/lib/plugins/worker/workers/lokijs-memory.worker.js deleted file mode 100644 index d71d0e2c2ca..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-memory.worker.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -var _lokijs = require("../../lokijs"); -var _worker = require("../../worker"); -var storage = (0, _lokijs.getRxStorageLoki)(); -(0, _worker.wrappedWorkerRxStorage)({ - storage: storage -}); -//# sourceMappingURL=lokijs-memory.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/lokijs-memory.worker.js.map b/dist/lib/plugins/worker/workers/lokijs-memory.worker.js.map deleted file mode 100644 index 723eb49f775..00000000000 --- a/dist/lib/plugins/worker/workers/lokijs-memory.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"lokijs-memory.worker.js","names":["storage","getRxStorageLoki","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/lokijs-memory.worker.ts"],"sourcesContent":["import { getRxStorageLoki } from '../../lokijs';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\nconst storage = getRxStorageLoki();\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAMA,OAAO,GAAG,IAAAC,wBAAgB,GAAE;AAClC,IAAAC,8BAAsB,EAAC;EACnBF,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/pouchdb-idb.worker.js b/dist/lib/plugins/worker/workers/pouchdb-idb.worker.js deleted file mode 100644 index 20db340c05e..00000000000 --- a/dist/lib/plugins/worker/workers/pouchdb-idb.worker.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -var _pouchdb = require("../../pouchdb"); -var _worker = require("../../worker"); -(0, _pouchdb.addPouchPlugin)(require('pouchdb-adapter-idb')); -var storage = (0, _pouchdb.getRxStoragePouch)({ - adapter: 'idb' -}); -(0, _worker.wrappedWorkerRxStorage)({ - storage: storage -}); -//# sourceMappingURL=pouchdb-idb.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/pouchdb-idb.worker.js.map b/dist/lib/plugins/worker/workers/pouchdb-idb.worker.js.map deleted file mode 100644 index f6963a030e8..00000000000 --- a/dist/lib/plugins/worker/workers/pouchdb-idb.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-idb.worker.js","names":["addPouchPlugin","require","storage","getRxStoragePouch","adapter","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/pouchdb-idb.worker.ts"],"sourcesContent":["import { getRxStoragePouch, addPouchPlugin } from '../../pouchdb';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\naddPouchPlugin(require('pouchdb-adapter-idb'));\nconst storage = getRxStoragePouch({\n adapter: 'idb'\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAAA,uBAAc,EAACC,OAAO,CAAC,qBAAqB,CAAC,CAAC;AAC9C,IAAMC,OAAO,GAAG,IAAAC,0BAAiB,EAAC;EAC9BC,OAAO,EAAE;AACb,CAAC,CAAC;AACF,IAAAC,8BAAsB,EAAC;EACnBH,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/pouchdb-memory.worker.js b/dist/lib/plugins/worker/workers/pouchdb-memory.worker.js deleted file mode 100644 index 69aaa303305..00000000000 --- a/dist/lib/plugins/worker/workers/pouchdb-memory.worker.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -var _pouchdb = require("../../pouchdb"); -var _worker = require("../../worker"); -(0, _pouchdb.addPouchPlugin)(require('pouchdb-adapter-memory')); -var storage = (0, _pouchdb.getRxStoragePouch)({ - adapter: 'memory' -}); -(0, _worker.wrappedWorkerRxStorage)({ - storage: storage -}); -//# sourceMappingURL=pouchdb-memory.worker.js.map \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/pouchdb-memory.worker.js.map b/dist/lib/plugins/worker/workers/pouchdb-memory.worker.js.map deleted file mode 100644 index 28a47dbb111..00000000000 --- a/dist/lib/plugins/worker/workers/pouchdb-memory.worker.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-memory.worker.js","names":["addPouchPlugin","require","storage","getRxStoragePouch","adapter","wrappedWorkerRxStorage"],"sources":["../../../../../src/plugins/worker/workers/pouchdb-memory.worker.ts"],"sourcesContent":["import { getRxStoragePouch, addPouchPlugin } from '../../pouchdb';\nimport { wrappedWorkerRxStorage } from '../../worker';\n\naddPouchPlugin(require('pouchdb-adapter-memory'));\nconst storage = getRxStoragePouch({\n adapter: 'memory'\n});\nwrappedWorkerRxStorage({\n storage\n});\n"],"mappings":";;AAAA;AACA;AAEA,IAAAA,uBAAc,EAACC,OAAO,CAAC,wBAAwB,CAAC,CAAC;AACjD,IAAMC,OAAO,GAAG,IAAAC,0BAAiB,EAAC;EAC9BC,OAAO,EAAE;AACb,CAAC,CAAC;AACF,IAAAC,8BAAsB,EAAC;EACnBH,OAAO,EAAPA;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/lib/plugins/worker/workers/webpack.config.js.map b/dist/lib/plugins/worker/workers/webpack.config.js.map deleted file mode 100644 index d86cf46a034..00000000000 --- a/dist/lib/plugins/worker/workers/webpack.config.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"webpack.config.js","names":["path","require","TerserPlugin","projectRootPath","resolve","__dirname","babelConfig","module","exports","entry","output","filename","clean","mode","cache","type","cacheDirectory","devtool","rules","test","exclude","use","loader","options","extensions","fallback","fs","optimization","moduleIds","minimize","minimizer","terserOptions","format","comments","extractComments"],"sources":["../../../../../src/plugins/worker/workers/webpack.config.js"],"sourcesContent":["const path = require('path');\nconst TerserPlugin = require('terser-webpack-plugin');\n\nconst projectRootPath = path.resolve(\n __dirname,\n '../../../../'\n);\n\nconst babelConfig = require('../../../../babel.config');\nmodule.exports = {\n entry: {\n 'lokijs-incremental-indexeddb': './src/plugins/worker/workers/lokijs-incremental-indexeddb.worker.ts',\n 'lokijs-indexeddb': './src/plugins/worker/workers/lokijs-indexeddb.worker.ts',\n 'lokijs-memory': './src/plugins/worker/workers/lokijs-memory.worker.ts',\n 'lokijs-fs': './src/plugins/worker/workers/lokijs-fs.worker.ts',\n 'pouchdb-idb': './src/plugins/worker/workers/pouchdb-idb.worker.ts',\n 'pouchdb-memory': './src/plugins/worker/workers/pouchdb-memory.worker.ts',\n 'dexie': './src/plugins/worker/workers/dexie.worker.ts',\n 'dexie-memory': './src/plugins/worker/workers/dexie-memory.worker.ts'\n },\n output: {\n filename: '[name].worker.js',\n clean: true,\n path: path.resolve(\n projectRootPath,\n 'dist/workers'\n ),\n },\n mode: 'production',\n cache: {\n type: 'filesystem',\n cacheDirectory: path.resolve(\n projectRootPath,\n 'test_tmp',\n 'webpack-cache-worker'\n ),\n },\n devtool: 'source-map',\n module: {\n rules: [\n /**\n * We transpile the typscript via babel instead of ts-loader.\n * This ensures we have the exact same babel config\n * as the root RxDB project.\n */\n {\n test: /\\.tsx?$/,\n exclude: /(node_modules)/,\n use: {\n loader: 'babel-loader',\n options: babelConfig\n },\n }\n ],\n },\n resolve: {\n extensions: ['.tsx', '.ts', '.js'],\n /**\n * Fix LokiJS bundle error\n * @link https://rxdb.info/rx-storage-lokijs.html\n */\n fallback: {\n fs: false\n }\n },\n optimization: {\n moduleIds: 'deterministic',\n minimize: true,\n minimizer: [new TerserPlugin({\n terserOptions: {\n format: {\n comments: false,\n },\n },\n /**\n * Disable creating the license files.\n * @link https://github.com/webpack/webpack/issues/12506#issuecomment-789314176\n */\n extractComments: false,\n })],\n }\n};\n"],"mappings":";;AAAA,IAAMA,IAAI,GAAGC,OAAO,CAAC,MAAM,CAAC;AAC5B,IAAMC,YAAY,GAAGD,OAAO,CAAC,uBAAuB,CAAC;AAErD,IAAME,eAAe,GAAGH,IAAI,CAACI,OAAO,CAChCC,SAAS,EACT,cAAc,CACjB;AAED,IAAMC,WAAW,GAAGL,OAAO,CAAC,0BAA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CAAC"} \ No newline at end of file diff --git a/dist/lib/query-cache.js b/dist/lib/query-cache.js index 48684595c92..74544f0558d 100644 --- a/dist/lib/query-cache.js +++ b/dist/lib/query-cache.js @@ -9,7 +9,7 @@ exports.createQueryCache = createQueryCache; exports.defaultCacheReplacementPolicyMonad = exports.defaultCacheReplacementPolicy = void 0; exports.triggerCacheReplacement = triggerCacheReplacement; exports.uncacheRxQuery = uncacheRxQuery; -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * the query-cache makes sure that on every query-state, exactly one instance can exist * if you use the same mango-query more then once, it will reuse the first RxQuery @@ -61,7 +61,7 @@ var defaultCacheReplacementPolicyMonad = function defaultCacheReplacementPolicyM if (queryCache._map.size < tryToKeepMax) { return; } - var minUnExecutedLifetime = (0, _util.now)() - unExecutedLifetime; + var minUnExecutedLifetime = (0, _utils.now)() - unExecutedLifetime; var maybeUncash = []; var queriesInCache = Array.from(queryCache._map.values()); for (var _i = 0, _queriesInCache = queriesInCache; _i < _queriesInCache.length; _i++) { @@ -112,9 +112,9 @@ function triggerCacheReplacement(rxCollection) { /** * Do not run directly to not reduce result latency of a new query */ - (0, _util.nextTick)() // wait at least one tick + (0, _utils.nextTick)() // wait at least one tick .then(function () { - return (0, _util.requestIdlePromise)(200); + return (0, _utils.requestIdlePromise)(200); }) // and then wait for the CPU to be idle .then(function () { if (!rxCollection.destroyed) { diff --git a/dist/lib/query-cache.js.map b/dist/lib/query-cache.js.map index c072eddefc5..23244171b78 100644 --- a/dist/lib/query-cache.js.map +++ b/dist/lib/query-cache.js.map @@ -1 +1 @@ -{"version":3,"file":"query-cache.js","names":["QueryCache","_map","Map","getByQuery","rxQuery","stringRep","toString","has","set","get","createQueryCache","uncacheRxQuery","queryCache","uncached","countRxQuerySubscribers","refCount$","observers","length","DEFAULT_TRY_TO_KEEP_MAX","DEFAULT_UNEXECUTED_LIFETME","defaultCacheReplacementPolicyMonad","tryToKeepMax","unExecutedLifetime","_collection","size","minUnExecutedLifetime","now","maybeUncash","queriesInCache","Array","from","values","_lastEnsureEqual","_creationTime","push","mustUncache","sortedByLastUsage","sort","a","b","toRemove","slice","forEach","defaultCacheReplacementPolicy","COLLECTIONS_WITH_RUNNING_CLEANUP","WeakSet","triggerCacheReplacement","rxCollection","add","nextTick","then","requestIdlePromise","destroyed","cacheReplacementPolicy","_queryCache"],"sources":["../../src/query-cache.ts"],"sourcesContent":["/**\n * the query-cache makes sure that on every query-state, exactly one instance can exist\n * if you use the same mango-query more then once, it will reuse the first RxQuery\n */\nimport type {\n RxQuery,\n RxCacheReplacementPolicy,\n RxCollection\n} from './types';\nimport {\n nextTick,\n now,\n requestIdlePromise\n} from './util';\n\nexport class QueryCache {\n public _map: Map = new Map();\n\n /**\n * check if an equal query is in the cache,\n * if true, return the cached one,\n * if false, save the given one and return it\n */\n getByQuery(rxQuery: RxQuery): RxQuery {\n const stringRep = rxQuery.toString();\n if (!this._map.has(stringRep)) {\n this._map.set(stringRep, rxQuery);\n }\n return this._map.get(stringRep) as RxQuery;\n }\n}\n\nexport function createQueryCache() {\n return new QueryCache();\n}\n\n\nexport function uncacheRxQuery(queryCache: QueryCache, rxQuery: RxQuery) {\n rxQuery.uncached = true;\n const stringRep = rxQuery.toString();\n queryCache._map.delete(stringRep);\n\n}\n\n\nexport function countRxQuerySubscribers(rxQuery: RxQuery): number {\n return rxQuery.refCount$.observers.length;\n}\n\n\nexport const DEFAULT_TRY_TO_KEEP_MAX = 100;\nexport const DEFAULT_UNEXECUTED_LIFETME = 30 * 1000;\n\n/**\n * The default cache replacement policy\n * See docs-src/query-cache.md to learn how it should work.\n * Notice that this runs often and should block the cpu as less as possible\n * This is a monad which makes it easier to unit test\n */\nexport const defaultCacheReplacementPolicyMonad: (\n tryToKeepMax: number,\n unExecutedLifetime: number\n) => RxCacheReplacementPolicy = (\n tryToKeepMax,\n unExecutedLifetime\n) => (\n _collection: RxCollection,\n queryCache: QueryCache\n) => {\n if (queryCache._map.size < tryToKeepMax) {\n return;\n }\n\n const minUnExecutedLifetime = now() - unExecutedLifetime;\n const maybeUncash: RxQuery[] = [];\n\n const queriesInCache = Array.from(queryCache._map.values());\n for (const rxQuery of queriesInCache) {\n // filter out queries with subscribers\n if (countRxQuerySubscribers(rxQuery) > 0) {\n continue;\n }\n // directly uncache queries that never executed and are older then unExecutedLifetime\n if (rxQuery._lastEnsureEqual === 0 && rxQuery._creationTime < minUnExecutedLifetime) {\n uncacheRxQuery(queryCache, rxQuery);\n continue;\n }\n maybeUncash.push(rxQuery);\n }\n\n const mustUncache = maybeUncash.length - tryToKeepMax;\n if (mustUncache <= 0) {\n return;\n }\n\n const sortedByLastUsage = maybeUncash.sort((a, b) => a._lastEnsureEqual - b._lastEnsureEqual);\n const toRemove = sortedByLastUsage.slice(0, mustUncache);\n toRemove.forEach(rxQuery => uncacheRxQuery(queryCache, rxQuery));\n};\n\n\nexport const defaultCacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicyMonad(\n DEFAULT_TRY_TO_KEEP_MAX,\n DEFAULT_UNEXECUTED_LIFETME\n);\n\nexport const COLLECTIONS_WITH_RUNNING_CLEANUP: WeakSet = new WeakSet();\n\n/**\n * Triggers the cache replacement policy after waitTime has passed.\n * We do not run this directly because at exactly the time a query is created,\n * we need all CPU to minimize latency.\n * Also this should not be triggered multiple times when waitTime is still waiting.\n */\nexport function triggerCacheReplacement(\n rxCollection: RxCollection\n) {\n if (COLLECTIONS_WITH_RUNNING_CLEANUP.has(rxCollection)) {\n // already started\n return;\n }\n\n COLLECTIONS_WITH_RUNNING_CLEANUP.add(rxCollection);\n\n /**\n * Do not run directly to not reduce result latency of a new query\n */\n nextTick() // wait at least one tick\n .then(() => requestIdlePromise(200)) // and then wait for the CPU to be idle\n .then(() => {\n if (!rxCollection.destroyed) {\n rxCollection.cacheReplacementPolicy(rxCollection, rxCollection._queryCache);\n }\n COLLECTIONS_WITH_RUNNING_CLEANUP.delete(rxCollection);\n });\n}\n"],"mappings":";;;;;;;;;;;AASA;AAT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CAACD,YAAY,CAAC;;EAElD;AACJ;AACA;EACI,IAAAE,cAAQ,GAAE,CAAC;EAAA,CACNC,IAAI,CAAC;IAAA,OAAM,IAAAC,wBAAkB,EAAC,GAAG,CAAC;EAAA,EAAC,CAAC;EAAA,CACpCD,IAAI,CAAC,YAAM;IACR,IAAI,CAACH,YAAY,CAACK,SAAS,EAAE;MACzBL,YAAY,CAACM,sBAAsB,CAACN,YAAY,EAAEA,YAAY,CAACO,WAAW,CAAC;IAC/E;IACAV,gCAAgC,UAAO,CAACG,YAAY,CAAC;EACzD,CAAC,CAAC;AACV"} \ No newline at end of file +{"version":3,"file":"query-cache.js","names":["QueryCache","_map","Map","getByQuery","rxQuery","stringRep","toString","has","set","get","createQueryCache","uncacheRxQuery","queryCache","uncached","countRxQuerySubscribers","refCount$","observers","length","DEFAULT_TRY_TO_KEEP_MAX","DEFAULT_UNEXECUTED_LIFETME","defaultCacheReplacementPolicyMonad","tryToKeepMax","unExecutedLifetime","_collection","size","minUnExecutedLifetime","now","maybeUncash","queriesInCache","Array","from","values","_lastEnsureEqual","_creationTime","push","mustUncache","sortedByLastUsage","sort","a","b","toRemove","slice","forEach","defaultCacheReplacementPolicy","COLLECTIONS_WITH_RUNNING_CLEANUP","WeakSet","triggerCacheReplacement","rxCollection","add","nextTick","then","requestIdlePromise","destroyed","cacheReplacementPolicy","_queryCache"],"sources":["../../src/query-cache.ts"],"sourcesContent":["/**\n * the query-cache makes sure that on every query-state, exactly one instance can exist\n * if you use the same mango-query more then once, it will reuse the first RxQuery\n */\nimport type {\n RxQuery,\n RxCacheReplacementPolicy,\n RxCollection\n} from './types';\nimport {\n nextTick,\n now,\n requestIdlePromise\n} from './plugins/utils';\n\nexport class QueryCache {\n public _map: Map = new Map();\n\n /**\n * check if an equal query is in the cache,\n * if true, return the cached one,\n * if false, save the given one and return it\n */\n getByQuery(rxQuery: RxQuery): RxQuery {\n const stringRep = rxQuery.toString();\n if (!this._map.has(stringRep)) {\n this._map.set(stringRep, rxQuery);\n }\n return this._map.get(stringRep) as RxQuery;\n }\n}\n\nexport function createQueryCache() {\n return new QueryCache();\n}\n\n\nexport function uncacheRxQuery(queryCache: QueryCache, rxQuery: RxQuery) {\n rxQuery.uncached = true;\n const stringRep = rxQuery.toString();\n queryCache._map.delete(stringRep);\n\n}\n\n\nexport function countRxQuerySubscribers(rxQuery: RxQuery): number {\n return rxQuery.refCount$.observers.length;\n}\n\n\nexport const DEFAULT_TRY_TO_KEEP_MAX = 100;\nexport const DEFAULT_UNEXECUTED_LIFETME = 30 * 1000;\n\n/**\n * The default cache replacement policy\n * See docs-src/query-cache.md to learn how it should work.\n * Notice that this runs often and should block the cpu as less as possible\n * This is a monad which makes it easier to unit test\n */\nexport const defaultCacheReplacementPolicyMonad: (\n tryToKeepMax: number,\n unExecutedLifetime: number\n) => RxCacheReplacementPolicy = (\n tryToKeepMax,\n unExecutedLifetime\n) => (\n _collection: RxCollection,\n queryCache: QueryCache\n) => {\n if (queryCache._map.size < tryToKeepMax) {\n return;\n }\n\n const minUnExecutedLifetime = now() - unExecutedLifetime;\n const maybeUncash: RxQuery[] = [];\n\n const queriesInCache = Array.from(queryCache._map.values());\n for (const rxQuery of queriesInCache) {\n // filter out queries with subscribers\n if (countRxQuerySubscribers(rxQuery) > 0) {\n continue;\n }\n // directly uncache queries that never executed and are older then unExecutedLifetime\n if (rxQuery._lastEnsureEqual === 0 && rxQuery._creationTime < minUnExecutedLifetime) {\n uncacheRxQuery(queryCache, rxQuery);\n continue;\n }\n maybeUncash.push(rxQuery);\n }\n\n const mustUncache = maybeUncash.length - tryToKeepMax;\n if (mustUncache <= 0) {\n return;\n }\n\n const sortedByLastUsage = maybeUncash.sort((a, b) => a._lastEnsureEqual - b._lastEnsureEqual);\n const toRemove = sortedByLastUsage.slice(0, mustUncache);\n toRemove.forEach(rxQuery => uncacheRxQuery(queryCache, rxQuery));\n};\n\n\nexport const defaultCacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicyMonad(\n DEFAULT_TRY_TO_KEEP_MAX,\n DEFAULT_UNEXECUTED_LIFETME\n);\n\nexport const COLLECTIONS_WITH_RUNNING_CLEANUP: WeakSet = new WeakSet();\n\n/**\n * Triggers the cache replacement policy after waitTime has passed.\n * We do not run this directly because at exactly the time a query is created,\n * we need all CPU to minimize latency.\n * Also this should not be triggered multiple times when waitTime is still waiting.\n */\nexport function triggerCacheReplacement(\n rxCollection: RxCollection\n) {\n if (COLLECTIONS_WITH_RUNNING_CLEANUP.has(rxCollection)) {\n // already started\n return;\n }\n\n COLLECTIONS_WITH_RUNNING_CLEANUP.add(rxCollection);\n\n /**\n * Do not run directly to not reduce result latency of a new query\n */\n nextTick() // wait at least one tick\n .then(() => requestIdlePromise(200)) // and then wait for the CPU to be idle\n .then(() => {\n if (!rxCollection.destroyed) {\n rxCollection.cacheReplacementPolicy(rxCollection, rxCollection._queryCache);\n }\n COLLECTIONS_WITH_RUNNING_CLEANUP.delete(rxCollection);\n });\n}\n"],"mappings":";;;;;;;;;;;AASA;AATA;AACA;AACA;AACA;AAHA,IAeaA,UAAU;EAAA;IAAA,KACZC,IAAI,GAAyB,IAAIC,GAAG,EAAE;EAAA;EAAA;EAE7C;AACJ;AACA;AACA;AACA;EAJI,OAKAC,UAAU,GAAV,oBAAWC,OAAgB,EAAW;IAClC,IAAMC,SAAS,GAAGD,OAAO,CAACE,QAAQ,EAAE;IACpC,IAAI,CAAC,IAAI,CAACL,IAAI,CAACM,GAAG,CAACF,SAAS,CAAC,EAAE;MAC3B,IAAI,CAACJ,IAAI,CAACO,GAAG,CAACH,SAAS,EAAED,OAAO,CAAC;IACrC;IACA,OAAO,IAAI,CAACH,IAAI,CAACQ,GAAG,CAACJ,SAAS,CAAC;EACnC,CAAC;EAAA;AAAA;AAAA;AAGE,SAASK,gBAAgB,GAAG;EAC/B,OAAO,IAAIV,UAAU,EAAE;AAC3B;AAGO,SAASW,cAAc,CAACC,UAAsB,EAAER,OAAgB,EAAE;EACrEA,OAA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IAAI,CAAC,UAACC,CAAC,EAAEC,CAAC;MAAA,OAAKD,CAAC,CAACN,gBAAgB,GAAGO,CAAC,CAACP,gBAAgB;IAAA,EAAC;IAC7F,IAAMQ,QAAQ,GAAGJ,iBAAiB,CAACK,KAAK,CAAC,CAAC,EAAEN,WAAW,CAAC;IACxDK,QAAQ,CAACE,OAAO,CAAC,UAAAtC,OAAO;MAAA,OAAIO,cAAc,CAACC,UAAU,EAAER,OAAO,CAAC;IAAA,EAAC;EACpE,CAAC;AAAA;AAAC;AAGK,IAAMuC,6BAAuD,GAAGvB,kCAAkC,CACrGF,uBAAuB,EACvBC,0BAA0B,CAC7B;AAAC;AAEK,IAAMyB,gCAAuD,GAAG,IAAIC,OAAO,EAAE;;AAEpF;AACA;AACA;AACA;AACA;AACA;AALA;AAMO,SAASC,uBAAuB,CACnCC,YAA0B,EAC5B;EACE,IAAIH,gCAAgC,CAACrC,GAAG,CAACwC,YAAY,CAAC,EAAE;IACpD;IACA;EACJ;EAEAH,gCAAgC,CAACI,GAAG,CAACD,YAAY,CAAC;;EAElD;AACJ;AACA;EACI,IAAAE,eAAQ,GAAE,CAAC;EAAA,CACNC,IAAI,CAAC;IAAA,OAAM,IAAAC,yBAAkB,EAAC,GAAG,CAAC;EAAA,EAAC,CAAC;EAAA,CACpCD,IAAI,CAAC,YAAM;IACR,IAAI,CAACH,YAAY,CAACK,SAAS,EAAE;MACzBL,YAAY,CAACM,sBAAsB,CAACN,YAAY,EAAEA,YAAY,CAACO,WAAW,CAAC;IAC/E;IACAV,gCAAgC,UAAO,CAACG,YAAY,CAAC;EACzD,CAAC,CAAC;AACV"} \ No newline at end of file diff --git a/dist/lib/query-planner.js.map b/dist/lib/query-planner.js.map index 779cfce2f81..54abe187993 100644 --- a/dist/lib/query-planner.js.map +++ b/dist/lib/query-planner.js.map @@ -1 +1 @@ -{"version":3,"file":"query-planner.js","names":["INDEX_MAX","String","fromCharCode","INDEX_MIN","Infinity","getQueryPlan","schema","query","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","selector","indexes","slice","index","push","optimalSortIndex","sort","map","sortField","Object","keys","optimalSortIndexCompareString","join","hasDescSorting","find","values","currentBestQuality","currentBestQueryPlan","forEach","inclusiveEnd","inclusiveStart","opts","indexField","matcher","operators","matcherOpts","length","startKey","endKey","operator","LOGICAL_OPERATORS","has","operatorValue","partialOpts","getMatcherQueryOpts","assign","queryPlan","startKeys","opt","endKeys","sortFieldsSameAsIndexFields","selectorSatisfiedByIndex","isSelectorSatisfiedByIndex","quality","rateQueryPlan","Set","LOWER_BOUND_LOGICAL_OPERATORS","UPPER_BOUND_LOGICAL_OPERATORS","selectorEntries","entries","hasNonMatchingOperator","fieldName","operation","includes","hasNonLogicOperator","op","_value","prevLowerBoundaryField","hasMoreThenOneLowerBoundaryField","hasLowerLogicOp","key","prevUpperBoundaryField","hasMoreThenOneUpperBoundaryField","hasUpperLogicOp","Error","pointsPerMatchingKey","idxOfFirstMinStartKey","findIndex","keyValue","idxOfFirstMaxEndKey","pointsIfNoReSortMustBeDone"],"sources":["../../src/query-planner.ts"],"sourcesContent":["import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxJsonSchema,\n RxQueryPlan,\n RxQueryPlanerOpts\n} from './types';\n\n\nexport const INDEX_MAX = String.fromCharCode(65535);\nexport const INDEX_MIN = -Infinity;\n\n/**\n * Returns the query plan which contains\n * information about how to run the query\n * and which indexes to use.\n *\n * This is used in some storage like Memory, dexie.js and IndexedDB.\n */\nexport function getQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): RxQueryPlan {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const selector = query.selector;\n\n let indexes: string[][] = schema.indexes ? schema.indexes.slice(0) as any : [];\n if (query.index) {\n indexes = [query.index];\n } else {\n indexes.push([primaryPath]);\n }\n\n const optimalSortIndex = query.sort.map(sortField => Object.keys(sortField)[0]);\n const optimalSortIndexCompareString = optimalSortIndex.join(',');\n /**\n * Most storages do not support descending indexes\n * so having a 'desc' in the sorting, means we always have to re-sort the results.\n */\n const hasDescSorting = !!query.sort.find(sortField => Object.values(sortField)[0] === 'desc');\n\n let currentBestQuality = -1;\n let currentBestQueryPlan: RxQueryPlan | undefined;\n\n indexes.forEach((index) => {\n let inclusiveEnd = true;\n let inclusiveStart = true;\n const opts: RxQueryPlanerOpts[] = index.map(indexField => {\n const matcher = selector[indexField];\n const operators = matcher ? Object.keys(matcher) : [];\n\n let matcherOpts: RxQueryPlanerOpts = {} as any;\n\n if (\n !matcher ||\n !operators.length\n ) {\n matcherOpts = {\n startKey: inclusiveStart ? INDEX_MIN : INDEX_MAX,\n endKey: inclusiveEnd ? INDEX_MAX : INDEX_MIN,\n inclusiveStart: true,\n inclusiveEnd: true\n };\n } else {\n operators.forEach(operator => {\n if (LOGICAL_OPERATORS.has(operator)) {\n const operatorValue = matcher[operator];\n const partialOpts = getMatcherQueryOpts(operator, operatorValue);\n matcherOpts = Object.assign(matcherOpts, partialOpts);\n }\n });\n }\n\n // fill missing attributes\n if (typeof matcherOpts.startKey === 'undefined') {\n matcherOpts.startKey = INDEX_MIN;\n }\n if (typeof matcherOpts.endKey === 'undefined') {\n matcherOpts.endKey = INDEX_MAX;\n }\n if (typeof matcherOpts.inclusiveStart === 'undefined') {\n matcherOpts.inclusiveStart = true;\n }\n if (typeof matcherOpts.inclusiveEnd === 'undefined') {\n matcherOpts.inclusiveEnd = true;\n }\n\n\n if (inclusiveStart && !matcherOpts.inclusiveStart) {\n inclusiveStart = false;\n }\n if (inclusiveEnd && !matcherOpts.inclusiveEnd) {\n inclusiveEnd = false;\n }\n\n return matcherOpts;\n });\n\n const queryPlan: RxQueryPlan = {\n index,\n startKeys: opts.map(opt => opt.startKey),\n endKeys: opts.map(opt => opt.endKey),\n inclusiveEnd,\n inclusiveStart,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === index.join(','),\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex(index, query.selector)\n };\n const quality = rateQueryPlan(\n schema,\n query,\n queryPlan\n );\n if (\n (\n quality > 0 &&\n quality > currentBestQuality\n ) ||\n query.index\n ) {\n currentBestQuality = quality;\n currentBestQueryPlan = queryPlan;\n }\n });\n\n /**\n * No index found, use the default index\n */\n if (!currentBestQueryPlan) {\n currentBestQueryPlan = {\n index: [primaryPath],\n startKeys: [INDEX_MIN],\n endKeys: [INDEX_MAX],\n inclusiveEnd: true,\n inclusiveStart: true,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === primaryPath,\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex([primaryPath], query.selector)\n };\n }\n\n return currentBestQueryPlan;\n}\n\nexport const LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte', '$lt', '$lte']);\nexport const LOWER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte']);\nexport const UPPER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$lt', '$lte']);\n\nexport function isSelectorSatisfiedByIndex(\n index: string[],\n selector: MangoQuerySelector\n): boolean {\n const selectorEntries = Object.entries(selector);\n const hasNonMatchingOperator = selectorEntries\n .find(([fieldName, operation]) => {\n if (!index.includes(fieldName)) {\n return true;\n }\n const hasNonLogicOperator = Object.entries(operation)\n .find(([op, _value]) => !LOGICAL_OPERATORS.has(op));\n return hasNonLogicOperator;\n });\n if (hasNonMatchingOperator) {\n return false;\n }\n\n\n let prevLowerBoundaryField: any;\n const hasMoreThenOneLowerBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasLowerLogicOp = Object.keys(operation).find(key => LOWER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevLowerBoundaryField && hasLowerLogicOp) {\n return true;\n } else if (hasLowerLogicOp !== '$eq') {\n prevLowerBoundaryField = hasLowerLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneLowerBoundaryField) {\n return false;\n }\n\n let prevUpperBoundaryField: any;\n const hasMoreThenOneUpperBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasUpperLogicOp = Object.keys(operation).find(key => UPPER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevUpperBoundaryField && hasUpperLogicOp) {\n return true;\n } else if (hasUpperLogicOp !== '$eq') {\n prevUpperBoundaryField = hasUpperLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneUpperBoundaryField) {\n return false;\n }\n\n return true;\n}\n\nexport function getMatcherQueryOpts(\n operator: string,\n operatorValue: any\n): Partial {\n switch (operator) {\n case '$eq':\n return {\n startKey: operatorValue,\n endKey: operatorValue\n };\n case '$lte':\n return {\n endKey: operatorValue\n };\n case '$gte':\n return {\n startKey: operatorValue\n };\n case '$lt':\n return {\n endKey: operatorValue,\n inclusiveEnd: false\n };\n case '$gt':\n return {\n startKey: operatorValue,\n inclusiveStart: false\n };\n default:\n throw new Error('SNH');\n }\n}\n\n\n/**\n * Returns a number that determines the quality of the query plan.\n * Higher number means better query plan.\n */\nexport function rateQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery,\n queryPlan: RxQueryPlan\n): number {\n let quality: number = 0;\n\n const pointsPerMatchingKey = 10;\n const idxOfFirstMinStartKey = queryPlan.startKeys.findIndex(keyValue => keyValue === INDEX_MIN);\n if (idxOfFirstMinStartKey > 0) {\n quality = quality + (idxOfFirstMinStartKey * pointsPerMatchingKey);\n }\n\n const idxOfFirstMaxEndKey = queryPlan.endKeys.findIndex(keyValue => keyValue === INDEX_MAX);\n if (idxOfFirstMaxEndKey > 0) {\n quality = quality + (idxOfFirstMaxEndKey * pointsPerMatchingKey);\n }\n\n const pointsIfNoReSortMustBeDone = 5;\n if (queryPlan.sortFieldsSameAsIndexFields) {\n quality = quality + pointsIfNoReSortMustBeDone;\n }\n\n return quality;\n}\n"],"mappings":";;;;;;;;;;AAAA;AAWO,IAAMA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,CAAC;IACL,KAAK,MAAM;MACP,OAAO;QACHJ,MAAM,EAAEI;MACZ,CAAC;IACL,KAAK,MAAM;MACP,OAAO;QACHL,QAAQ,EAAEK;MACd,CAAC;IACL,KAAK,KAAK;MACN,OAAO;QACHJ,MAAM,EAAEI,aAAa;QACrBb,YAAY,EAAE;MAClB,CAAC;IACL,KAAK,KAAK;MACN,OAAO;QACHQ,QAAQ,EAAEK,aAAa;QACvBZ,cAAc,EAAE;MACpB,CAAC;IACL;MACI,MAAM,IAAI4C,KAAK,CAAC,KAAK,CAAC;EAAC;AAEnC;;AAGA;AACA;AACA;AACA;AACO,SAASpB,aAAa,CACzBjD,MAA+C,EAC/CC,KAAkC,EAClCwC,SAAsB,EAChB;EACN,IAAIO,OAAe,GAAG,CAAC;EAEvB,IAAMsB,oBAAoB,GAAG,EAAE;EAC/B,IAAMC,qBAAqB,GAAG9B,SAAS,CAACC,SAAS,CAAC8B,SAAS,CAAC,UAAAC,QAAQ;IAAA,OAAIA,QAAQ,KAAK5E,SAAS;EAAA,EAAC;EAC/F,IAAI0E,qBAAqB,GAAG,CAAC,EAAE;IAC3BvB,OAAO,GAAGA,OAAO,GAAIuB,qBAAqB,GAAGD,oBAAqB;EACtE;EAEA,IAAMI,mBAAmB,GAAGjC,SAAS,CAACG,OAAO,CAAC4B,SAAS,CAAC,UAAAC,QAAQ;IAAA,OAAIA,QAAQ,KAAK/E,SAAS;EAAA,EAAC;EAC3F,IAAIgF,mBAAmB,GAAG,CAAC,EAAE;IACzB1B,OAAO,GAAGA,OAAO,GAAI0B,mBAAmB,GAAGJ,oBAAqB;EACpE;EAEA,IAAMK,0BAA0B,GAAG,CAAC;EACpC,IAAIlC,SAAS,CAACI,2BAA2B,EAAE;IACvCG,OAAO,GAAGA,OAAO,GAAG2B,0BAA0B;EAClD;EAEA,OAAO3B,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"query-planner.js","names":["INDEX_MAX","String","fromCharCode","INDEX_MIN","Infinity","getQueryPlan","schema","query","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","selector","indexes","slice","index","push","optimalSortIndex","sort","map","sortField","Object","keys","optimalSortIndexCompareString","join","hasDescSorting","find","values","currentBestQuality","currentBestQueryPlan","forEach","inclusiveEnd","inclusiveStart","opts","indexField","matcher","operators","matcherOpts","length","startKey","endKey","operator","LOGICAL_OPERATORS","has","operatorValue","partialOpts","getMatcherQueryOpts","assign","queryPlan","startKeys","opt","endKeys","sortFieldsSameAsIndexFields","selectorSatisfiedByIndex","isSelectorSatisfiedByIndex","quality","rateQueryPlan","Set","LOWER_BOUND_LOGICAL_OPERATORS","UPPER_BOUND_LOGICAL_OPERATORS","selectorEntries","entries","hasNonMatchingOperator","fieldName","operation","includes","hasNonLogicOperator","op","_value","prevLowerBoundaryField","hasMoreThenOneLowerBoundaryField","hasLowerLogicOp","key","prevUpperBoundaryField","hasMoreThenOneUpperBoundaryField","hasUpperLogicOp","Error","pointsPerMatchingKey","idxOfFirstMinStartKey","findIndex","keyValue","idxOfFirstMaxEndKey","pointsIfNoReSortMustBeDone"],"sources":["../../src/query-planner.ts"],"sourcesContent":["import { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxJsonSchema,\n RxQueryPlan,\n RxQueryPlanerOpts\n} from './types';\n\n\nexport const INDEX_MAX = String.fromCharCode(65535);\nexport const INDEX_MIN = -Infinity;\n\n/**\n * Returns the query plan which contains\n * information about how to run the query\n * and which indexes to use.\n *\n * This is used in some storage like Memory, dexie.js and IndexedDB.\n */\nexport function getQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery\n): RxQueryPlan {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const selector = query.selector;\n\n let indexes: string[][] = schema.indexes ? schema.indexes.slice(0) as any : [];\n if (query.index) {\n indexes = [query.index];\n } else {\n indexes.push([primaryPath]);\n }\n\n const optimalSortIndex = query.sort.map(sortField => Object.keys(sortField)[0]);\n const optimalSortIndexCompareString = optimalSortIndex.join(',');\n /**\n * Most storages do not support descending indexes\n * so having a 'desc' in the sorting, means we always have to re-sort the results.\n */\n const hasDescSorting = !!query.sort.find(sortField => Object.values(sortField)[0] === 'desc');\n\n let currentBestQuality = -1;\n let currentBestQueryPlan: RxQueryPlan | undefined;\n\n indexes.forEach((index) => {\n let inclusiveEnd = true;\n let inclusiveStart = true;\n const opts: RxQueryPlanerOpts[] = index.map(indexField => {\n const matcher = (selector as any)[indexField];\n const operators = matcher ? Object.keys(matcher) : [];\n\n let matcherOpts: RxQueryPlanerOpts = {} as any;\n\n if (\n !matcher ||\n !operators.length\n ) {\n matcherOpts = {\n startKey: inclusiveStart ? INDEX_MIN : INDEX_MAX,\n endKey: inclusiveEnd ? INDEX_MAX : INDEX_MIN,\n inclusiveStart: true,\n inclusiveEnd: true\n };\n } else {\n operators.forEach(operator => {\n if (LOGICAL_OPERATORS.has(operator)) {\n const operatorValue = matcher[operator];\n const partialOpts = getMatcherQueryOpts(operator, operatorValue);\n matcherOpts = Object.assign(matcherOpts, partialOpts);\n }\n });\n }\n\n // fill missing attributes\n if (typeof matcherOpts.startKey === 'undefined') {\n matcherOpts.startKey = INDEX_MIN;\n }\n if (typeof matcherOpts.endKey === 'undefined') {\n matcherOpts.endKey = INDEX_MAX;\n }\n if (typeof matcherOpts.inclusiveStart === 'undefined') {\n matcherOpts.inclusiveStart = true;\n }\n if (typeof matcherOpts.inclusiveEnd === 'undefined') {\n matcherOpts.inclusiveEnd = true;\n }\n\n\n if (inclusiveStart && !matcherOpts.inclusiveStart) {\n inclusiveStart = false;\n }\n if (inclusiveEnd && !matcherOpts.inclusiveEnd) {\n inclusiveEnd = false;\n }\n\n return matcherOpts;\n });\n\n const queryPlan: RxQueryPlan = {\n index,\n startKeys: opts.map(opt => opt.startKey),\n endKeys: opts.map(opt => opt.endKey),\n inclusiveEnd,\n inclusiveStart,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === index.join(','),\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex(index, query.selector)\n };\n const quality = rateQueryPlan(\n schema,\n query,\n queryPlan\n );\n if (\n (\n quality > 0 &&\n quality > currentBestQuality\n ) ||\n query.index\n ) {\n currentBestQuality = quality;\n currentBestQueryPlan = queryPlan;\n }\n });\n\n /**\n * No index found, use the default index\n */\n if (!currentBestQueryPlan) {\n currentBestQueryPlan = {\n index: [primaryPath],\n startKeys: [INDEX_MIN],\n endKeys: [INDEX_MAX],\n inclusiveEnd: true,\n inclusiveStart: true,\n sortFieldsSameAsIndexFields: !hasDescSorting && optimalSortIndexCompareString === primaryPath,\n selectorSatisfiedByIndex: isSelectorSatisfiedByIndex([primaryPath], query.selector)\n };\n }\n\n return currentBestQueryPlan;\n}\n\nexport const LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte', '$lt', '$lte']);\nexport const LOWER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$gt', '$gte']);\nexport const UPPER_BOUND_LOGICAL_OPERATORS = new Set(['$eq', '$lt', '$lte']);\n\nexport function isSelectorSatisfiedByIndex(\n index: string[],\n selector: MangoQuerySelector\n): boolean {\n const selectorEntries = Object.entries(selector);\n const hasNonMatchingOperator = selectorEntries\n .find(([fieldName, operation]) => {\n if (!index.includes(fieldName)) {\n return true;\n }\n const hasNonLogicOperator = Object.entries(operation as any)\n .find(([op, _value]) => !LOGICAL_OPERATORS.has(op));\n return hasNonLogicOperator;\n });\n if (hasNonMatchingOperator) {\n return false;\n }\n\n\n let prevLowerBoundaryField: any;\n const hasMoreThenOneLowerBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasLowerLogicOp = Object.keys(operation).find(key => LOWER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevLowerBoundaryField && hasLowerLogicOp) {\n return true;\n } else if (hasLowerLogicOp !== '$eq') {\n prevLowerBoundaryField = hasLowerLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneLowerBoundaryField) {\n return false;\n }\n\n let prevUpperBoundaryField: any;\n const hasMoreThenOneUpperBoundaryField = index.find(fieldName => {\n const operation = selector[fieldName];\n if (!operation) {\n return false;\n }\n const hasUpperLogicOp = Object.keys(operation).find(key => UPPER_BOUND_LOGICAL_OPERATORS.has(key));\n if (prevUpperBoundaryField && hasUpperLogicOp) {\n return true;\n } else if (hasUpperLogicOp !== '$eq') {\n prevUpperBoundaryField = hasUpperLogicOp;\n }\n return false;\n });\n if (hasMoreThenOneUpperBoundaryField) {\n return false;\n }\n\n return true;\n}\n\nexport function getMatcherQueryOpts(\n operator: string,\n operatorValue: any\n): Partial {\n switch (operator) {\n case '$eq':\n return {\n startKey: operatorValue,\n endKey: operatorValue\n };\n case '$lte':\n return {\n endKey: operatorValue\n };\n case '$gte':\n return {\n startKey: operatorValue\n };\n case '$lt':\n return {\n endKey: operatorValue,\n inclusiveEnd: false\n };\n case '$gt':\n return {\n startKey: operatorValue,\n inclusiveStart: false\n };\n default:\n throw new Error('SNH');\n }\n}\n\n\n/**\n * Returns a number that determines the quality of the query plan.\n * Higher number means better query plan.\n */\nexport function rateQueryPlan(\n schema: RxJsonSchema>,\n query: FilledMangoQuery,\n queryPlan: RxQueryPlan\n): number {\n let quality: number = 0;\n\n const pointsPerMatchingKey = 10;\n const idxOfFirstMinStartKey = queryPlan.startKeys.findIndex(keyValue => keyValue === INDEX_MIN);\n if (idxOfFirstMinStartKey > 0) {\n quality = quality + (idxOfFirstMinStartKey * pointsPerMatchingKey);\n }\n\n const idxOfFirstMaxEndKey = queryPlan.endKeys.findIndex(keyValue => keyValue === INDEX_MAX);\n if (idxOfFirstMaxEndKey > 0) {\n quality = quality + (idxOfFirstMaxEndKey * pointsPerMatchingKey);\n }\n\n const pointsIfNoReSortMustBeDone = 5;\n if (queryPlan.sortFieldsSameAsIndexFields) {\n quality = quality + pointsIfNoReSortMustBeDone;\n }\n\n return quality;\n}\n"],"mappings":";;;;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/replication-protocol/checkpoint.js index cab427be195..3a7cddfc84c 100644 --- a/dist/lib/replication-protocol/checkpoint.js +++ b/dist/lib/replication-protocol/checkpoint.js @@ -1,202 +1,102 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.getCheckpointKey = getCheckpointKey; -exports.setCheckpoint = exports.getLastCheckpointDoc = void 0; +exports.getLastCheckpointDoc = getLastCheckpointDoc; +exports.setCheckpoint = setCheckpoint; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxSchemaHelper = require("../rx-schema-helper"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _metaInstance = require("./meta-instance"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } +function getLastCheckpointDoc(_x, _x2) { + return _getLastCheckpointDoc.apply(this, arguments); } /** * Sets the checkpoint, * automatically resolves conflicts that appear. */ -var setCheckpoint = function setCheckpoint(state, direction, checkpoint) { - try { - var _exit = false; - var previousCheckpointDoc = state.lastCheckpointDoc[direction]; - return Promise.resolve(function () { - if (checkpoint && - /** - * If the replication is already canceled, - * we do not write a checkpoint - * because that could mean we write a checkpoint - * for data that has been fetched from the master - * but not been written to the child. - */ - !state.events.canceled.getValue() && ( - /** - * Only write checkpoint if it is different from before - * to have less writes to the storage. - */ +function _getLastCheckpointDoc() { + _getLastCheckpointDoc = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(state, direction) { + var checkpointDocId, checkpointResult, checkpointDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + checkpointDocId = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, { + isCheckpoint: '1', + itemId: direction, + replicationIdentifier: state.checkpointKey + }); + _context.next = 3; + return state.input.metaInstance.findDocumentsById([checkpointDocId], false); + case 3: + checkpointResult = _context.sent; + checkpointDoc = checkpointResult[checkpointDocId]; + state.lastCheckpointDoc[direction] = checkpointDoc; + if (!checkpointDoc) { + _context.next = 10; + break; + } + return _context.abrupt("return", checkpointDoc.data); + case 10: + return _context.abrupt("return", undefined); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getLastCheckpointDoc.apply(this, arguments); +} +function setCheckpoint(_x3, _x4, _x5) { + return _setCheckpoint.apply(this, arguments); +} +function _setCheckpoint() { + _setCheckpoint = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(state, direction, checkpoint) { + var previousCheckpointDoc, newDoc, result, error; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + previousCheckpointDoc = state.lastCheckpointDoc[direction]; + if (!(checkpoint && + /** + * If the replication is already canceled, + * we do not write a checkpoint + * because that could mean we write a checkpoint + * for data that has been fetched from the master + * but not been written to the child. + */ + !state.events.canceled.getValue() && ( + /** + * Only write checkpoint if it is different from before + * to have less writes to the storage. + */ - !previousCheckpointDoc || JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint))) { - var newDoc = { - id: '', - isCheckpoint: '1', - itemId: direction, - replicationIdentifier: state.checkpointKey, - _deleted: false, - _attachments: {}, - data: checkpoint, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)() - }; - newDoc.id = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, newDoc); - return _for(function () { - return !_exit; - }, void 0, function () { + !previousCheckpointDoc || JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)))) { + _context2.next = 25; + break; + } + newDoc = { + id: '', + isCheckpoint: '1', + itemId: direction, + replicationIdentifier: state.checkpointKey, + _deleted: false, + _attachments: {}, + data: checkpoint, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)() + }; + newDoc.id = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, newDoc); + case 4: + if (!true) { + _context2.next = 25; + break; + } /** * Instead of just storign the new checkpoint, * we have to stack up the checkpoint with the previous one. @@ -207,56 +107,44 @@ var setCheckpoint = function setCheckpoint(state, direction, checkpoint) { if (previousCheckpointDoc) { newDoc.data = (0, _rxStorageHelper.stackCheckpoints)([previousCheckpointDoc.data, newDoc.data]); } - newDoc._meta.lwt = (0, _util.now)(); - newDoc._rev = (0, _util.createRevision)(state.input.hashFunction, newDoc, previousCheckpointDoc); - return Promise.resolve(state.input.metaInstance.bulkWrite([{ + newDoc._meta.lwt = (0, _utils.now)(); + newDoc._rev = (0, _utils.createRevision)(state.input.identifier, previousCheckpointDoc); + _context2.next = 10; + return state.input.metaInstance.bulkWrite([{ previous: previousCheckpointDoc, document: newDoc - }], 'replication-set-checkpoint')).then(function (result) { - if (result.success[newDoc.id]) { - state.lastCheckpointDoc[direction] = (0, _util.getFromObjectOrThrow)(result.success, newDoc.id); - _exit = true; - } else { - var error = (0, _util.getFromObjectOrThrow)(result.error, newDoc.id); - if (error.status !== 409) { - throw error; - } else { - previousCheckpointDoc = (0, _util.ensureNotFalsy)(error.documentInDb); - newDoc._rev = (0, _util.createRevision)(state.input.hashFunction, newDoc, previousCheckpointDoc); - } - } - }); - }); - } - }()); - } catch (e) { - return Promise.reject(e); - } -}; -exports.setCheckpoint = setCheckpoint; -var getLastCheckpointDoc = function getLastCheckpointDoc(state, direction) { - try { - var checkpointDocId = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, { - isCheckpoint: '1', - itemId: direction, - replicationIdentifier: state.checkpointKey - }); - return Promise.resolve(state.input.metaInstance.findDocumentsById([checkpointDocId], false)).then(function (checkpointResult) { - var checkpointDoc = checkpointResult[checkpointDocId]; - state.lastCheckpointDoc[direction] = checkpointDoc; - if (checkpointDoc) { - return checkpointDoc.data; - } else { - return undefined; + }], 'replication-set-checkpoint'); + case 10: + result = _context2.sent; + if (!result.success[newDoc.id]) { + _context2.next = 16; + break; + } + state.lastCheckpointDoc[direction] = (0, _utils.getFromObjectOrThrow)(result.success, newDoc.id); + return _context2.abrupt("return"); + case 16: + error = (0, _utils.getFromObjectOrThrow)(result.error, newDoc.id); + if (!(error.status !== 409)) { + _context2.next = 21; + break; + } + throw error; + case 21: + previousCheckpointDoc = (0, _utils.ensureNotFalsy)(error.documentInDb); + newDoc._rev = (0, _utils.createRevision)(state.input.identifier, previousCheckpointDoc); + case 23: + _context2.next = 4; + break; + case 25: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.getLastCheckpointDoc = getLastCheckpointDoc; + }, _callee2); + })); + return _setCheckpoint.apply(this, arguments); +} function getCheckpointKey(input) { - var hash = (0, _util.fastUnsecureHash)([input.identifier, input.forkInstance.databaseName, input.forkInstance.collectionName].join('||')); + var hash = (0, _utils.fastUnsecureHash)([input.identifier, input.forkInstance.databaseName, input.forkInstance.collectionName].join('||')); return 'rx-storage-replication-' + hash; } //# sourceMappingURL=checkpoint.js.map \ No newline at end of file diff --git a/dist/lib/replication-protocol/checkpoint.js.map b/dist/lib/replication-protocol/checkpoint.js.map index 1ca2aa09f7b..a902bb33f58 100644 --- a/dist/lib/replication-protocol/checkpoint.js.map +++ b/dist/lib/replication-protocol/checkpoint.js.map @@ -1 +1 @@ -{"version":3,"file":"checkpoint.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","setCheckpoint","direction","checkpoint","previousCheckpointDoc","lastCheckpointDoc","events","canceled","getValue","JSON","stringify","data","newDoc","id","isCheckpoint","itemId","replicationIdentifier","checkpointKey","_deleted","_attachments","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","getComposedPrimaryKeyOfDocumentData","RX_REPLICATION_META_INSTANCE_SCHEMA","stackCheckpoints","lwt","now","createRevision","input","hashFunction","metaInstance","bulkWrite","previous","document","success","getFromObjectOrThrow","error","status","ensureNotFalsy","documentInDb","getLastCheckpointDoc","checkpointDocId","findDocumentsById","checkpointResult","checkpointDoc","undefined","getCheckpointKey","hash","fastUnsecureHash","identifier","forkInstance","databaseName","collectionName","join"],"sources":["../../../src/replication-protocol/checkpoint.ts"],"sourcesContent":["import { getComposedPrimaryKeyOfDocumentData } from '../rx-schema-helper';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxDocumentData,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta\n} from '../types';\nimport {\n createRevision,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromObjectOrThrow,\n now\n} from '../util';\nimport { RX_REPLICATION_META_INSTANCE_SCHEMA } from './meta-instance';\n\nexport async function getLastCheckpointDoc(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection\n): Promise {\n const checkpointDocId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey\n }\n );\n const checkpointResult = await state.input.metaInstance.findDocumentsById(\n [\n checkpointDocId\n ],\n false\n );\n\n const checkpointDoc = checkpointResult[checkpointDocId];\n state.lastCheckpointDoc[direction] = checkpointDoc;\n if (checkpointDoc) {\n return checkpointDoc.data;\n } else {\n return undefined;\n }\n}\n\n\n/**\n * Sets the checkpoint,\n * automatically resolves conflicts that appear.\n */\nexport async function setCheckpoint(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection,\n checkpoint: CheckpointType\n) {\n let previousCheckpointDoc = state.lastCheckpointDoc[direction];\n if (\n checkpoint &&\n /**\n * If the replication is already canceled,\n * we do not write a checkpoint\n * because that could mean we write a checkpoint\n * for data that has been fetched from the master\n * but not been written to the child.\n */\n !state.events.canceled.getValue() &&\n /**\n * Only write checkpoint if it is different from before\n * to have less writes to the storage.\n */\n (\n !previousCheckpointDoc ||\n JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)\n )\n ) {\n const newDoc: RxDocumentData = {\n id: '',\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey,\n _deleted: false,\n _attachments: {},\n data: checkpoint,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision()\n };\n newDoc.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newDoc\n );\n while (true) {\n /**\n * Instead of just storign the new checkpoint,\n * we have to stack up the checkpoint with the previous one.\n * This is required for plugins like the sharding RxStorage\n * where the changeStream events only contain a Partial of the\n * checkpoint.\n */\n if (previousCheckpointDoc) {\n newDoc.data = stackCheckpoints([\n previousCheckpointDoc.data,\n newDoc.data\n ]);\n }\n newDoc._meta.lwt = now();\n newDoc._rev = createRevision(\n state.input.hashFunction,\n newDoc,\n previousCheckpointDoc\n );\n const result = await state.input.metaInstance.bulkWrite([{\n previous: previousCheckpointDoc,\n document: newDoc\n }], 'replication-set-checkpoint');\n\n if (result.success[newDoc.id]) {\n state.lastCheckpointDoc[direction] = getFromObjectOrThrow(\n result.success,\n newDoc.id\n );\n return;\n } else {\n const error = getFromObjectOrThrow(\n result.error,\n newDoc.id\n );\n if (error.status !== 409) {\n throw error;\n } else {\n previousCheckpointDoc = ensureNotFalsy(error.documentInDb);\n newDoc._rev = createRevision(\n state.input.hashFunction,\n newDoc,\n previousCheckpointDoc\n );\n }\n }\n }\n }\n}\n\nexport function getCheckpointKey(\n input: RxStorageInstanceReplicationInput\n): string {\n const hash = fastUnsecureHash([\n input.identifier,\n input.forkInstance.databaseName,\n input.forkInstance.collectionName\n ].join('||'));\n return 'rx-storage-replication-' + hash;\n}\n"],"mappings":";;;;;;;AAAA;AACA;AAQA;AASA;AAqBO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACK,IAAI,EAAE;MACxBL,KAAK,CAACK,IAAI,CAAC,QAAQD,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAE,CAAC,CAAC,CAAC;MACxE;IACD;IACAA,I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AAG,IAAAO,oBAAc,EACxBtD,KAAK,CAACuD,KAAK,CAACC,YAAY,EACxBnB,MAAM,EACNR,qBAAqB,CACxB;cAAC;YAAA;UAAA;QAGd,CAAC;MAAA;IAAA;EAET,CAAC;IAAA;EAAA;AAAA;AAAA;AAAA,IA1HqBsC,oBAAoB,YAApBA,oBAAoB,CACtCnE,KAAmD,EACnD2B,SAAwC;EAAA,IACL;IACnC,IAAMyC,eAAe,GAAG,IAAAnB,mDAAmC,EACvDC,iDAAmC,EACnC;MACIX,YAAY,EAAE,GAAG;MACjBC,MAAM,EAAEb,SAAS;MACjBc,qBAAqB,EAAEzC,KAAK,CAAC0C;IACjC,CAAC,CACJ;IAAC,uBAC6B1C,KAAK,CAACuD,KAAK,CAACE,YAAY,CAACY,iBAAiB,CACrE,CACID,eAAe,CAClB,EACD,KAAK,CACR,iBALKE,gBAAgB;MAOtB,IAAMC,aAAa,GAAGD,gBAAgB,CAACF,eAAe,CAAC;MACvDpE,KAAK,CAAC8B,iBAAiB,CAACH,SAAS,CAAC,GAAG4C,aAAa;MAAC,IAC/CA,aAAa;QACb,OAAOA,aAAa,CAACnC,IAAI;MAAC;QAE1B,OAAOoC,SAAS;MAAC;IAAA;EAEzB,CAAC;IAAA;EAAA;AAAA;AAAA;AAkGM,SAASC,gBAAgB,CAC5BlB,KAAmD,EAC7C;EACN,IAAMmB,IAAI,GAAG,IAAAC,sBAAgB,EAAC,CAC1BpB,KAAK,CAACqB,UAAU,EAChBrB,KAAK,CAACsB,YAAY,CAACC,YAAY,EAC/BvB,KAAK,CAACsB,YAAY,CAACE,cAAc,CACpC,CAACC,IAAI,CAAC,IAAI,CAAC,CAAC;EACb,OAAO,yBAAyB,GAAGN,IAAI;AAC3C"} \ No newline at end of file +{"version":3,"file":"checkpoint.js","names":["getLastCheckpointDoc","state","direction","checkpointDocId","getComposedPrimaryKeyOfDocumentData","RX_REPLICATION_META_INSTANCE_SCHEMA","isCheckpoint","itemId","replicationIdentifier","checkpointKey","input","metaInstance","findDocumentsById","checkpointResult","checkpointDoc","lastCheckpointDoc","data","undefined","setCheckpoint","checkpoint","previousCheckpointDoc","events","canceled","getValue","JSON","stringify","newDoc","id","_deleted","_attachments","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","stackCheckpoints","lwt","now","createRevision","identifier","bulkWrite","previous","document","result","success","getFromObjectOrThrow","error","status","ensureNotFalsy","documentInDb","getCheckpointKey","hash","fastUnsecureHash","forkInstance","databaseName","collectionName","join"],"sources":["../../../src/replication-protocol/checkpoint.ts"],"sourcesContent":["import { getComposedPrimaryKeyOfDocumentData } from '../rx-schema-helper';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxDocumentData,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n RxStorageReplicationDirection,\n RxStorageReplicationMeta\n} from '../types';\nimport {\n createRevision,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n getFromObjectOrThrow,\n now\n} from '../plugins/utils';\nimport { RX_REPLICATION_META_INSTANCE_SCHEMA } from './meta-instance';\n\nexport async function getLastCheckpointDoc(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection\n): Promise {\n const checkpointDocId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey\n }\n );\n const checkpointResult = await state.input.metaInstance.findDocumentsById(\n [\n checkpointDocId\n ],\n false\n );\n\n const checkpointDoc = checkpointResult[checkpointDocId];\n state.lastCheckpointDoc[direction] = checkpointDoc;\n if (checkpointDoc) {\n return checkpointDoc.data;\n } else {\n return undefined;\n }\n}\n\n\n/**\n * Sets the checkpoint,\n * automatically resolves conflicts that appear.\n */\nexport async function setCheckpoint(\n state: RxStorageInstanceReplicationState,\n direction: RxStorageReplicationDirection,\n checkpoint: CheckpointType\n) {\n let previousCheckpointDoc = state.lastCheckpointDoc[direction];\n if (\n checkpoint &&\n /**\n * If the replication is already canceled,\n * we do not write a checkpoint\n * because that could mean we write a checkpoint\n * for data that has been fetched from the master\n * but not been written to the child.\n */\n !state.events.canceled.getValue() &&\n /**\n * Only write checkpoint if it is different from before\n * to have less writes to the storage.\n */\n (\n !previousCheckpointDoc ||\n JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)\n )\n ) {\n const newDoc: RxDocumentData = {\n id: '',\n isCheckpoint: '1',\n itemId: direction,\n replicationIdentifier: state.checkpointKey,\n _deleted: false,\n _attachments: {},\n data: checkpoint,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision()\n };\n newDoc.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newDoc\n );\n while (true) {\n /**\n * Instead of just storign the new checkpoint,\n * we have to stack up the checkpoint with the previous one.\n * This is required for plugins like the sharding RxStorage\n * where the changeStream events only contain a Partial of the\n * checkpoint.\n */\n if (previousCheckpointDoc) {\n newDoc.data = stackCheckpoints([\n previousCheckpointDoc.data,\n newDoc.data\n ]);\n }\n newDoc._meta.lwt = now();\n newDoc._rev = createRevision(\n state.input.identifier,\n previousCheckpointDoc\n );\n const result = await state.input.metaInstance.bulkWrite([{\n previous: previousCheckpointDoc,\n document: newDoc\n }], 'replication-set-checkpoint');\n\n if (result.success[newDoc.id]) {\n state.lastCheckpointDoc[direction] = getFromObjectOrThrow(\n result.success,\n newDoc.id\n );\n return;\n } else {\n const error = getFromObjectOrThrow(\n result.error,\n newDoc.id\n );\n if (error.status !== 409) {\n throw error;\n } else {\n previousCheckpointDoc = ensureNotFalsy(error.documentInDb);\n newDoc._rev = createRevision(\n state.input.identifier,\n previousCheckpointDoc\n );\n }\n }\n }\n }\n}\n\nexport function getCheckpointKey(\n input: RxStorageInstanceReplicationInput\n): string {\n const hash = fastUnsecureHash([\n input.identifier,\n input.forkInstance.databaseName,\n input.forkInstance.collectionName\n ].join('||'));\n return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oB,EAC9BF,MAAM,CAACG,KAAK,EACZnB,MAAM,CAACC,EAAE,CACZ;UAAA,MACGkB,KAAK,CAACC,MAAM,KAAK,GAAG;YAAA;YAAA;UAAA;UAAA,MACdD,KAAK;QAAA;UAEXzB,qBAAqB,GAAG,IAAA2B,qBAAc,EAACF,KAAK,CAACG,YAAY,CAAC;UAC1DtB,MAAM,CAACM,IAAI,GAAG,IAAAK,qBAAc,EACxBpC,KAAK,CAACS,KAAK,CAAC4B,UAAU,EACtBlB,qBAAqB,CACxB;QAAC;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAKrB;EAAA;AAAA;AAEM,SAAS6B,gBAAgB,CAC5BvC,KAAmD,EAC7C;EACN,IAAMwC,IAAI,GAAG,IAAAC,uBAAgB,EAAC,CAC1BzC,KAAK,CAAC4B,UAAU,EAChB5B,KAAK,CAAC0C,YAAY,CAACC,YAAY,EAC/B3C,KAAK,CAAC0C,YAAY,CAACE,cAAc,CACpC,CAACC,IAAI,CAAC,IAAI,CAAC,CAAC;EACb,OAAO,yBAAyB,GAAGL,IAAI;AAC3C"} \ No newline at end of file diff --git a/dist/lib/replication-protocol/conflicts.js b/dist/lib/replication-protocol/conflicts.js index 02357dbff4e..18f76c552e6 100644 --- a/dist/lib/replication-protocol/conflicts.js +++ b/dist/lib/replication-protocol/conflicts.js @@ -4,54 +4,12 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveConflictError = exports.defaultConflictHandler = void 0; -var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); -var _util = require("../util"); -/** - * Resolves a conflict error or determines that the given document states are equal. - * Returns the resolved document that must be written to the fork. - * Then the new document state can be pushed upstream. - * If document is not in conflict, returns undefined. - * If error is non-409, it throws an error. - * Conflicts are only solved in the upstream, never in the downstream. - */ -var resolveConflictError = function resolveConflictError(state, input, forkState) { - try { - var conflictHandler = state.input.conflictHandler; - return Promise.resolve(conflictHandler(input, 'replication-resolve-conflict')).then(function (conflictHandlerOutput) { - if (conflictHandlerOutput.isEqual) { - /** - * Documents are equal, - * so this is not a conflict -> do nothing. - */ - return undefined; - } else { - /** - * We have a resolved conflict, - * use the resolved document data. - */ - var resolvedDoc = Object.assign({}, conflictHandlerOutput.documentData, { - /** - * Because the resolved conflict is written to the fork, - * we have to keep/update the forks _meta data, not the masters. - */ - _meta: (0, _util.flatClone)(forkState._meta), - _rev: (0, _util.getDefaultRevision)(), - _attachments: (0, _util.flatClone)(forkState._attachments) - }); - resolvedDoc._meta.lwt = (0, _util.now)(); - resolvedDoc._rev = (0, _util.createRevision)(state.input.hashFunction, resolvedDoc, forkState); - return { - resolvedDoc: resolvedDoc, - output: conflictHandlerOutput - }; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; +exports.defaultConflictHandler = void 0; exports.resolveConflictError = resolveConflictError; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); +var _utils = require("../plugins/utils"); var defaultConflictHandler = function defaultConflictHandler(i, _context) { /** * If the documents are deep equal, @@ -75,5 +33,61 @@ var defaultConflictHandler = function defaultConflictHandler(i, _context) { documentData: i.realMasterState }); }; + +/** + * Resolves a conflict error or determines that the given document states are equal. + * Returns the resolved document that must be written to the fork. + * Then the new document state can be pushed upstream. + * If document is not in conflict, returns undefined. + * If error is non-409, it throws an error. + * Conflicts are only solved in the upstream, never in the downstream. + */ exports.defaultConflictHandler = defaultConflictHandler; +function resolveConflictError(_x, _x2, _x3) { + return _resolveConflictError.apply(this, arguments); +} +function _resolveConflictError() { + _resolveConflictError = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(state, input, forkState) { + var conflictHandler, conflictHandlerOutput, resolvedDoc; + return _regenerator["default"].wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + conflictHandler = state.input.conflictHandler; + _context2.next = 3; + return conflictHandler(input, 'replication-resolve-conflict'); + case 3: + conflictHandlerOutput = _context2.sent; + if (!conflictHandlerOutput.isEqual) { + _context2.next = 8; + break; + } + return _context2.abrupt("return", undefined); + case 8: + /** + * We have a resolved conflict, + * use the resolved document data. + */ + resolvedDoc = Object.assign({}, conflictHandlerOutput.documentData, { + /** + * Because the resolved conflict is written to the fork, + * we have to keep/update the forks _meta data, not the masters. + */ + _meta: (0, _utils.flatClone)(forkState._meta), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: (0, _utils.flatClone)(forkState._attachments) + }); + resolvedDoc._meta.lwt = (0, _utils.now)(); + resolvedDoc._rev = (0, _utils.createRevision)(state.input.identifier, forkState); + return _context2.abrupt("return", { + resolvedDoc: resolvedDoc, + output: conflictHandlerOutput + }); + case 12: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return _resolveConflictError.apply(this, arguments); +} //# sourceMappingURL=conflicts.js.map \ No newline at end of file diff --git a/dist/lib/replication-protocol/conflicts.js.map b/dist/lib/replication-protocol/conflicts.js.map index f6dd034b4e4..1f5c1cddcdd 100644 --- a/dist/lib/replication-protocol/conflicts.js.map +++ b/dist/lib/replication-protocol/conflicts.js.map @@ -1 +1 @@ -{"version":3,"file":"conflicts.js","names":["resolveConflictError","state","input","forkState","conflictHandler","conflictHandlerOutput","isEqual","undefined","resolvedDoc","Object","assign","documentData","_meta","flatClone","_rev","getDefaultRevision","_attachments","lwt","now","createRevision","hashFunction","output","defaultConflictHandler","i","_context","deepEqual","newDocumentState","realMasterState","Promise","resolve"],"sources":["../../../src/replication-protocol/conflicts.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport type {\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxDocumentData,\n RxStorageInstanceReplicationState\n} from '../types';\nimport {\n getDefaultRevision,\n createRevision,\n now,\n flatClone\n} from '../util';\n\nexport const defaultConflictHandler: RxConflictHandler = function (\n i: RxConflictHandlerInput,\n _context: string\n): Promise> {\n /**\n * If the documents are deep equal,\n * we have no conflict.\n * On your custom conflict handler you might only\n * check some properties, like the updatedAt time,\n * for better performance, because deepEqual is expensive.\n */\n if (deepEqual(\n i.newDocumentState,\n i.realMasterState\n )) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n /**\n * The default conflict handler will always\n * drop the fork state and use the master state instead.\n */\n return Promise.resolve({\n isEqual: false,\n documentData: i.realMasterState\n });\n};\n\n\n/**\n * Resolves a conflict error or determines that the given document states are equal.\n * Returns the resolved document that must be written to the fork.\n * Then the new document state can be pushed upstream.\n * If document is not in conflict, returns undefined.\n * If error is non-409, it throws an error.\n * Conflicts are only solved in the upstream, never in the downstream.\n */\nexport async function resolveConflictError(\n state: RxStorageInstanceReplicationState,\n input: RxConflictHandlerInput,\n forkState: RxDocumentData\n): Promise<{\n resolvedDoc: RxDocumentData;\n output: RxConflictHandlerOutput;\n } | undefined> {\n const conflictHandler: RxConflictHandler = state.input.conflictHandler;\n const conflictHandlerOutput = await conflictHandler(input, 'replication-resolve-conflict');\n\n if (conflictHandlerOutput.isEqual) {\n /**\n * Documents are equal,\n * so this is not a conflict -> do nothing.\n */\n return undefined;\n } else {\n /**\n * We have a resolved conflict,\n * use the resolved document data.\n */\n const resolvedDoc: RxDocumentData = Object.assign(\n {},\n conflictHandlerOutput.documentData,\n {\n /**\n * Because the resolved conflict is written to the fork,\n * we have to keep/update the forks _meta data, not the masters.\n */\n _meta: flatClone(forkState._meta),\n _rev: getDefaultRevision(),\n _attachments: flatClone(forkState._attachments)\n }\n );\n resolvedDoc._meta.lwt = now();\n resolvedDoc._rev = createRevision(\n state.input.hashFunction,\n resolvedDoc,\n forkState\n );\n return {\n resolvedDoc,\n output: conflictHandlerOutput\n };\n }\n}\n"],"mappings":";;;;;;;AAAA;AAQA;AAsCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAPA,IAQsBA,oBAAoB,YAApBA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AAC;IACnBvB,OAAO,EAAE,KAAK;IACdK,YAAY,EAAEY,CAAC,CAACI;EACpB,CAAC,CAAC;AACN,CAAC;AAAC"} \ No newline at end of file +{"version":3,"file":"conflicts.js","names":["defaultConflictHandler","i","_context","deepEqual","newDocumentState","realMasterState","Promise","resolve","isEqual","documentData","resolveConflictError","state","input","forkState","conflictHandler","conflictHandlerOutput","undefined","resolvedDoc","Object","assign","_meta","flatClone","_rev","getDefaultRevision","_attachments","lwt","now","createRevision","identifier","output"],"sources":["../../../src/replication-protocol/conflicts.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\nimport type {\n RxConflictHandler,\n RxConflictHandlerInput,\n RxConflictHandlerOutput,\n RxDocumentData,\n RxStorageInstanceReplicationState\n} from '../types';\nimport {\n getDefaultRevision,\n createRevision,\n now,\n flatClone\n} from '../plugins/utils';\n\nexport const defaultConflictHandler: RxConflictHandler = function (\n i: RxConflictHandlerInput,\n _context: string\n): Promise> {\n /**\n * If the documents are deep equal,\n * we have no conflict.\n * On your custom conflict handler you might only\n * check some properties, like the updatedAt time,\n * for better performance, because deepEqual is expensive.\n */\n if (deepEqual(\n i.newDocumentState,\n i.realMasterState\n )) {\n return Promise.resolve({\n isEqual: true\n });\n }\n\n /**\n * The default conflict handler will always\n * drop the fork state and use the master state instead.\n */\n return Promise.resolve({\n isEqual: false,\n documentData: i.realMasterState\n });\n};\n\n\n/**\n * Resolves a conflict error or determines that the given document states are equal.\n * Returns the resolved document that must be written to the fork.\n * Then the new document state can be pushed upstream.\n * If document is not in conflict, returns undefined.\n * If error is non-409, it throws an error.\n * Conflicts are only solved in the upstream, never in the downstream.\n */\nexport async function resolveConflictError(\n state: RxStorageInstanceReplicationState,\n input: RxConflictHandlerInput,\n forkState: RxDocumentData\n): Promise<{\n resolvedDoc: RxDocumentData;\n output: RxConflictHandlerOutput;\n} | undefined> {\n const conflictHandler: RxConflictHandler = state.input.conflictHandler;\n const conflictHandlerOutput = await conflictHandler(input, 'replication-resolve-conflict');\n\n if (conflictHandlerOutput.isEqual) {\n /**\n * Documents are equal,\n * so this is not a conflict -> do nothing.\n */\n return undefined;\n } else {\n /**\n * We have a resolved conflict,\n * use the resolved document data.\n */\n const resolvedDoc: RxDocumentData = Object.assign(\n {},\n conflictHandlerOutput.documentData,\n {\n /**\n * Because the resolved conflict is written to the fork,\n * we have to keep/update the forks _meta data, not the masters.\n */\n _meta: flatClone(forkState._meta),\n _rev: getDefaultRevision(),\n _attachments: flatClone(forkState._attachments)\n }\n );\n resolvedDoc._meta.lwt = now();\n resolvedDoc._rev = createRevision(\n state.input.identifier,\n forkState\n );\n return {\n resolvedDoc,\n output: conflictHandlerOutput\n };\n }\n}\n"],"mappings":";;;;;;;;;;AAAA;AAQA;AAOO,IAAMA,sBAA8C,GAAG,SAAjDA,sBAA8C,CACvDC,CAA8B,EAC9BC,QAAgB,EACqB;EACrC;AACJ;AACA;AACA;AACA;AACA;AACA;EACI,IAAI,IAAAC,yBAAS,EACTF,CAAC,CAACG,gBAAgB,EAClBH,CAAC,CAACI,eAAe,CACpB,EAAE;IACC,OAAOC,OAAO,CAACC,OAAO,CAAC;MACnBC,OAAO,EAAE;IACb,CAAC,CAAC;EACN;;EAEA;AACJ;AACA;AACA;EACI,OAAOF,OAAO,CAACC,OAAO,CAAC;IACnBC,OAAO,EAAE,KAAK;IACdC,YAAY,EAAER,CAAC,CAACI;EACpB,CAAC,CAAC;AACN,CAAC;;AAGD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAPA;AAAA,SAQsBK,oBAAoB;EAAA;AAAA;AAAA;EAAA,sGAAnC,iBACHC,KAAmD,EACnDC,KAAwC,EACxCC,SAAoC;IAAA;IAAA;MAAA;QAAA;UAK9BC,eAA6C,GAAGH,KAAK,CAACC,KAAK,CAACE,eAAe;UAAA;UAAA,OAC7CA,eAAe,CAACF,KAAK,EAAE,8BAA8B,CAAC;QAAA;UAApFG,qBAAqB;UAAA,KAEvBA,qBAAqB,CAACP,OAAO;YAAA;YAAA;UAAA;UAAA,kCAKtBQ,SAAS;QAAA;UAEhB;AACR;AACA;AACA;UACcC,WAAsC,GAAGC,MAAM,CAACC,MAAM,CACxD,CAAC,CAAC,EACFJ,qBAAqB,CAACN,YAAY,EAClC;YACI;AAChB;AACA;AACA;YACgBW,KAAK,EAAE,IAAAC,gBAAS,EAACR,SAAS,CAACO,KAAK,CAAC;YACjCE,IAAI,EAAE,IAAAC,yBAAkB,GAAE;YAC1BC,YAAY,EAAE,IAAAH,gBAAS,EAACR,SAAS,CAACW,YAAY;UAClD,CAAC,CACJ;UACDP,WAAW,CAACG,KAAK,CAACK,GAAG,GAAG,IAAAC,UAAG,GAAE;UAC7BT,WAAW,CAACK,IAAI,GAAG,IAAAK,qBAAc,EAC7BhB,KAAK,CAACC,KAAK,CAACgB,UAAU,EACtBf,SAAS,CACZ;UAAC,kCACK;YACHI,WAAW,EAAXA,WAAW;YACXY,MAAM,EAAEd;UACZ,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAER;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/replication-protocol/downstream.js b/dist/lib/replication-protocol/downstream.js index ec874e54ac3..3ebb0bca563 100644 --- a/dist/lib/replication-protocol/downstream.js +++ b/dist/lib/replication-protocol/downstream.js @@ -1,164 +1,19 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.startReplicationDownstream = startReplicationDownstream; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); +var _rxError = require("../rx-error"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _checkpoint = require("./checkpoint"); var _helper = require("./helper"); var _metaInstance = require("./meta-instance"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} /** * Writes all documents from the master to the fork. * The downstream has two operation modes @@ -168,49 +23,6 @@ function _for(test, update, body) { * and still can have fast event based sync when the client is not offline. */ function startReplicationDownstream(state) { - var downstreamResyncOnce = function downstreamResyncOnce() { - try { - state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1; - if (state.events.canceled.getValue()) { - return Promise.resolve(); - } - state.checkpointQueue = state.checkpointQueue.then(function () { - return (0, _checkpoint.getLastCheckpointDoc)(state, 'down'); - }); - return Promise.resolve(state.checkpointQueue).then(function (lastCheckpoint) { - var _interrupt = false; - function _temp2() { - return Promise.resolve(Promise.all(promises)).then(function () {}); - } - var promises = []; - var _temp = _for(function () { - return !_interrupt && !state.events.canceled.getValue(); - }, void 0, function () { - lastTimeMasterChangesRequested = timer++; - return Promise.resolve(replicationHandler.masterChangesSince(lastCheckpoint, state.input.pullBatchSize)).then(function (downResult) { - if (downResult.documents.length === 0) { - _interrupt = true; - return; - } - lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, downResult.checkpoint]); - promises.push(persistFromMaster(downResult.documents, lastCheckpoint)); - - /** - * By definition we stop pull when the pulled documents - * do not fill up the pullBatchSize because we - * can assume that the remote has no more documents. - */ - if (downResult.documents.length < state.input.pullBatchSize) { - _interrupt = true; - } - }); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); - } - }; var replicationHandler = state.input.replicationHandler; // used to detect which tasks etc can in it at which order. @@ -227,7 +39,7 @@ function startReplicationDownstream(state) { var useTasks = []; while (openTasks.length > 0) { state.events.active.down.next(true); - var innerTaskWithTime = (0, _util.ensureNotFalsy)(openTasks.shift()); + var innerTaskWithTime = (0, _utils.ensureNotFalsy)(openTasks.shift()); /** * If the task came in before the last time we started the pull @@ -279,6 +91,73 @@ function startReplicationDownstream(state) { * and then await all writes at the end. */ var lastTimeMasterChangesRequested = -1; + function downstreamResyncOnce() { + return _downstreamResyncOnce.apply(this, arguments); + } + function _downstreamResyncOnce() { + _downstreamResyncOnce = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var lastCheckpoint, promises, downResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1; + if (!state.events.canceled.getValue()) { + _context2.next = 3; + break; + } + return _context2.abrupt("return"); + case 3: + state.checkpointQueue = state.checkpointQueue.then(function () { + return (0, _checkpoint.getLastCheckpointDoc)(state, 'down'); + }); + _context2.next = 6; + return state.checkpointQueue; + case 6: + lastCheckpoint = _context2.sent; + promises = []; + case 8: + if (state.events.canceled.getValue()) { + _context2.next = 21; + break; + } + lastTimeMasterChangesRequested = timer++; + _context2.next = 12; + return replicationHandler.masterChangesSince(lastCheckpoint, state.input.pullBatchSize); + case 12: + downResult = _context2.sent; + if (!(downResult.documents.length === 0)) { + _context2.next = 15; + break; + } + return _context2.abrupt("break", 21); + case 15: + lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, downResult.checkpoint]); + promises.push(persistFromMaster(downResult.documents, lastCheckpoint)); + + /** + * By definition we stop pull when the pulled documents + * do not fill up the pullBatchSize because we + * can assume that the remote has no more documents. + */ + if (!(downResult.documents.length < state.input.pullBatchSize)) { + _context2.next = 19; + break; + } + return _context2.abrupt("break", 21); + case 19: + _context2.next = 8; + break; + case 21: + _context2.next = 23; + return Promise.all(promises); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _downstreamResyncOnce.apply(this, arguments); + } function downstreamProcessChanges(tasks) { state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1; var docsOfAllTasks = []; @@ -290,7 +169,7 @@ function startReplicationDownstream(state) { docsOfAllTasks = docsOfAllTasks.concat(task.documents); lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, task.checkpoint]); }); - return persistFromMaster(docsOfAllTasks, (0, _util.ensureNotFalsy)(lastCheckpoint)); + return persistFromMaster(docsOfAllTasks, (0, _utils.ensureNotFalsy)(lastCheckpoint)); } /** @@ -301,7 +180,7 @@ function startReplicationDownstream(state) { * This often bundles up single writes and improves performance * by processing the documents in bulks. */ - var persistenceQueue = _util.PROMISE_RESOLVE_VOID; + var persistenceQueue = _utils.PROMISE_RESOLVE_VOID; var nonPersistedFromMaster = { docs: {} }; @@ -327,7 +206,7 @@ function startReplicationDownstream(state) { var useCheckpoint = nonPersistedFromMaster.checkpoint; var docIds = Object.keys(downDocsById); if (state.events.canceled.getValue() || docIds.length === 0) { - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } var writeRowsToFork = []; var writeRowsToForkById = {}; @@ -336,47 +215,55 @@ function startReplicationDownstream(state) { return Promise.all([state.input.forkInstance.findDocumentsById(docIds, true), (0, _metaInstance.getAssumedMasterState)(state, docIds)]).then(function (_ref) { var currentForkState = _ref[0], assumedMasterState = _ref[1]; - return Promise.all(docIds.map(function (docId) { - try { - var forkStateFullDoc = currentForkState[docId]; - var forkStateDocData = forkStateFullDoc ? (0, _helper.writeDocToDocState)(forkStateFullDoc) : undefined; - var masterState = downDocsById[docId]; - var assumedMaster = assumedMasterState[docId]; - if (assumedMaster && assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev) { - /** - * The current fork state represents a resolved conflict - * that first must be send to the master in the upstream. - * All conflicts are resolved by the upstream. - */ - return Promise.resolve(_util.PROMISE_RESOLVE_VOID); - } - var isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ? _util.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ - realMasterState: assumedMaster.docData, - newDocumentState: forkStateDocData - }, 'downstream-check-if-equal-0').then(function (r) { - return r.isEqual; - }); - return Promise.resolve(isAssumedMasterEqualToForkStatePromise).then(function (isAssumedMasterEqualToForkState) { - if (!isAssumedMasterEqualToForkState && assumedMaster && assumedMaster.docData._rev && forkStateFullDoc._meta[state.input.identifier] && (0, _util.parseRevision)(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]) { - isAssumedMasterEqualToForkState = true; - } - if (forkStateFullDoc && assumedMaster && isAssumedMasterEqualToForkState === false || forkStateFullDoc && !assumedMaster) { - /** - * We have a non-upstream-replicated - * local write to the fork. - * This means we ignore the downstream of this document - * because anyway the upstream will first resolve the conflict. - */ - return _util.PROMISE_RESOLVE_VOID; - } - var areStatesExactlyEqualPromise = !forkStateDocData ? _util.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ - realMasterState: masterState, - newDocumentState: forkStateDocData - }, 'downstream-check-if-equal-1').then(function (r) { - return r.isEqual; - }); - return Promise.resolve(areStatesExactlyEqualPromise).then(function (areStatesExactlyEqual) { - if (forkStateDocData && areStatesExactlyEqual) { + return Promise.all(docIds.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(docId) { + var forkStateFullDoc, forkStateDocData, masterState, assumedMaster, isAssumedMasterEqualToForkStatePromise, isAssumedMasterEqualToForkState, areStatesExactlyEqualPromise, areStatesExactlyEqual, newForkState, nextRevisionHeight, forkWriteRow; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + forkStateFullDoc = currentForkState[docId]; + forkStateDocData = forkStateFullDoc ? (0, _helper.writeDocToDocState)(forkStateFullDoc) : undefined; + masterState = downDocsById[docId]; + assumedMaster = assumedMasterState[docId]; + if (!(assumedMaster && assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev)) { + _context.next = 6; + break; + } + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 6: + isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ? _utils.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ + realMasterState: assumedMaster.docData, + newDocumentState: forkStateDocData + }, 'downstream-check-if-equal-0').then(function (r) { + return r.isEqual; + }); + _context.next = 9; + return isAssumedMasterEqualToForkStatePromise; + case 9: + isAssumedMasterEqualToForkState = _context.sent; + if (!isAssumedMasterEqualToForkState && assumedMaster && assumedMaster.docData._rev && forkStateFullDoc._meta[state.input.identifier] && (0, _utils.parseRevision)(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]) { + isAssumedMasterEqualToForkState = true; + } + if (!(forkStateFullDoc && assumedMaster && isAssumedMasterEqualToForkState === false || forkStateFullDoc && !assumedMaster)) { + _context.next = 13; + break; + } + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 13: + areStatesExactlyEqualPromise = !forkStateDocData ? _utils.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ + realMasterState: masterState, + newDocumentState: forkStateDocData + }, 'downstream-check-if-equal-1').then(function (r) { + return r.isEqual; + }); + _context.next = 16; + return areStatesExactlyEqualPromise; + case 16: + areStatesExactlyEqual = _context.sent; + if (!(forkStateDocData && areStatesExactlyEqual)) { + _context.next = 20; + break; + } /** * Document states are exactly equal. * This can happen when the replication is shut down @@ -388,57 +275,50 @@ function startReplicationDownstream(state) { if (!assumedMaster || isAssumedMasterEqualToForkState === false) { useMetaWriteRows.push((0, _metaInstance.getMetaWriteRow)(state, forkStateDocData, assumedMaster ? assumedMaster.metaDocument : undefined)); } - return _util.PROMISE_RESOLVE_VOID; - } - - /** - * All other master states need to be written to the forkInstance - * and metaInstance. - */ - var newForkState = Object.assign({}, masterState, forkStateFullDoc ? { - _meta: (0, _util.flatClone)(forkStateFullDoc._meta), - _attachments: {}, - _rev: (0, _util.getDefaultRevision)() - } : { - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }); - - /** - * TODO for unknown reason we need - * to manually set the lwt and the _rev here - * to fix the pouchdb tests. This is not required for - * the other RxStorage implementations which means something is wrong. - */ - newForkState._meta.lwt = (0, _util.now)(); - newForkState._rev = masterState._rev ? masterState._rev : (0, _util.createRevision)(state.input.hashFunction, newForkState, forkStateFullDoc); - - /** - * If the remote works with revisions, - * we store the height of the next fork-state revision - * inside of the documents meta data. - * By doing so we can filter it out in the upstream - * and detect the document as being equal to master or not. - * This is used for example in the CouchDB replication plugin. - */ - if (masterState._rev) { - var nextRevisionHeight = !forkStateFullDoc ? 1 : (0, _util.parseRevision)(forkStateFullDoc._rev).height + 1; - newForkState._meta[state.input.identifier] = nextRevisionHeight; - } - var forkWriteRow = { - previous: forkStateFullDoc, - document: newForkState - }; - writeRowsToFork.push(forkWriteRow); - writeRowsToForkById[docId] = forkWriteRow; - writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, masterState, assumedMaster ? assumedMaster.metaDocument : undefined); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })); + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 20: + /** + * All other master states need to be written to the forkInstance + * and metaInstance. + */ + newForkState = Object.assign({}, masterState, forkStateFullDoc ? { + _meta: (0, _utils.flatClone)(forkStateFullDoc._meta), + _attachments: {}, + _rev: (0, _utils.getDefaultRevision)() + } : { + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }); + /** + * If the remote works with revisions, + * we store the height of the next fork-state revision + * inside of the documents meta data. + * By doing so we can filter it out in the upstream + * and detect the document as being equal to master or not. + * This is used for example in the CouchDB replication plugin. + */ + if (masterState._rev) { + nextRevisionHeight = !forkStateFullDoc ? 1 : (0, _utils.parseRevision)(forkStateFullDoc._rev).height + 1; + newForkState._meta[state.input.identifier] = nextRevisionHeight; + } + forkWriteRow = { + previous: forkStateFullDoc, + document: newForkState + }; + writeRowsToFork.push(forkWriteRow); + writeRowsToForkById[docId] = forkWriteRow; + writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, masterState, assumedMaster ? assumedMaster.metaDocument : undefined); + case 26: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); }).then(function () { if (writeRowsToFork.length > 0) { return state.input.forkInstance.bulkWrite(writeRowsToFork, state.downstreamBulkWriteFlag).then(function (forkWriteResult) { @@ -446,6 +326,19 @@ function startReplicationDownstream(state) { state.events.processed.down.next(writeRowsToForkById[docId]); useMetaWriteRows.push(writeRowsToMeta[docId]); }); + Object.values(forkWriteResult.error).forEach(function (error) { + /** + * We do not have to care about downstream conflict errors here + * because on conflict, it will be solved locally and result in another write. + */ + if (error.status === 409) { + return; + } + // other non-conflict errors must be handled + state.events.error.next((0, _rxError.newRxError)('RC_PULL', { + writeError: error + })); + }); }); } }).then(function () { diff --git a/dist/lib/replication-protocol/downstream.js.map b/dist/lib/replication-protocol/downstream.js.map index 35f90e97358..38d337cd27d 100644 --- a/dist/lib/replication-protocol/downstream.js.map +++ b/dist/lib/replication-protocol/downstream.js.map @@ -1 +1 @@ -{"version":3,"file":"downstream.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","startReplicationDownstream","downstreamResyncOnce","stats","down","events","canceled","getValue","checkpointQueue","getLastCheckpointDoc","lastCheckpoint","Promise","all","promises","lastTimeMasterChangesRequested","timer","replicationHandler","masterChangesSince","input","pullBatchSize","downResult","documents","length","stackCheckpoints","checkpoint","push","persistFromMaster","openTasks","addNewTask","task","taskWithTime","time","streamQueue","useTasks","active","next","innerTaskWithTime","ensureNotFalsy","shift","downstreamProcessChanges","firstSyncDone","sub","masterChangeStream$","subscribe","masterChangeStreamEmit","firstValueFrom","pipe","filter","unsubscribe","tasks","docsOfAllTasks","forEach","Error","concat","persistenceQueue","PROMISE_RESOLVE_VOID","nonPersistedFromMaster","docs","docData","docId","primaryPath","downDocsById","useCheckpoint","docIds","Object","keys","writeRowsToFork","writeRowsToForkById","writeRowsToMeta","useMetaWriteRows","forkInstance","findDocumentsById","getAssumedMasterState","currentForkState","assumedMasterState","map","forkStateFullDoc","forkStateDocData","writeDocToDocState","undefined","masterState","assumedMaster","metaDocument","isResolvedConflict","_rev","isAssumedMasterEqualToForkStatePromise","PROMISE_RESOLVE_FALSE","conflictHandler","realMasterState","newDocumentState","r","isEqual","isAssumedMasterEqualToForkState","_meta","identifier","parseRevision","height","areStatesExactlyEqualPromise","areStatesExactlyEqual","getMetaWriteRow","newForkState","assign","flatClone","_attachments","getDefaultRevision","getDefaultRxDocumentMeta","lwt","now","createRevision","hashFunction","nextRevisionHeight","forkWriteRow","previous","document","bulkWrite","downstreamBulkWriteFlag","forkWriteResult","success","processed","metaInstance","setCheckpoint","unhandledError","error"],"sources":["../../../src/replication-protocol/downstream.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter\n} from 'rxjs';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxStorageInstanceReplicationState,\n BulkWriteRow,\n BulkWriteRowById,\n RxStorageReplicationMeta,\n RxDocumentData,\n ById,\n WithDeleted,\n DocumentsWithCheckpoint\n} from '../types';\nimport {\n createRevision,\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now,\n parseRevision,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from '../util';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all documents from the master to the fork.\n * The downstream has two operation modes\n * - Sync by iterating over the checkpoints via downstreamResyncOnce()\n * - Sync by listening to the changestream via downstreamProcessChanges()\n * We need this to be able to do initial syncs\n * and still can have fast event based sync when the client is not offline.\n */\nexport function startReplicationDownstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n\n\n type Task = DocumentsWithCheckpoint | 'RESYNC';\n type TaskWithTime = {\n time: number;\n task: Task;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n function addNewTask(task: Task): void {\n state.stats.down.addNewTask = state.stats.down.addNewTask + 1;\n const taskWithTime = {\n time: timer++,\n task\n };\n openTasks.push(taskWithTime);\n state.streamQueue.down = state.streamQueue.down\n .then(() => {\n const useTasks: Task[] = [];\n while (openTasks.length > 0) {\n state.events.active.down.next(true);\n const innerTaskWithTime = ensureNotFalsy(openTasks.shift());\n\n /**\n * If the task came in before the last time we started the pull\n * from the master, then we can drop the task.\n */\n if (innerTaskWithTime.time < lastTimeMasterChangesRequested) {\n continue;\n }\n\n if (innerTaskWithTime.task === 'RESYNC') {\n if (useTasks.length === 0) {\n useTasks.push(innerTaskWithTime.task);\n break;\n } else {\n break;\n }\n }\n\n useTasks.push(innerTaskWithTime.task);\n }\n\n if (useTasks.length === 0) return;\n\n if (useTasks[0] === 'RESYNC') {\n return downstreamResyncOnce();\n } else {\n return downstreamProcessChanges(useTasks);\n }\n }).then(() => {\n state.events.active.down.next(false);\n if (!state.firstSyncDone.down.getValue()) {\n state.firstSyncDone.down.next(true);\n }\n });\n }\n addNewTask('RESYNC');\n\n /**\n * If a write on the master happens, we have to trigger the downstream.\n */\n const sub = replicationHandler\n .masterChangeStream$\n .subscribe((task: Task) => {\n state.stats.down.masterChangeStreamEmit = state.stats.down.masterChangeStreamEmit + 1;\n addNewTask(task);\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n /**\n * For faster performance, we directly start each write\n * and then await all writes at the end.\n */\n let lastTimeMasterChangesRequested: number = -1;\n async function downstreamResyncOnce() {\n state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'down'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n lastTimeMasterChangesRequested = timer++;\n const downResult = await replicationHandler.masterChangesSince(\n lastCheckpoint,\n state.input.pullBatchSize\n );\n\n if (downResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, downResult.checkpoint]);\n\n promises.push(\n persistFromMaster(\n downResult.documents,\n lastCheckpoint\n )\n );\n\n /**\n * By definition we stop pull when the pulled documents\n * do not fill up the pullBatchSize because we\n * can assume that the remote has no more documents.\n */\n if (downResult.documents.length < state.input.pullBatchSize) {\n break;\n }\n\n }\n await Promise.all(promises);\n }\n\n\n function downstreamProcessChanges(tasks: Task[]) {\n state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1;\n let docsOfAllTasks: WithDeleted[] = [];\n let lastCheckpoint: CheckpointType | undefined = null as any;\n\n tasks.forEach(task => {\n if (task === 'RESYNC') {\n throw new Error('SNH');\n }\n docsOfAllTasks = docsOfAllTasks.concat(task.documents);\n lastCheckpoint = stackCheckpoints([lastCheckpoint, task.checkpoint]);\n });\n return persistFromMaster(\n docsOfAllTasks,\n ensureNotFalsy(lastCheckpoint)\n );\n }\n\n\n /**\n * It can happen that the calls to masterChangesSince() or the changeStream()\n * are way faster then how fast the documents can be persisted.\n * Therefore we merge all incoming downResults into the nonPersistedFromMaster object\n * and process them together if possible.\n * This often bundles up single writes and improves performance\n * by processing the documents in bulks.\n */\n let persistenceQueue = PROMISE_RESOLVE_VOID;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n function persistFromMaster(\n docs: WithDeleted[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.down.persistFromMaster = state.stats.down.persistFromMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n /**\n * Run in the queue\n * with all open documents from nonPersistedFromMaster.\n */\n persistenceQueue = persistenceQueue.then(() => {\n const downDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(downDocsById);\n\n if (\n state.events.canceled.getValue() ||\n docIds.length === 0\n ) {\n return PROMISE_RESOLVE_VOID;\n }\n\n const writeRowsToFork: BulkWriteRow[] = [];\n const writeRowsToForkById: ById> = {};\n const writeRowsToMeta: BulkWriteRowById = {};\n const useMetaWriteRows: BulkWriteRow[] = [];\n\n return Promise.all([\n state.input.forkInstance.findDocumentsById(docIds, true),\n getAssumedMasterState(\n state,\n docIds\n )\n ]).then(([\n currentForkState,\n assumedMasterState\n ]) => {\n return Promise.all(\n docIds.map(async (docId) => {\n const forkStateFullDoc: RxDocumentData | undefined = currentForkState[docId];\n const forkStateDocData: WithDeleted | undefined = forkStateFullDoc ? writeDocToDocState(forkStateFullDoc) : undefined;\n const masterState = downDocsById[docId];\n const assumedMaster = assumedMasterState[docId];\n\n if (\n assumedMaster &&\n assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev\n ) {\n /**\n * The current fork state represents a resolved conflict\n * that first must be send to the master in the upstream.\n * All conflicts are resolved by the upstream.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n const isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: assumedMaster.docData,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-0').then(r => r.isEqual);\n let isAssumedMasterEqualToForkState = await isAssumedMasterEqualToForkStatePromise;\n\n if (\n !isAssumedMasterEqualToForkState &&\n (\n assumedMaster &&\n (assumedMaster.docData as any)._rev &&\n forkStateFullDoc._meta[state.input.identifier] &&\n parseRevision(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]\n )\n ) {\n isAssumedMasterEqualToForkState = true;\n }\n if (\n (\n forkStateFullDoc &&\n assumedMaster &&\n isAssumedMasterEqualToForkState === false\n ) ||\n (\n forkStateFullDoc && !assumedMaster\n )\n ) {\n /**\n * We have a non-upstream-replicated\n * local write to the fork.\n * This means we ignore the downstream of this document\n * because anyway the upstream will first resolve the conflict.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n\n const areStatesExactlyEqualPromise = !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: masterState,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-1').then(r => r.isEqual);\n const areStatesExactlyEqual = await areStatesExactlyEqualPromise;\n\n if (\n forkStateDocData &&\n areStatesExactlyEqual\n ) {\n /**\n * Document states are exactly equal.\n * This can happen when the replication is shut down\n * unexpected like when the user goes offline.\n *\n * Only when the assumedMaster is different from the forkState,\n * we have to patch the document in the meta instance.\n */\n if (\n !assumedMaster ||\n isAssumedMasterEqualToForkState === false\n ) {\n useMetaWriteRows.push(\n getMetaWriteRow(\n state,\n forkStateDocData,\n assumedMaster ? assumedMaster.metaDocument : undefined\n )\n );\n }\n return PROMISE_RESOLVE_VOID;\n }\n\n /**\n * All other master states need to be written to the forkInstance\n * and metaInstance.\n */\n const newForkState = Object.assign(\n {},\n masterState,\n forkStateFullDoc ? {\n _meta: flatClone(forkStateFullDoc._meta),\n _attachments: {},\n _rev: getDefaultRevision()\n } : {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n });\n\n\n /**\n * TODO for unknown reason we need\n * to manually set the lwt and the _rev here\n * to fix the pouchdb tests. This is not required for\n * the other RxStorage implementations which means something is wrong.\n */\n newForkState._meta.lwt = now();\n newForkState._rev = (masterState as any)._rev ? (masterState as any)._rev : createRevision(\n state.input.hashFunction,\n newForkState,\n forkStateFullDoc\n );\n\n /**\n * If the remote works with revisions,\n * we store the height of the next fork-state revision\n * inside of the documents meta data.\n * By doing so we can filter it out in the upstream\n * and detect the document as being equal to master or not.\n * This is used for example in the CouchDB replication plugin.\n */\n if ((masterState as any)._rev) {\n const nextRevisionHeight = !forkStateFullDoc ? 1 : parseRevision(forkStateFullDoc._rev).height + 1;\n newForkState._meta[state.input.identifier] = nextRevisionHeight;\n }\n\n const forkWriteRow = {\n previous: forkStateFullDoc,\n document: newForkState\n };\n\n writeRowsToFork.push(forkWriteRow);\n writeRowsToForkById[docId] = forkWriteRow;\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n masterState,\n assumedMaster ? assumedMaster.metaDocument : undefined\n );\n })\n );\n }).then(() => {\n if (writeRowsToFork.length > 0) {\n return state.input.forkInstance.bulkWrite(\n writeRowsToFork,\n state.downstreamBulkWriteFlag\n ).then((forkWriteResult) => {\n Object.keys(forkWriteResult.success).forEach((docId) => {\n state.events.processed.down.next(writeRowsToForkById[docId]);\n useMetaWriteRows.push(writeRowsToMeta[docId]);\n });\n });\n }\n }).then(() => {\n if (useMetaWriteRows.length > 0) {\n return state.input.metaInstance.bulkWrite(\n useMetaWriteRows,\n 'replication-down-write-meta'\n );\n }\n }).then(() => {\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'down',\n useCheckpoint\n ));\n });\n }).catch(unhandledError => state.events.error.next(unhandledError));\n return persistenceQueue;\n }\n}\n"],"mappings":";;;;;;AAAA;AAIA;AAWA;AAWA;AAIA;AACA;AAQO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACK,IAAI,EAAE;MACxBL,KAAK,CAACK,IAAI,CAAC,QAAQD,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAE,CAAC,CAAC,CAAC;MACxE;IACD;IACAA,IAAI,CAACG,CAAC,GAAGF,KAAK;IACdD,IAAI,CAACI,CAAC,GAAGF,KAAK;IACd,IAAMM,QAAQ,GAAGR,IAAI,CAACK,CAAC;IACvB,IAAIG,QAAQ,EAAE;MACbA,QAAQ,CAACR,IAAI,CAAC;IACf;EACD;AACD;AA9DO,IAAM,QAAQ,aAAc,YAAW;EAC7C,iBAAiB,CAAC;EAClB,MAAMS,SAAS,CAACF,IAAI,GAAG,UAASG,WAAW,EAAEC,UAAU,EAAE;IACxD,IAAMC,MAAM,GAAG,WAAW;IAC1B,IAAMX,KAAK,GAAG,IAAI,CAACE,CAAC;IACpB,IAAIF,KAAK,EAAE;MACV,IAAMY,QAAQ,GAAGZ,KAAK,GAAG,CAAC,GAAGS,WAAW,GAAGC,UAA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C7C,gBAAgB,EAChB,6BAA6B,CAChC;QACL;MACJ,CAAC,CAAC,CAACxF,IAAI,CAAC,YAAM;QACV;AAChB;AACA;AACA;AACA;QACgBN,KAAK,CAACiC,eAAe,GAAGjC,KAAK,CAACiC,eAAe,CAAC3B,IAAI,CAAC;UAAA,OAAM,IAAA2I,yBAAa,EAClEjJ,KAAK,EACL,MAAM,EACNuF,aAAa,CAChB;QAAA,EAAC;MACN,CAAC,CAAC;IACN,CAAC,CAAC,SAAM,CAAC,UAAA2D,cAAc;MAAA,OAAIlJ,KAAK,CAAC8B,MAAM,CAACqH,KAAK,CAACvF,IAAI,CAACsF,cAAc,CAAC;IAAA,EAAC;IACnE,OAAOnE,gBAAgB;EAC3B;AACJ"} \ No newline at end of file +{"version":3,"file":"downstream.js","names":["startReplicationDownstream","state","replicationHandler","input","timer","openTasks","addNewTask","task","stats","down","taskWithTime","time","push","streamQueue","then","useTasks","length","events","active","next","innerTaskWithTime","ensureNotFalsy","shift","lastTimeMasterChangesRequested","downstreamResyncOnce","downstreamProcessChanges","firstSyncDone","getValue","sub","masterChangeStream$","subscribe","masterChangeStreamEmit","firstValueFrom","canceled","pipe","filter","unsubscribe","checkpointQueue","getLastCheckpointDoc","lastCheckpoint","promises","masterChangesSince","pullBatchSize","downResult","documents","stackCheckpoints","checkpoint","persistFromMaster","Promise","all","tasks","docsOfAllTasks","forEach","Error","concat","persistenceQueue","PROMISE_RESOLVE_VOID","nonPersistedFromMaster","docs","docData","docId","primaryPath","downDocsById","useCheckpoint","docIds","Object","keys","writeRowsToFork","writeRowsToForkById","writeRowsToMeta","useMetaWriteRows","forkInstance","findDocumentsById","getAssumedMasterState","currentForkState","assumedMasterState","map","forkStateFullDoc","forkStateDocData","writeDocToDocState","undefined","masterState","assumedMaster","metaDocument","isResolvedConflict","_rev","isAssumedMasterEqualToForkStatePromise","PROMISE_RESOLVE_FALSE","conflictHandler","realMasterState","newDocumentState","r","isEqual","isAssumedMasterEqualToForkState","_meta","identifier","parseRevision","height","areStatesExactlyEqualPromise","areStatesExactlyEqual","getMetaWriteRow","newForkState","assign","flatClone","_attachments","getDefaultRevision","getDefaultRxDocumentMeta","nextRevisionHeight","forkWriteRow","previous","document","bulkWrite","downstreamBulkWriteFlag","forkWriteResult","success","processed","values","error","status","newRxError","writeError","metaInstance","setCheckpoint","unhandledError"],"sources":["../../../src/replication-protocol/downstream.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter\n} from 'rxjs';\nimport { newRxError } from '../rx-error';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n RxStorageInstanceReplicationState,\n BulkWriteRow,\n BulkWriteRowById,\n RxStorageReplicationMeta,\n RxDocumentData,\n ById,\n WithDeleted,\n DocumentsWithCheckpoint\n} from '../types';\nimport {\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n parseRevision,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all documents from the master to the fork.\n * The downstream has two operation modes\n * - Sync by iterating over the checkpoints via downstreamResyncOnce()\n * - Sync by listening to the changestream via downstreamProcessChanges()\n * We need this to be able to do initial syncs\n * and still can have fast event based sync when the client is not offline.\n */\nexport function startReplicationDownstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n\n\n type Task = DocumentsWithCheckpoint | 'RESYNC';\n type TaskWithTime = {\n time: number;\n task: Task;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n function addNewTask(task: Task): void {\n state.stats.down.addNewTask = state.stats.down.addNewTask + 1;\n const taskWithTime = {\n time: timer++,\n task\n };\n openTasks.push(taskWithTime);\n state.streamQueue.down = state.streamQueue.down\n .then(() => {\n const useTasks: Task[] = [];\n while (openTasks.length > 0) {\n state.events.active.down.next(true);\n const innerTaskWithTime = ensureNotFalsy(openTasks.shift());\n\n /**\n * If the task came in before the last time we started the pull\n * from the master, then we can drop the task.\n */\n if (innerTaskWithTime.time < lastTimeMasterChangesRequested) {\n continue;\n }\n\n if (innerTaskWithTime.task === 'RESYNC') {\n if (useTasks.length === 0) {\n useTasks.push(innerTaskWithTime.task);\n break;\n } else {\n break;\n }\n }\n\n useTasks.push(innerTaskWithTime.task);\n }\n\n if (useTasks.length === 0) return;\n\n if (useTasks[0] === 'RESYNC') {\n return downstreamResyncOnce();\n } else {\n return downstreamProcessChanges(useTasks);\n }\n }).then(() => {\n state.events.active.down.next(false);\n if (!state.firstSyncDone.down.getValue()) {\n state.firstSyncDone.down.next(true);\n }\n });\n }\n addNewTask('RESYNC');\n\n /**\n * If a write on the master happens, we have to trigger the downstream.\n */\n const sub = replicationHandler\n .masterChangeStream$\n .subscribe((task: Task) => {\n state.stats.down.masterChangeStreamEmit = state.stats.down.masterChangeStreamEmit + 1;\n addNewTask(task);\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n /**\n * For faster performance, we directly start each write\n * and then await all writes at the end.\n */\n let lastTimeMasterChangesRequested: number = -1;\n async function downstreamResyncOnce() {\n state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'down'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n lastTimeMasterChangesRequested = timer++;\n const downResult = await replicationHandler.masterChangesSince(\n lastCheckpoint,\n state.input.pullBatchSize\n );\n\n if (downResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, downResult.checkpoint]);\n\n promises.push(\n persistFromMaster(\n downResult.documents,\n lastCheckpoint\n )\n );\n\n /**\n * By definition we stop pull when the pulled documents\n * do not fill up the pullBatchSize because we\n * can assume that the remote has no more documents.\n */\n if (downResult.documents.length < state.input.pullBatchSize) {\n break;\n }\n\n }\n await Promise.all(promises);\n }\n\n\n function downstreamProcessChanges(tasks: Task[]) {\n state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1;\n let docsOfAllTasks: WithDeleted[] = [];\n let lastCheckpoint: CheckpointType | undefined = null as any;\n\n tasks.forEach(task => {\n if (task === 'RESYNC') {\n throw new Error('SNH');\n }\n docsOfAllTasks = docsOfAllTasks.concat(task.documents);\n lastCheckpoint = stackCheckpoints([lastCheckpoint, task.checkpoint]);\n });\n return persistFromMaster(\n docsOfAllTasks,\n ensureNotFalsy(lastCheckpoint)\n );\n }\n\n\n /**\n * It can happen that the calls to masterChangesSince() or the changeStream()\n * are way faster then how fast the documents can be persisted.\n * Therefore we merge all incoming downResults into the nonPersistedFromMaster object\n * and process them together if possible.\n * This often bundles up single writes and improves performance\n * by processing the documents in bulks.\n */\n let persistenceQueue = PROMISE_RESOLVE_VOID;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n function persistFromMaster(\n docs: WithDeleted[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.down.persistFromMaster = state.stats.down.persistFromMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n /**\n * Run in the queue\n * with all open documents from nonPersistedFromMaster.\n */\n persistenceQueue = persistenceQueue.then(() => {\n const downDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(downDocsById);\n\n if (\n state.events.canceled.getValue() ||\n docIds.length === 0\n ) {\n return PROMISE_RESOLVE_VOID;\n }\n\n const writeRowsToFork: BulkWriteRow[] = [];\n const writeRowsToForkById: ById> = {};\n const writeRowsToMeta: BulkWriteRowById = {};\n const useMetaWriteRows: BulkWriteRow[] = [];\n\n return Promise.all([\n state.input.forkInstance.findDocumentsById(docIds, true),\n getAssumedMasterState(\n state,\n docIds\n )\n ]).then(([\n currentForkState,\n assumedMasterState\n ]) => {\n return Promise.all(\n docIds.map(async (docId) => {\n const forkStateFullDoc: RxDocumentData | undefined = currentForkState[docId];\n const forkStateDocData: WithDeleted | undefined = forkStateFullDoc ? writeDocToDocState(forkStateFullDoc) : undefined;\n const masterState = downDocsById[docId];\n const assumedMaster = assumedMasterState[docId];\n\n if (\n assumedMaster &&\n assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev\n ) {\n /**\n * The current fork state represents a resolved conflict\n * that first must be send to the master in the upstream.\n * All conflicts are resolved by the upstream.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n const isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: assumedMaster.docData,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-0').then(r => r.isEqual);\n let isAssumedMasterEqualToForkState = await isAssumedMasterEqualToForkStatePromise;\n\n if (\n !isAssumedMasterEqualToForkState &&\n (\n assumedMaster &&\n (assumedMaster.docData as any)._rev &&\n forkStateFullDoc._meta[state.input.identifier] &&\n parseRevision(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]\n )\n ) {\n isAssumedMasterEqualToForkState = true;\n }\n if (\n (\n forkStateFullDoc &&\n assumedMaster &&\n isAssumedMasterEqualToForkState === false\n ) ||\n (\n forkStateFullDoc && !assumedMaster\n )\n ) {\n /**\n * We have a non-upstream-replicated\n * local write to the fork.\n * This means we ignore the downstream of this document\n * because anyway the upstream will first resolve the conflict.\n */\n return PROMISE_RESOLVE_VOID;\n }\n\n\n const areStatesExactlyEqualPromise = !forkStateDocData ?\n PROMISE_RESOLVE_FALSE :\n state.input.conflictHandler({\n realMasterState: masterState,\n newDocumentState: forkStateDocData\n }, 'downstream-check-if-equal-1').then(r => r.isEqual);\n const areStatesExactlyEqual = await areStatesExactlyEqualPromise;\n\n if (\n forkStateDocData &&\n areStatesExactlyEqual\n ) {\n /**\n * Document states are exactly equal.\n * This can happen when the replication is shut down\n * unexpected like when the user goes offline.\n *\n * Only when the assumedMaster is different from the forkState,\n * we have to patch the document in the meta instance.\n */\n if (\n !assumedMaster ||\n isAssumedMasterEqualToForkState === false\n ) {\n useMetaWriteRows.push(\n getMetaWriteRow(\n state,\n forkStateDocData,\n assumedMaster ? assumedMaster.metaDocument : undefined\n )\n );\n }\n return PROMISE_RESOLVE_VOID;\n }\n\n /**\n * All other master states need to be written to the forkInstance\n * and metaInstance.\n */\n const newForkState = Object.assign(\n {},\n masterState,\n forkStateFullDoc ? {\n _meta: flatClone(forkStateFullDoc._meta),\n _attachments: {},\n _rev: getDefaultRevision()\n } : {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n });\n\n /**\n * If the remote works with revisions,\n * we store the height of the next fork-state revision\n * inside of the documents meta data.\n * By doing so we can filter it out in the upstream\n * and detect the document as being equal to master or not.\n * This is used for example in the CouchDB replication plugin.\n */\n if ((masterState as any)._rev) {\n const nextRevisionHeight = !forkStateFullDoc ? 1 : parseRevision(forkStateFullDoc._rev).height + 1;\n newForkState._meta[state.input.identifier] = nextRevisionHeight;\n }\n\n const forkWriteRow = {\n previous: forkStateFullDoc,\n document: newForkState\n };\n\n writeRowsToFork.push(forkWriteRow);\n writeRowsToForkById[docId] = forkWriteRow;\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n masterState,\n assumedMaster ? assumedMaster.metaDocument : undefined\n );\n })\n );\n }).then(() => {\n if (writeRowsToFork.length > 0) {\n return state.input.forkInstance.bulkWrite(\n writeRowsToFork,\n state.downstreamBulkWriteFlag\n ).then((forkWriteResult) => {\n Object.keys(forkWriteResult.success).forEach((docId) => {\n state.events.processed.down.next(writeRowsToForkById[docId]);\n useMetaWriteRows.push(writeRowsToMeta[docId]);\n });\n Object.values(forkWriteResult.error).forEach(error => {\n /**\n * We do not have to care about downstream conflict errors here\n * because on conflict, it will be solved locally and result in another write.\n */\n if (error.status === 409) {\n return;\n }\n // other non-conflict errors must be handled\n state.events.error.next(newRxError('RC_PULL', {\n writeError: error\n }));\n });\n });\n }\n }).then(() => {\n if (useMetaWriteRows.length > 0) {\n return state.input.metaInstance.bulkWrite(\n useMetaWriteRows,\n 'replication-down-write-meta'\n );\n }\n }).then(() => {\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'down',\n useCheckpoint\n ));\n });\n }).catch(unhandledError => state.events.error.next(unhandledError));\n return persistenceQueue;\n }\n}\n"],"mappings":";;;;;;;;;AAAA;AAIA;AACA;AAWA;AASA;AAIA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,0BAA0B,CACtCC,KAAmD,EACrD;EACE,IAAMC,kBAAkB,GAAGD,KAAK,CAACE,KAAK,CAACD,kBAAkB;;EAEzD;EACA,IAAIE,KAAK,GAAG,CAAC;EAQb,IAAMC,SAAyB,GAAG,EAAE;EAGpC,SAASC,UAAU,CAACC,IAAU,EAAQ;IAClCN,KAAK,CAACO,KAAK,CAACC,IAAI,CAACH,UAAU,GAAGL,KAAK,CAACO,KAAK,CAACC,IAAI,CAACH,UAAU,GAAG,CAAC;IAC7D,IAAMI,YAAY,GAAG;MACjBC,IAAI,EAAEP,KAAK,EAAE;MACbG,IAAI,EAAJA;IACJ,CAAC;IACDF,SAAS,CAACO,IAAI,CAACF,YAAY,CAAC;IAC5BT,KAAK,CAACY,WAAW,CAACJ,IAAI,G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AACQ,KAAK,EAAK;cACpD3D,KAAK,CAACgB,MAAM,CAACkG,SAAS,CAAC1G,IAAI,CAACU,IAAI,CAACiD,mBAAmB,CAACR,KAAK,CAAC,CAAC;cAC5DU,gBAAgB,CAAC1D,IAAI,CAACyD,eAAe,CAACT,KAAK,CAAC,CAAC;YACjD,CAAC,CAAC;YACFK,MAAM,CAACmD,MAAM,CAACH,eAAe,CAACI,KAAK,CAAC,CAACjE,OAAO,CAAC,UAAAiE,KAAK,EAAI;cAClD;AAC5B;AACA;AACA;cAC4B,IAAIA,KAAK,CAACC,MAAM,KAAK,GAAG,EAAE;gBACtB;cACJ;cACA;cACArH,KAAK,CAACgB,MAAM,CAACoG,KAAK,CAAClG,IAAI,CAAC,IAAAoG,mBAAU,EAAC,SAAS,EAAE;gBAC1CC,UAAU,EAAEH;cAChB,CAAC,CAAC,CAAC;YACP,CAAC,CAAC;UACN,CAAC,CAAC;QACN;MACJ,CAAC,CAAC,CAACvG,IAAI,CAAC,YAAM;QACV,IAAIwD,gBAAgB,CAACtD,MAAM,GAAG,CAAC,EAAE;UAC7B,OAAOf,KAAK,CAACE,KAAK,CAACsH,YAAY,CAACV,SAAS,CACrCzC,gBAAgB,EAChB,6BAA6B,CAChC;QACL;MACJ,CAAC,CAAC,CAACxD,IAAI,CAAC,YAAM;QACV;AAChB;AACA;AACA;AACA;QACgBb,KAAK,CAACoC,eAAe,GAAGpC,KAAK,CAACoC,eAAe,CAACvB,IAAI,CAAC;UAAA,OAAM,IAAA4G,yBAAa,EAClEzH,KAAK,EACL,MAAM,EACN8D,aAAa,CAChB;QAAA,EAAC;MACN,CAAC,CAAC;IACN,CAAC,CAAC,SAAM,CAAC,UAAA4D,cAAc;MAAA,OAAI1H,KAAK,CAACgB,MAAM,CAACoG,KAAK,CAAClG,IAAI,CAACwG,cAAc,CAAC;IAAA,EAAC;IACnE,OAAOpE,gBAAgB;EAC3B;AACJ"} \ No newline at end of file diff --git a/dist/lib/replication-protocol/helper.js b/dist/lib/replication-protocol/helper.js index fecd42ebf25..1d4065e7a19 100644 --- a/dist/lib/replication-protocol/helper.js +++ b/dist/lib/replication-protocol/helper.js @@ -5,20 +5,20 @@ Object.defineProperty(exports, "__esModule", { }); exports.docStateToWriteDoc = docStateToWriteDoc; exports.writeDocToDocState = writeDocToDocState; -var _util = require("../util"); -function docStateToWriteDoc(hashFunction, docState, previous) { +var _utils = require("../plugins/utils"); +function docStateToWriteDoc(databaseInstanceToken, docState, previous) { var docData = Object.assign({}, docState, { _attachments: {}, _meta: { - lwt: (0, _util.now)() + lwt: (0, _utils.now)() }, - _rev: (0, _util.getDefaultRevision)() + _rev: (0, _utils.getDefaultRevision)() }); - docData._rev = (0, _util.createRevision)(hashFunction, docData, previous); + docData._rev = (0, _utils.createRevision)(databaseInstanceToken, previous); return docData; } function writeDocToDocState(writeDoc) { - var ret = (0, _util.flatClone)(writeDoc); + var ret = (0, _utils.flatClone)(writeDoc); delete ret._attachments; delete ret._meta; delete ret._rev; diff --git a/dist/lib/replication-protocol/helper.js.map b/dist/lib/replication-protocol/helper.js.map index ff121095176..818677efaae 100644 --- a/dist/lib/replication-protocol/helper.js.map +++ b/dist/lib/replication-protocol/helper.js.map @@ -1 +1 @@ -{"version":3,"file":"helper.js","names":["docStateToWriteDoc","hashFunction","docState","previous","docData","Object","assign","_attachments","_meta","lwt","now","_rev","getDefaultRevision","createRevision","writeDocToDocState","writeDoc","ret","flatClone"],"sources":["../../../src/replication-protocol/helper.ts"],"sourcesContent":["import type {\n HashFunction,\n RxDocumentData,\n WithDeleted\n} from '../types';\nimport {\n createRevision,\n flatClone,\n getDefaultRevision,\n now\n} from '../util';\n\nexport function docStateToWriteDoc(\n hashFunction: HashFunction,\n docState: WithDeleted,\n previous?: RxDocumentData\n): RxDocumentData {\n const docData: RxDocumentData = Object.assign(\n {},\n docState,\n {\n _attachments: {},\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision()\n }\n );\n docData._rev = createRevision(\n hashFunction,\n docData,\n previous\n );\n return docData;\n}\n\nexport function writeDocToDocState(\n writeDoc: RxDocumentData\n): WithDeleted {\n const ret = flatClone(writeDoc);\n delete (ret as any)._attachments;\n delete (ret as any)._meta;\n delete (ret as any)._rev;\n return ret;\n}\n"],"mappings":";;;;;;;AAKA;AAOO,SAASA,kBAAkB,CAC9BC,YAA0B,EAC1BC,QAAgC,EAChCC,QAAoC,EACX;EACzB,IAAMC,OAAkC,GAAGC,MAAM,CAACC,MAAM,CACpD,CAAC,CAAC,EACFJ,QAAQ,EACR;IACIK,YAAY,EAAE,CAAC,CAAC;IAChBC,KAAK,EAAE;MACHC,GAAG,EAAE,IAAAC,SAAG;IACZ,CAAC;IACDC,IAAI,EAAE,IAAAC,wBAAkB;EAC5B,CAAC,CACJ;EACDR,OAAO,CAACO,IAAI,GAAG,IAAAE,oBAAc,EACzBZ,YAAY,EACZG,OAAO,EACPD,QAAQ,CACX;EACD,OAAOC,OAAO;AAClB;AAEO,SAASU,kBAAkB,CAC9BC,QAAmC,EACb;EACtB,IAAMC,GAAG,GAAG,IAAAC,eAAS,EAACF,QAAQ,CAAC;EAC/B,OAAQC,GAAG,CAAST,YAAY;EAChC,OAAQS,GAAG,CAASR,KAAK;EACzB,OAAQQ,GAAG,CAASL,IAAI;EACxB,OAAOK,GAAG;AACd"} \ No newline at end of file +{"version":3,"file":"helper.js","names":["docStateToWriteDoc","databaseInstanceToken","docState","previous","docData","Object","assign","_attachments","_meta","lwt","now","_rev","getDefaultRevision","createRevision","writeDocToDocState","writeDoc","ret","flatClone"],"sources":["../../../src/replication-protocol/helper.ts"],"sourcesContent":["import type {\n RxDocumentData,\n WithDeleted\n} from '../types';\nimport {\n createRevision,\n flatClone,\n getDefaultRevision,\n now\n} from '../plugins/utils';\n\nexport function docStateToWriteDoc(\n databaseInstanceToken: string,\n docState: WithDeleted,\n previous?: RxDocumentData\n): RxDocumentData {\n const docData: RxDocumentData = Object.assign(\n {},\n docState,\n {\n _attachments: {},\n _meta: {\n lwt: now()\n },\n _rev: getDefaultRevision()\n }\n );\n docData._rev = createRevision(\n databaseInstanceToken,\n previous\n );\n return docData;\n}\n\nexport function writeDocToDocState(\n writeDoc: RxDocumentData\n): WithDeleted {\n const ret = flatClone(writeDoc);\n delete (ret as any)._attachments;\n delete (ret as any)._meta;\n delete (ret as any)._rev;\n return ret;\n}\n"],"mappings":";;;;;;;AAIA;AAOO,SAASA,kBAAkB,CAC9BC,qBAA6B,EAC7BC,QAAgC,EAChCC,QAAoC,EACX;EACzB,IAAMC,OAAkC,GAAGC,MAAM,CAACC,MAAM,CACpD,CAAC,CAAC,EACFJ,QAAQ,EACR;IACIK,YAAY,EAAE,CAAC,CAAC;IAChBC,KAAK,EAAE;MACHC,GAAG,EAAE,IAAAC,UAAG;IACZ,CAAC;IACDC,IAAI,EAAE,IAAAC,yBAAkB;EAC5B,CAAC,CACJ;EACDR,OAAO,CAACO,IAAI,GAAG,IAAAE,qBAAc,EACzBZ,qBAAqB,EACrBE,QAAQ,CACX;EACD,OAAOC,OAAO;AAClB;AAEO,SAASU,kBAAkB,CAC9BC,QAAmC,EACb;EACtB,IAAMC,GAAG,GAAG,IAAAC,gBAAS,EAACF,QAAQ,CAAC;EAC/B,OAAQC,GAAG,CAAST,YAAY;EAChC,OAAQS,GAAG,CAASR,KAAK;EACzB,OAAQQ,GAAG,CAASL,IAAI;EACxB,OAAOK,GAAG;AACd"} \ No newline at end of file diff --git a/dist/lib/replication-protocol/index.js b/dist/lib/replication-protocol/index.js index 1e321fadcc4..8a5354dc378 100644 --- a/dist/lib/replication-protocol/index.js +++ b/dist/lib/replication-protocol/index.js @@ -1,25 +1,28 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { - awaitRxStorageReplicationIdle: true, replicateRxStorageInstance: true, awaitRxStorageReplicationFirstInSync: true, awaitRxStorageReplicationInSync: true, + awaitRxStorageReplicationIdle: true, rxStorageInstanceToReplicationHandler: true, cancelRxStorageReplication: true }; exports.awaitRxStorageReplicationFirstInSync = awaitRxStorageReplicationFirstInSync; -exports.awaitRxStorageReplicationIdle = void 0; +exports.awaitRxStorageReplicationIdle = awaitRxStorageReplicationIdle; exports.awaitRxStorageReplicationInSync = awaitRxStorageReplicationInSync; exports.cancelRxStorageReplication = cancelRxStorageReplication; exports.replicateRxStorageInstance = replicateRxStorageInstance; exports.rxStorageInstanceToReplicationHandler = rxStorageInstanceToReplicationHandler; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _rxSchemaHelper = require("../rx-schema-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _checkpoint = require("./checkpoint"); Object.keys(_checkpoint).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -92,187 +95,12 @@ Object.keys(_conflicts).forEach(function (key) { } }); }); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} /** * These files contain the replication protocol. * It can be used to replicated RxStorageInstances or RxCollections * or even to do a client(s)-server replication. */ -var awaitRxStorageReplicationIdle = function awaitRxStorageReplicationIdle(state) { - try { - return Promise.resolve(awaitRxStorageReplicationFirstInSync(state)).then(function () { - var _exit = false; - return _for(function () { - return !_exit; - }, void 0, function () { - var _state$streamQueue = state.streamQueue, - down = _state$streamQueue.down, - up = _state$streamQueue.up; - return Promise.resolve(Promise.all([up, down])).then(function () { - if (down === state.streamQueue.down && up === state.streamQueue.up) { - _exit = true; - } - }); - /** - * If the Promises have not been reasigned - * after awaiting them, we know that the replication - * is in idle state at this point in time. - */ - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.awaitRxStorageReplicationIdle = awaitRxStorageReplicationIdle; + function replicateRxStorageInstance(input) { var checkpointKey = (0, _checkpoint.getCheckpointKey)(input); var state = { @@ -315,10 +143,10 @@ function replicateRxStorageInstance(input) { up: new _rxjs.BehaviorSubject(false) }, streamQueue: { - down: _util.PROMISE_RESOLVE_VOID, - up: _util.PROMISE_RESOLVE_VOID + down: _utils.PROMISE_RESOLVE_VOID, + up: _utils.PROMISE_RESOLVE_VOID }, - checkpointQueue: _util.PROMISE_RESOLVE_VOID, + checkpointQueue: _utils.PROMISE_RESOLVE_VOID, lastCheckpointDoc: {} }; (0, _downstream.startReplicationDownstream)(state); @@ -335,14 +163,50 @@ function awaitRxStorageReplicationFirstInSync(state) { function awaitRxStorageReplicationInSync(replicationState) { return Promise.all([replicationState.streamQueue.up, replicationState.streamQueue.down, replicationState.checkpointQueue]); } -function rxStorageInstanceToReplicationHandler(instance, conflictHandler, hashFunction) { +function awaitRxStorageReplicationIdle(_x) { + return _awaitRxStorageReplicationIdle.apply(this, arguments); +} +function _awaitRxStorageReplicationIdle() { + _awaitRxStorageReplicationIdle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(state) { + var _state$streamQueue, down, up; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return awaitRxStorageReplicationFirstInSync(state); + case 2: + if (!true) { + _context3.next = 10; + break; + } + _state$streamQueue = state.streamQueue, down = _state$streamQueue.down, up = _state$streamQueue.up; + _context3.next = 6; + return Promise.all([up, down]); + case 6: + if (!(down === state.streamQueue.down && up === state.streamQueue.up)) { + _context3.next = 8; + break; + } + return _context3.abrupt("return"); + case 8: + _context3.next = 2; + break; + case 10: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _awaitRxStorageReplicationIdle.apply(this, arguments); +} +function rxStorageInstanceToReplicationHandler(instance, conflictHandler, databaseInstanceToken) { var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(instance.schema.primaryKey); var replicationHandler = { masterChangeStream$: instance.changeStream().pipe((0, _rxjs.map)(function (eventBulk) { var ret = { checkpoint: eventBulk.checkpoint, documents: eventBulk.events.map(function (event) { - return (0, _helper.writeDocToDocState)((0, _util.ensureNotFalsy)(event.documentData)); + return (0, _helper.writeDocToDocState)((0, _utils.ensureNotFalsy)(event.documentData)); }) }; return ret; @@ -357,75 +221,109 @@ function rxStorageInstanceToReplicationHandler(instance, conflictHandler, hashFu }; }); }, - masterWrite: function masterWrite(rows) { - try { - var rowById = {}; - rows.forEach(function (row) { - var docId = row.newDocumentState[primaryPath]; - rowById[docId] = row; - }); - var ids = Object.keys(rowById); - return Promise.resolve(instance.findDocumentsById(ids, true)).then(function (masterDocsState) { - var conflicts = []; - var writeRows = []; - return Promise.resolve(Promise.all(Object.entries(rowById).map(function (_ref) { - try { - var id = _ref[0], - row = _ref[1]; - var masterState = masterDocsState[id]; - var _temp3 = function () { - if (!masterState) { - writeRows.push({ - document: (0, _helper.docStateToWriteDoc)(hashFunction, row.newDocumentState) - }); - } else { - var _temp4 = function () { - if (masterState && !row.assumedMasterState) { - conflicts.push((0, _helper.writeDocToDocState)(masterState)); - } else return Promise.resolve(conflictHandler({ - realMasterState: (0, _helper.writeDocToDocState)(masterState), - newDocumentState: (0, _util.ensureNotFalsy)(row.assumedMasterState) - }, 'rxStorageInstanceToReplicationHandler-masterWrite')).then(function (_conflictHandler) { - if (_conflictHandler.isEqual === true) { + masterWrite: function () { + var _masterWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rows) { + var rowById, ids, masterDocsState, conflicts, writeRows, result; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + rowById = {}; + rows.forEach(function (row) { + var docId = row.newDocumentState[primaryPath]; + rowById[docId] = row; + }); + ids = Object.keys(rowById); + _context2.next = 5; + return instance.findDocumentsById(ids, true); + case 5: + masterDocsState = _context2.sent; + conflicts = []; + writeRows = []; + _context2.next = 10; + return Promise.all(Object.entries(rowById).map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_ref) { + var id, row, masterState; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + id = _ref[0], row = _ref[1]; + masterState = masterDocsState[id]; + if (masterState) { + _context.next = 6; + break; + } + writeRows.push({ + document: (0, _helper.docStateToWriteDoc)(databaseInstanceToken, row.newDocumentState) + }); + _context.next = 18; + break; + case 6: + if (!(masterState && !row.assumedMasterState)) { + _context.next = 10; + break; + } + conflicts.push((0, _helper.writeDocToDocState)(masterState)); + _context.next = 18; + break; + case 10: + _context.next = 12; + return conflictHandler({ + realMasterState: (0, _helper.writeDocToDocState)(masterState), + newDocumentState: (0, _utils.ensureNotFalsy)(row.assumedMasterState) + }, 'rxStorageInstanceToReplicationHandler-masterWrite'); + case 12: + _context.t0 = _context.sent.isEqual; + if (!(_context.t0 === true)) { + _context.next = 17; + break; + } writeRows.push({ previous: masterState, - document: (0, _helper.docStateToWriteDoc)(hashFunction, row.newDocumentState, masterState) + document: (0, _helper.docStateToWriteDoc)(databaseInstanceToken, row.newDocumentState, masterState) }); - } else { + _context.next = 18; + break; + case 17: conflicts.push((0, _helper.writeDocToDocState)(masterState)); - } - }); - }(); - if (_temp4 && _temp4.then) return _temp4.then(function () {}); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp = function () { - if (writeRows.length > 0) { - return Promise.resolve(instance.bulkWrite(writeRows, 'replication-master-write')).then(function (result) { - Object.values(result.error).forEach(function (err) { - if (err.status !== 409) { - throw new Error('non conflict error'); - } else { - conflicts.push((0, _helper.writeDocToDocState)((0, _util.ensureNotFalsy)(err.documentInDb))); + case 18: + case "end": + return _context.stop(); } - }); - }); + }, _callee); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }())); + case 10: + if (!(writeRows.length > 0)) { + _context2.next = 15; + break; } - }(); - return _temp && _temp.then ? _temp.then(function () { - return conflicts; - }) : conflicts; - }); - }); - } catch (e) { - return Promise.reject(e); + _context2.next = 13; + return instance.bulkWrite(writeRows, 'replication-master-write'); + case 13: + result = _context2.sent; + Object.values(result.error).forEach(function (err) { + if (err.status !== 409) { + throw new Error('non conflict error'); + } else { + conflicts.push((0, _helper.writeDocToDocState)((0, _utils.ensureNotFalsy)(err.documentInDb))); + } + }); + case 15: + return _context2.abrupt("return", conflicts); + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function masterWrite(_x2) { + return _masterWrite.apply(this, arguments); } - } + return masterWrite; + }() }; return replicationHandler; } diff --git a/dist/lib/replication-protocol/index.js.map b/dist/lib/replication-protocol/index.js.map index 8b750313ea4..ac16f0cf512 100644 --- a/dist/lib/replication-protocol/index.js.map +++ b/dist/lib/replication-protocol/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","awaitRxStorageReplicationIdle","awaitRxStorageReplicationFirstInSync","streamQueue","down","up","Promise","all","replicateRxStorageInstance","input","checkpointKey","getCheckpointKey","primaryPath","getPrimaryFieldOfPrimaryKey","forkInstance","schema","primaryKey","downstreamBulkWriteFlag","events","canceled","BehaviorSubject","active","processed","Subject","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","PROMISE_RESOLVE_VOID","checkpointQueue","lastCheckpointDoc","startReplicationDownstream","startReplicationUpstream","firstValueFrom","combineLatest","pipe","filter","awaitRxStorageReplicationInSync","replicationState","rxStorageInstanceToReplicationHandler","instance","conflictHandler","hashFunction","replicationHandler","masterChangeStream$","changeStream","map","eventBulk","ret","checkpoint","documents","event","writeDocToDocState","ensureNotFalsy","documentData","masterChangesSince","batchSize","getChangedDocumentsSince","length","d","masterWrite","rows","rowById","forEach","row","docId","newDocumentState","ids","Object","keys","findDocumentsById","masterDocsState","conflicts","writeRows","entries","id","masterState","push","document","docStateToWriteDoc","assumedMasterState","realMasterState","isEqual","previous","bulkWrite","values","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n map,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n HashFunction,\n RxConflictHandler,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types';\nimport {\n ensureNotFalsy,\n PROMISE_RESOLVE_VOID\n} from '../util';\nimport {\n getCheckpointKey\n} from './checkpoint';\nimport { startReplicationDownstream } from './downstream';\nimport { docStateToWriteDoc, writeDocToDocState } from './helper';\nimport { startReplicationUpstream } from './upstream';\n\n\nexport * from './checkpoint';\nexport * from './downstream';\nexport * from './upstream';\nexport * from './meta-instance';\nexport * from './conflicts';\nexport * from './helper';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n const checkpointKey = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n input,\n checkpointKey,\n downstreamBulkWriteFlag: 'replication-downstream-' + checkpointKey,\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reasigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n hashFunction: HashFunction\n): RxReplicationHandler {\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n map(eventBulk => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: eventBulk.events.map(event => {\n return writeDocToDocState(ensureNotFalsy(event.documentData) as any);\n })\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return instance.getChangedDocumentsSince(\n batchSize,\n checkpoint\n ).then(result => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: result.documents.map(d => writeDocToDocState(d))\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsState = await instance.findDocumentsById(\n ids,\n true\n );\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState[id];\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(hashFunction, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(hashFunction, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState));\n }\n })\n );\n\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n Object\n .values(result.error)\n .forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb))\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;AAQA;AAgBA;AAIA;AAQA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AALA;AAMA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AALA;AASA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AARA;AAKA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AARO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;M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,CAAC+E,QAAQ,EAAE;EACpDtD,gBAAgB,CAAC/B,MAAM,CAACC,QAAQ,CAACoF,QAAQ,EAAE;AAC/C"} \ No newline at end of file +{"version":3,"file":"index.js","names":["replicateRxStorageInstance","input","checkpointKey","getCheckpointKey","state","primaryPath","getPrimaryFieldOfPrimaryKey","forkInstance","schema","primaryKey","downstreamBulkWriteFlag","events","canceled","BehaviorSubject","active","down","up","processed","Subject","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","streamQueue","PROMISE_RESOLVE_VOID","checkpointQueue","lastCheckpointDoc","startReplicationDownstream","startReplicationUpstream","awaitRxStorageReplicationFirstInSync","firstValueFrom","combineLatest","pipe","filter","v","then","awaitRxStorageReplicationInSync","replicationState","Promise","all","awaitRxStorageReplicationIdle","rxStorageInstanceToReplicationHandler","instance","conflictHandler","databaseInstanceToken","replicationHandler","masterChangeStream$","changeStream","map","eventBulk","ret","checkpoint","documents","event","writeDocToDocState","ensureNotFalsy","documentData","masterChangesSince","batchSize","getChangedDocumentsSince","result","length","d","masterWrite","rows","rowById","forEach","row","docId","newDocumentState","ids","Object","keys","findDocumentsById","masterDocsState","conflicts","writeRows","entries","id","masterState","push","document","docStateToWriteDoc","assumedMasterState","realMasterState","isEqual","previous","bulkWrite","values","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n map,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n RxConflictHandler,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types';\nimport {\n ensureNotFalsy,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils';\nimport {\n getCheckpointKey\n} from './checkpoint';\nimport { startReplicationDownstream } from './downstream';\nimport { docStateToWriteDoc, writeDocToDocState } from './helper';\nimport { startReplicationUpstream } from './upstream';\n\n\nexport * from './checkpoint';\nexport * from './downstream';\nexport * from './upstream';\nexport * from './meta-instance';\nexport * from './conflicts';\nexport * from './helper';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n const checkpointKey = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n input,\n checkpointKey,\n downstreamBulkWriteFlag: 'replication-downstream-' + checkpointKey,\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reasigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n databaseInstanceToken: string\n): RxReplicationHandler {\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n map(eventBulk => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: eventBulk.events.map(event => {\n return writeDocToDocState(ensureNotFalsy(event.documentData) as any);\n })\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return instance.getChangedDocumentsSince(\n batchSize,\n checkpoint\n ).then(result => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: result.documents.map(d => writeDocToDocState(d))\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsState = await instance.findDocumentsById(\n ids,\n true\n );\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState[id];\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(databaseInstanceToken, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(databaseInstanceToken, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState));\n }\n })\n );\n\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n Object\n .values(result.error)\n .forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb))\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAOA;AAQA;AAeA;AAIA;AAQA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AALA;AAMA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AALA;AASA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AARA;AAKA;EAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA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;MAAA;MAAA;IAAA;EAExB,CAAC;EAED,OAAO9B,kBAAkB;AAC7B;AAGO,SAASgD,0BAA0B,CACtCxD,gBAAwD,EAC1D;EACEA,gBAAgB,CAACrC,MAAM,CAACC,QAAQ,CAAC6F,IAAI,CAAC,IAAI,CAAC;EAC3CzD,gBAAgB,CAACrC,MAAM,CAACG,MAAM,CAACE,EAAE,CAAC0F,QAAQ,EAAE;EAC5C1D,gBAAgB,CAACrC,MAAM,CAACG,MAAM,CAACC,IAAI,CAAC2F,QAAQ,EAAE;EAC9C1D,gBAAgB,CAACrC,MAAM,CAACM,SAAS,CAACD,EAAE,CAAC0F,QAAQ,EAAE;EAC/C1D,gBAAgB,CAACrC,MAAM,CAACM,SAAS,CAACF,IAAI,CAAC2F,QAAQ,EAAE;EACjD1D,gBAAgB,CAACrC,MAAM,CAACQ,iBAAiB,CAACuF,QAAQ,EAAE;EACpD1D,gBAAgB,CAACrC,MAAM,CAACC,QAAQ,CAAC8F,QAAQ,EAAE;AAC/C"} \ No newline at end of file diff --git a/dist/lib/replication-protocol/meta-instance.js b/dist/lib/replication-protocol/meta-instance.js index ab6a4653436..f10080c62af 100644 --- a/dist/lib/replication-protocol/meta-instance.js +++ b/dist/lib/replication-protocol/meta-instance.js @@ -8,7 +8,7 @@ exports.getAssumedMasterState = getAssumedMasterState; exports.getMetaWriteRow = getMetaWriteRow; var _rxSchemaHelper = require("../rx-schema-helper"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var RX_REPLICATION_META_INSTANCE_SCHEMA = (0, _rxSchemaHelper.fillWithDefaultSettings)({ primaryKey: { key: 'id', @@ -80,16 +80,16 @@ function getMetaWriteRow(state, newMasterDocState, previous, isResolvedConflict) data: newMasterDocState, _attachments: {}, _deleted: false, - _rev: (0, _util.getDefaultRevision)(), + _rev: (0, _utils.getDefaultRevision)(), _meta: { lwt: 0 } }; newMeta.data = newMasterDocState; newMeta.isResolvedConflict = isResolvedConflict; - newMeta._meta.lwt = (0, _util.now)(); + newMeta._meta.lwt = (0, _utils.now)(); newMeta.id = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(RX_REPLICATION_META_INSTANCE_SCHEMA, newMeta); - newMeta._rev = (0, _util.createRevision)(state.input.hashFunction, newMeta, previous); + newMeta._rev = (0, _utils.createRevision)(state.input.identifier, previous); return { previous: previous, document: newMeta diff --git a/dist/lib/replication-protocol/meta-instance.js.map b/dist/lib/replication-protocol/meta-instance.js.map index 4ead494250b..b7c9cfaed89 100644 --- a/dist/lib/replication-protocol/meta-instance.js.map +++ b/dist/lib/replication-protocol/meta-instance.js.map @@ -1 +1 @@ -{"version":3,"file":"meta-instance.js","names":["RX_REPLICATION_META_INSTANCE_SCHEMA","fillWithDefaultSettings","primaryKey","key","fields","separator","type","version","additionalProperties","properties","id","minLength","maxLength","replicationIdentifier","isCheckpoint","itemId","data","isResolvedConflict","required","getAssumedMasterState","state","docIds","input","metaInstance","findDocumentsById","map","docId","useId","getComposedPrimaryKeyOfDocumentData","checkpointKey","then","metaDocs","ret","Object","values","forEach","metaDoc","docData","metaDocument","getMetaWriteRow","newMasterDocState","previous","primaryPath","newMeta","flatCloneDocWithMeta","_attachments","_deleted","_rev","getDefaultRevision","_meta","lwt","now","createRevision","hashFunction","document"],"sources":["../../../src/replication-protocol/meta-instance.ts"],"sourcesContent":["import {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from '../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n ById,\n RxDocumentData,\n RxJsonSchema,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport { getDefaultRevision, createRevision, now } from '../util';\n\nexport const RX_REPLICATION_META_INSTANCE_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n primaryKey: {\n key: 'id',\n fields: [\n 'replicationIdentifier',\n 'itemId',\n 'isCheckpoint'\n ],\n separator: '|'\n },\n type: 'object',\n version: 0,\n additionalProperties: false,\n properties: {\n id: {\n type: 'string',\n minLength: 1,\n maxLength: 100\n },\n replicationIdentifier: {\n type: 'string'\n },\n isCheckpoint: {\n type: 'string',\n enum: [\n '0',\n '1'\n ],\n maxLength: 1\n },\n itemId: {\n type: 'string'\n },\n data: {\n type: 'object',\n additionalProperties: true\n },\n isResolvedConflict: {\n type: 'string'\n }\n },\n required: [\n 'id',\n 'replicationIdentifier',\n 'isCheckpoint',\n 'itemId',\n 'data'\n ]\n});\n\n\n/**\n * Returns the document states of what the fork instance\n * assumes to be the latest state on the master instance.\n */\nexport function getAssumedMasterState(\n state: RxStorageInstanceReplicationState,\n docIds: string[]\n): Promise;\n metaDocument: RxDocumentData;\n }>> {\n return state.input.metaInstance.findDocumentsById(\n docIds.map(docId => {\n const useId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n itemId: docId,\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0'\n }\n );\n return useId;\n }),\n true\n ).then(metaDocs => {\n const ret: {\n [docId: string]: {\n docData: RxDocumentData;\n metaDocument: RxDocumentData;\n };\n } = {};\n Object\n .values(metaDocs)\n .forEach((metaDoc) => {\n ret[metaDoc.itemId] = {\n docData: metaDoc.data,\n metaDocument: metaDoc\n };\n });\n\n return ret;\n });\n}\n\n\nexport function getMetaWriteRow(\n state: RxStorageInstanceReplicationState,\n newMasterDocState: WithDeleted,\n previous?: RxDocumentData,\n isResolvedConflict?: string\n): BulkWriteRow {\n const docId: string = (newMasterDocState as any)[state.primaryPath];\n const newMeta: RxDocumentData = previous ? flatCloneDocWithMeta(\n previous\n ) : {\n id: '',\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0',\n itemId: docId,\n data: newMasterDocState,\n _attachments: {},\n _deleted: false,\n _rev: getDefaultRevision(),\n _meta: {\n lwt: 0\n }\n };\n newMeta.data = newMasterDocState;\n newMeta.isResolvedConflict = isResolvedConflict;\n newMeta._meta.lwt = now();\n newMeta.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newMeta\n );\n newMeta._rev = createRevision(\n state.input.hashFunction,\n newMeta,\n previous\n );\n return {\n previous,\n document: newMeta\n };\n}\n"],"mappings":";;;;;;;;AAAA;AAIA;AAUA;AAEO,IAAMA,mCAA2F,GAAG,IAAAC,uCAAuB,EAAC;EAC/HC,UAAU,EAAE;IACRC,GAAG,EAAE,IAAI;IACTC,MAAM,EAAE,CACJ,uBAAuB,EACvB,QAAQ,EACR,cAAc,CACjB;IACDC,SAAS,EAAE;EACf,CAAC;EACDC,IAAI,EAAE,QAAQ;EACdC,OAAO,EAAE,CAAC;EACVC,oBAAoB,EAAE,KAAK;EAC3BC,UAAU,EAAE;IACRC,EAAE,EAAE;MACAJ,IAAI,EAAE,QAAQ;MACdK,SAAS,EAAE,CAAC;MACZC,SAAS,EAAE;IACf,CAAC;IACDC,qBAAqB,EAAE;MACnBP,IAAI,EAAE;IACV,CAAC;IACDQ,YAAY,EAAE;MACVR,IAAI,EAAE,QAAQ;MACd,QAAM,CACF,GAAG,EACH,GAAG,CACN;MACDM,SAAS,EAAE;IACf,CAAC;IACDG,MAAM,EAAE;MACJT,IAAI,EAAE;IACV,CAAC;IACDU,IAAI,EAAE;MACFV,IAAI,EAAE,QAAQ;MACdE,oBAAoB,EAAE;IAC1B,CAAC;IACDS,kBAAkB,EAAE;MAChBX,IAAI,EAAE;IACV;EACJ,CAAC;EACDY,QAAQ,EAAE,CACN,IAAI,EACJ,uBAAuB,EACvB,cAAc,EACd,QAAQ,EACR,MAAM;AAEd,CAAC,CAAC;;AAGF;AACA;AACA;AACA;AAHA;AAIO,SAASC,qBAAqB,CACjCC,KAAmD,EACnDC,MAAgB,EAIZ;EACJ,OAAOD,KAAK,CAACE,KAAK,CAACC,YAAY,CAACC,iBAAiB,CAC7CH,MAAM,CAACI,GAAG,CAAC,UAAAC,KAAK,EAAI;I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IAAAC,SAAG,GAAE;EACzBR,OAAO,CAACjC,EAAE,GAAG,IAAAkB,mDAAmC,EAC5C5B,mCAAmC,EACnC2C,OAAO,CACV;EACDA,OAAO,CAACI,IAAI,GAAG,IAAAK,oBAAc,EACzBhC,KAAK,CAACE,KAAK,CAAC+B,YAAY,EACxBV,OAAO,EACPF,QAAQ,CACX;EACD,OAAO;IACHA,QAAQ,EAARA,QAAQ;IACRa,QAAQ,EAAEX;EACd,CAAC;AACL"} \ No newline at end of file +{"version":3,"file":"meta-instance.js","names":["RX_REPLICATION_META_INSTANCE_SCHEMA","fillWithDefaultSettings","primaryKey","key","fields","separator","type","version","additionalProperties","properties","id","minLength","maxLength","replicationIdentifier","isCheckpoint","itemId","data","isResolvedConflict","required","getAssumedMasterState","state","docIds","input","metaInstance","findDocumentsById","map","docId","useId","getComposedPrimaryKeyOfDocumentData","checkpointKey","then","metaDocs","ret","Object","values","forEach","metaDoc","docData","metaDocument","getMetaWriteRow","newMasterDocState","previous","primaryPath","newMeta","flatCloneDocWithMeta","_attachments","_deleted","_rev","getDefaultRevision","_meta","lwt","now","createRevision","identifier","document"],"sources":["../../../src/replication-protocol/meta-instance.ts"],"sourcesContent":["import {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from '../rx-schema-helper';\nimport { flatCloneDocWithMeta } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n ById,\n RxDocumentData,\n RxJsonSchema,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport { getDefaultRevision, createRevision, now } from '../plugins/utils';\n\nexport const RX_REPLICATION_META_INSTANCE_SCHEMA: RxJsonSchema> = fillWithDefaultSettings({\n primaryKey: {\n key: 'id',\n fields: [\n 'replicationIdentifier',\n 'itemId',\n 'isCheckpoint'\n ],\n separator: '|'\n },\n type: 'object',\n version: 0,\n additionalProperties: false,\n properties: {\n id: {\n type: 'string',\n minLength: 1,\n maxLength: 100\n },\n replicationIdentifier: {\n type: 'string'\n },\n isCheckpoint: {\n type: 'string',\n enum: [\n '0',\n '1'\n ],\n maxLength: 1\n },\n itemId: {\n type: 'string'\n },\n data: {\n type: 'object',\n additionalProperties: true\n },\n isResolvedConflict: {\n type: 'string'\n }\n },\n required: [\n 'id',\n 'replicationIdentifier',\n 'isCheckpoint',\n 'itemId',\n 'data'\n ]\n});\n\n\n/**\n * Returns the document states of what the fork instance\n * assumes to be the latest state on the master instance.\n */\nexport function getAssumedMasterState(\n state: RxStorageInstanceReplicationState,\n docIds: string[]\n): Promise;\n metaDocument: RxDocumentData;\n }>> {\n return state.input.metaInstance.findDocumentsById(\n docIds.map(docId => {\n const useId = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n {\n itemId: docId,\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0'\n }\n );\n return useId;\n }),\n true\n ).then(metaDocs => {\n const ret: {\n [docId: string]: {\n docData: RxDocumentData;\n metaDocument: RxDocumentData;\n };\n } = {};\n Object\n .values(metaDocs)\n .forEach((metaDoc) => {\n ret[metaDoc.itemId] = {\n docData: metaDoc.data,\n metaDocument: metaDoc\n };\n });\n\n return ret;\n });\n}\n\n\nexport function getMetaWriteRow(\n state: RxStorageInstanceReplicationState,\n newMasterDocState: WithDeleted,\n previous?: RxDocumentData,\n isResolvedConflict?: string\n): BulkWriteRow {\n const docId: string = (newMasterDocState as any)[state.primaryPath];\n const newMeta: RxDocumentData = previous ? flatCloneDocWithMeta(\n previous\n ) : {\n id: '',\n replicationIdentifier: state.checkpointKey,\n isCheckpoint: '0',\n itemId: docId,\n data: newMasterDocState,\n _attachments: {},\n _deleted: false,\n _rev: getDefaultRevision(),\n _meta: {\n lwt: 0\n }\n };\n newMeta.data = newMasterDocState;\n newMeta.isResolvedConflict = isResolvedConflict;\n newMeta._meta.lwt = now();\n newMeta.id = getComposedPrimaryKeyOfDocumentData(\n RX_REPLICATION_META_INSTANCE_SCHEMA,\n newMeta\n );\n newMeta._rev = createRevision(\n state.input.identifier,\n previous\n );\n return {\n previous,\n document: newMeta\n };\n}\n"],"mappings":";;;;;;;;AAAA;AAIA;AAUA;AAEO,IAAMA,mCAA2F,GAAG,IAAAC,uCAAuB,EAAC;EAC/HC,UAAU,EAAE;IACRC,GAAG,EAAE,IAAI;IACTC,MAAM,EAAE,CACJ,uBAAuB,EACvB,QAAQ,EACR,cAAc,CACjB;IACDC,SAAS,EAAE;EACf,CAAC;EACDC,IAAI,EAAE,QAAQ;EACdC,OAAO,EAAE,CAAC;EACVC,oBAAoB,EAAE,KAAK;EAC3BC,UAAU,EAAE;IACRC,EAAE,EAAE;MACAJ,IAAI,EAAE,QAAQ;MACdK,SAAS,EAAE,CAAC;MACZC,SAAS,EAAE;IACf,CAAC;IACDC,qBAAqB,EAAE;MACnBP,IAAI,EAAE;IACV,CAAC;IACDQ,YAAY,EAAE;MACVR,IAAI,EAAE,QAAQ;MACd,QAAM,CACF,GAAG,EACH,GAAG,CACN;MACDM,SAAS,EAAE;IACf,CAAC;IACDG,MAAM,EAAE;MACJT,IAAI,EAAE;IACV,CAAC;IACDU,IAAI,EAAE;MACFV,IAAI,EAAE,QAAQ;MACdE,oBAAoB,EAAE;IAC1B,CAAC;IACDS,kBAAkB,EAAE;MAChBX,IAAI,EAAE;IACV;EACJ,CAAC;EACDY,QAAQ,EAAE,CACN,IAAI,EACJ,uBAAuB,EACvB,cAAc,EACd,QAAQ,EACR,MAAM;AAEd,CAAC,CAAC;;AAGF;AACA;AACA;AACA;AAHA;AAIO,SAASC,qBAAqB,CACjCC,KAAmD,EACnDC,MAAgB,EAIZ;EACJ,OAAOD,KAAK,CAACE,KAAK,CAACC,YAAY,CAACC,iBAAiB,CAC7CH,MAAM,CAACI,GAAG,CAAC,UAAAC,KAAK,EAAI;IAChB,IAAMC,KAAK,GAAG,IAAAC,mDAAmC,EAC7C5B,mCAAmC,EACnC;MACIe,MAAM,EAAEW,KAAK;MACbb,qBAAqB,EAAEO,KAAK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O,CAACI,IAAI,GAAG,IAAAK,qBAAc,EACzBhC,KAAK,CAACE,KAAK,CAAC+B,UAAU,EACtBZ,QAAQ,CACX;EACD,OAAO;IACHA,QAAQ,EAARA,QAAQ;IACRa,QAAQ,EAAEX;EACd,CAAC;AACL"} \ No newline at end of file diff --git a/dist/lib/replication-protocol/upstream.js b/dist/lib/replication-protocol/upstream.js index e1cbdbbc1fb..32912659957 100644 --- a/dist/lib/replication-protocol/upstream.js +++ b/dist/lib/replication-protocol/upstream.js @@ -1,165 +1,19 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.startReplicationUpstream = startReplicationUpstream; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _checkpoint = require("./checkpoint"); var _conflicts = require("./conflicts"); var _helper = require("./helper"); var _metaInstance = require("./meta-instance"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} /** * Writes all document changes from the fork to the master. * The upstream runs on two modes: @@ -169,60 +23,6 @@ function _for(test, update, body) { * so we do not have to prepare for missed out events. */ function startReplicationUpstream(state) { - var upstreamInitialSync = function upstreamInitialSync() { - try { - state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1; - if (state.events.canceled.getValue()) { - return Promise.resolve(); - } - state.checkpointQueue = state.checkpointQueue.then(function () { - return (0, _checkpoint.getLastCheckpointDoc)(state, 'up'); - }); - return Promise.resolve(state.checkpointQueue).then(function (lastCheckpoint) { - var _interrupt = false; - function _temp11() { - /** - * If we had conflicts during the initial sync, - * it means that we likely have new writes to the fork - * and so we have to run the initial sync again to upastream these new writes. - */ - return Promise.resolve(Promise.all(promises)).then(function (resolvedPromises) { - var hadConflicts = resolvedPromises.find(function (r) { - return !!r; - }); - var _temp9 = function () { - if (hadConflicts) { - return Promise.resolve(upstreamInitialSync()).then(function () {}); - } else if (!state.firstSyncDone.up.getValue()) { - state.firstSyncDone.up.next(true); - } - }(); - if (_temp9 && _temp9.then) return _temp9.then(function () {}); - }); - } - var promises = []; - var _temp10 = _for(function () { - return !_interrupt && !state.events.canceled.getValue(); - }, void 0, function () { - initialSyncStartTime = timer++; - return Promise.resolve(state.input.forkInstance.getChangedDocumentsSince(state.input.pushBatchSize, lastCheckpoint)).then(function (upResult) { - if (upResult.documents.length === 0) { - _interrupt = true; - return; - } - lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, upResult.checkpoint]); - promises.push(persistToMaster(upResult.documents, (0, _util.ensureNotFalsy)(lastCheckpoint))); - }); - }); - return _temp10 && _temp10.then ? _temp10.then(_temp11) : _temp11(_temp10); - }); - } catch (e) { - return Promise.reject(e); - } - }; - /** - * Takes all open tasks an processes them at once. - */ var replicationHandler = state.input.replicationHandler; state.streamQueue.up = state.streamQueue.up.then(function () { return upstreamInitialSync().then(function () { @@ -255,6 +55,82 @@ function startReplicationUpstream(state) { }))).then(function () { return sub.unsubscribe(); }); + function upstreamInitialSync() { + return _upstreamInitialSync.apply(this, arguments); + } + /** + * Takes all open tasks an processes them at once. + */ + function _upstreamInitialSync() { + _upstreamInitialSync = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var lastCheckpoint, promises, upResult, resolvedPromises, hadConflicts; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1; + if (!state.events.canceled.getValue()) { + _context4.next = 3; + break; + } + return _context4.abrupt("return"); + case 3: + state.checkpointQueue = state.checkpointQueue.then(function () { + return (0, _checkpoint.getLastCheckpointDoc)(state, 'up'); + }); + _context4.next = 6; + return state.checkpointQueue; + case 6: + lastCheckpoint = _context4.sent; + promises = []; + case 8: + if (state.events.canceled.getValue()) { + _context4.next = 19; + break; + } + initialSyncStartTime = timer++; + _context4.next = 12; + return state.input.forkInstance.getChangedDocumentsSince(state.input.pushBatchSize, lastCheckpoint); + case 12: + upResult = _context4.sent; + if (!(upResult.documents.length === 0)) { + _context4.next = 15; + break; + } + return _context4.abrupt("break", 19); + case 15: + lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, upResult.checkpoint]); + promises.push(persistToMaster(upResult.documents, (0, _utils.ensureNotFalsy)(lastCheckpoint))); + _context4.next = 8; + break; + case 19: + _context4.next = 21; + return Promise.all(promises); + case 21: + resolvedPromises = _context4.sent; + hadConflicts = resolvedPromises.find(function (r) { + return !!r; + }); + if (!hadConflicts) { + _context4.next = 28; + break; + } + _context4.next = 26; + return upstreamInitialSync(); + case 26: + _context4.next = 29; + break; + case 28: + if (!state.firstSyncDone.up.getValue()) { + state.firstSyncDone.up.next(true); + } + case 29: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _upstreamInitialSync.apply(this, arguments); + } function processTasks() { if (state.events.canceled.getValue() || openTasks.length === 0) { state.events.active.up.next(false); @@ -269,7 +145,7 @@ function startReplicationUpstream(state) { var docs = []; var checkpoint = {}; while (openTasks.length > 0) { - var taskWithTime = (0, _util.ensureNotFalsy)(openTasks.shift()); + var taskWithTime = (0, _utils.ensureNotFalsy)(openTasks.shift()); /** * If the task came in before the last time the initial sync fetching * has run, we can ignore the task because the initial sync already processed @@ -283,7 +159,7 @@ function startReplicationUpstream(state) { })); checkpoint = (0, _rxStorageHelper.stackCheckpoints)([checkpoint, taskWithTime.task.checkpoint]); } - var promise = docs.length === 0 ? _util.PROMISE_RESOLVE_FALSE : persistToMaster(docs, checkpoint); + var promise = docs.length === 0 ? _utils.PROMISE_RESOLVE_FALSE : persistToMaster(docs, checkpoint); return promise.then(function () { if (openTasks.length === 0) { state.events.active.up.next(false); @@ -293,7 +169,7 @@ function startReplicationUpstream(state) { }); }); } - var persistenceQueue = _util.PROMISE_RESOLVE_FALSE; + var persistenceQueue = _utils.PROMISE_RESOLVE_FALSE; var nonPersistedFromMaster = { docs: {} }; @@ -313,191 +189,242 @@ function startReplicationUpstream(state) { nonPersistedFromMaster.docs[docId] = docData; }); nonPersistedFromMaster.checkpoint = checkpoint; - persistenceQueue = persistenceQueue.then(function () { - try { - if (state.events.canceled.getValue()) { - return Promise.resolve(false); - } - var upDocsById = nonPersistedFromMaster.docs; - nonPersistedFromMaster.docs = {}; - var useCheckpoint = nonPersistedFromMaster.checkpoint; - var docIds = Object.keys(upDocsById); - if (docIds.length === 0) { - return Promise.resolve(false); - } - return Promise.resolve((0, _metaInstance.getAssumedMasterState)(state, docIds)).then(function (assumedMasterState) { - var writeRowsToMaster = {}; - var writeRowsToMasterIds = []; - var writeRowsToMeta = {}; - var forkStateById = {}; - return Promise.resolve(Promise.all(docIds.map(function (docId) { - try { - var _temp8 = function _temp8(_state$input$conflict) { - if (_temp7 && _state$input$conflict.isEqual || - /** - * If the master works with _rev fields, - * we use that to check if our current doc state - * is different from the assumedMasterDoc. - */ - - assumedMasterDoc && assumedMasterDoc.docData._rev && (0, _util.parseRevision)(fullDocData._rev).height === fullDocData._meta[state.input.identifier]) { - _exit = true; - return; - } - writeRowsToMasterIds.push(docId); - writeRowsToMaster[docId] = { - assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined, - newDocumentState: docData - }; - writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, docData, assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined); - }; - var _exit = false; - var fullDocData = upDocsById[docId]; - forkStateById[docId] = fullDocData; - var docData = (0, _helper.writeDocToDocState)(fullDocData); - var assumedMasterDoc = assumedMasterState[docId]; - - /** - * If the master state is equal to the - * fork state, we can assume that the document state is already - * replicated. - */ - var _temp7 = assumedMasterDoc && - // if the isResolvedConflict is correct, we do not have to compare the documents. - assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev; - return Promise.resolve(_temp7 ? Promise.resolve(state.input.conflictHandler({ - realMasterState: assumedMasterDoc.docData, - newDocumentState: docData - }, 'upstream-check-if-equal')).then(_temp8) : _temp8(_temp7)); - } catch (e) { - return Promise.reject(e); + persistenceQueue = persistenceQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var upDocsById, useCheckpoint, docIds, assumedMasterState, writeRowsToMaster, writeRowsToMasterIds, writeRowsToMeta, forkStateById, writeRowsArray, conflictIds, conflictsById, writeBatches, useWriteRowsToMeta, hadConflictWrites, conflictWriteFork, conflictWriteMeta, forkWriteResult, useMetaWrites; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!state.events.canceled.getValue()) { + _context3.next = 2; + break; } - }))).then(function () { - if (writeRowsToMasterIds.length === 0) { - return false; + return _context3.abrupt("return", false); + case 2: + upDocsById = nonPersistedFromMaster.docs; + nonPersistedFromMaster.docs = {}; + useCheckpoint = nonPersistedFromMaster.checkpoint; + docIds = Object.keys(upDocsById); + if (!(docIds.length === 0)) { + _context3.next = 8; + break; } - var writeRowsArray = Object.values(writeRowsToMaster); - var conflictIds = new Set(); - var conflictsById = {}; + return _context3.abrupt("return", false); + case 8: + _context3.next = 10; + return (0, _metaInstance.getAssumedMasterState)(state, docIds); + case 10: + assumedMasterState = _context3.sent; + writeRowsToMaster = {}; + writeRowsToMasterIds = []; + writeRowsToMeta = {}; + forkStateById = {}; + _context3.next = 17; + return Promise.all(docIds.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(docId) { + var fullDocData, docData, assumedMasterDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + fullDocData = upDocsById[docId]; + forkStateById[docId] = fullDocData; + docData = (0, _helper.writeDocToDocState)(fullDocData); + assumedMasterDoc = assumedMasterState[docId]; + /** + * If the master state is equal to the + * fork state, we can assume that the document state is already + * replicated. + */ + _context.t1 = assumedMasterDoc && + // if the isResolvedConflict is correct, we do not have to compare the documents. + assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev; + if (!_context.t1) { + _context.next = 9; + break; + } + _context.next = 8; + return state.input.conflictHandler({ + realMasterState: assumedMasterDoc.docData, + newDocumentState: docData + }, 'upstream-check-if-equal'); + case 8: + _context.t1 = _context.sent.isEqual; + case 9: + _context.t0 = _context.t1; + if (_context.t0) { + _context.next = 12; + break; + } + _context.t0 = + /** + * If the master works with _rev fields, + * we use that to check if our current doc state + * is different from the assumedMasterDoc. + */ + assumedMasterDoc && assumedMasterDoc.docData._rev && (0, _utils.parseRevision)(fullDocData._rev).height === fullDocData._meta[state.input.identifier]; + case 12: + if (!_context.t0) { + _context.next = 14; + break; + } + return _context.abrupt("return"); + case 14: + writeRowsToMasterIds.push(docId); + writeRowsToMaster[docId] = { + assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined, + newDocumentState: docData + }; + writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, docData, assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined); + case 17: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); + case 17: + if (!(writeRowsToMasterIds.length === 0)) { + _context3.next = 19; + break; + } + return _context3.abrupt("return", false); + case 19: + writeRowsArray = Object.values(writeRowsToMaster); + conflictIds = new Set(); + conflictsById = {}; /** * To always respect the push.batchSize, * we have to split the write rows into batches * to ensure that replicationHandler.masterWrite() is never * called with more documents than what the batchSize limits. */ - var writeBatches = (0, _util.batchArray)(writeRowsArray, state.input.pushBatchSize); - return Promise.resolve(Promise.all(writeBatches.map(function (writeBatch) { - try { - return Promise.resolve(replicationHandler.masterWrite(writeBatch)).then(function (masterWriteResult) { - masterWriteResult.forEach(function (conflictDoc) { - var id = conflictDoc[state.primaryPath]; - conflictIds.add(id); - conflictsById[id] = conflictDoc; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - function _temp6() { - function _temp4() { - /** - * For better performance we do not await checkpoint writes, - * but to ensure order on parallel checkpoint writes, - * we have to use a queue. - */ - state.checkpointQueue = state.checkpointQueue.then(function () { - return (0, _checkpoint.setCheckpoint)(state, 'up', useCheckpoint); - }); - return hadConflictWrites; - } - /** - * Resolve conflicts by writing a new document - * state to the fork instance and the 'real' master state - * to the meta instance. - * Non-409 errors will be detected by resolveConflictError() - */ - var hadConflictWrites = false; - var _temp3 = function () { - if (conflictIds.size > 0) { - state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1; - var conflictWriteFork = []; - var conflictWriteMeta = {}; - return Promise.resolve(Promise.all(Object.entries(conflictsById).map(function (_ref) { - var docId = _ref[0], - realMasterState = _ref[1]; - var writeToMasterRow = writeRowsToMaster[docId]; - var input = { - newDocumentState: writeToMasterRow.newDocumentState, - assumedMasterState: writeToMasterRow.assumedMasterState, - realMasterState: realMasterState - }; - return (0, _conflicts.resolveConflictError)(state, input, forkStateById[docId]).then(function (resolved) { - if (resolved) { - state.events.resolvedConflicts.next({ - input: input, - output: resolved.output - }); - conflictWriteFork.push({ - previous: forkStateById[docId], - document: resolved.resolvedDoc - }); - var assumedMasterDoc = assumedMasterState[docId]; - conflictWriteMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, (0, _util.ensureNotFalsy)(realMasterState), assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined, resolved.resolvedDoc._rev); - } + writeBatches = (0, _utils.batchArray)(writeRowsArray, state.input.pushBatchSize); + _context3.next = 25; + return Promise.all(writeBatches.map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(writeBatch) { + var masterWriteResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return replicationHandler.masterWrite(writeBatch); + case 2: + masterWriteResult = _context2.sent; + masterWriteResult.forEach(function (conflictDoc) { + var id = conflictDoc[state.primaryPath]; + conflictIds.add(id); + conflictsById[id] = conflictDoc; }); - }))).then(function () { - var _temp2 = function () { - if (conflictWriteFork.length > 0) { - hadConflictWrites = true; - state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1; - return Promise.resolve(state.input.forkInstance.bulkWrite(conflictWriteFork, 'replication-up-write-conflict')).then(function (forkWriteResult) { - /** - * Errors in the forkWriteResult must not be handled - * because they have been caused by a write to the forkInstance - * in between which will anyway trigger a new upstream cycle - * that will then resolved the conflict again. - */ - var useMetaWrites = []; - Object.keys(forkWriteResult.success).forEach(function (docId) { - useMetaWrites.push(conflictWriteMeta[docId]); - }); - var _temp = function () { - if (useMetaWrites.length > 0) { - return Promise.resolve(state.input.metaInstance.bulkWrite(useMetaWrites, 'replication-up-write-conflict-meta')).then(function () {}); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); // TODO what to do with conflicts while writing to the metaInstance? - } - }(); - if (_temp2 && _temp2.then) return _temp2.then(function () {}); - }); + case 4: + case "end": + return _context2.stop(); } - }(); - return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3); + }, _callee2); + })); + return function (_x2) { + return _ref3.apply(this, arguments); + }; + }())); + case 25: + useWriteRowsToMeta = []; + writeRowsToMasterIds.forEach(function (docId) { + if (!conflictIds.has(docId)) { + state.events.processed.up.next(writeRowsToMaster[docId]); + useWriteRowsToMeta.push(writeRowsToMeta[docId]); } - var useWriteRowsToMeta = []; - writeRowsToMasterIds.forEach(function (docId) { - if (!conflictIds.has(docId)) { - state.events.processed.up.next(writeRowsToMaster[docId]); - useWriteRowsToMeta.push(writeRowsToMeta[docId]); + }); + if (!(useWriteRowsToMeta.length > 0)) { + _context3.next = 30; + break; + } + _context3.next = 30; + return state.input.metaInstance.bulkWrite(useWriteRowsToMeta, 'replication-up-write-meta'); + case 30: + /** + * Resolve conflicts by writing a new document + * state to the fork instance and the 'real' master state + * to the meta instance. + * Non-409 errors will be detected by resolveConflictError() + */ + hadConflictWrites = false; + if (!(conflictIds.size > 0)) { + _context3.next = 48; + break; + } + state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1; + conflictWriteFork = []; + conflictWriteMeta = {}; + _context3.next = 37; + return Promise.all(Object.entries(conflictsById).map(function (_ref4) { + var docId = _ref4[0], + realMasterState = _ref4[1]; + var writeToMasterRow = writeRowsToMaster[docId]; + var input = { + newDocumentState: writeToMasterRow.newDocumentState, + assumedMasterState: writeToMasterRow.assumedMasterState, + realMasterState: realMasterState + }; + return (0, _conflicts.resolveConflictError)(state, input, forkStateById[docId]).then(function (resolved) { + if (resolved) { + state.events.resolvedConflicts.next({ + input: input, + output: resolved.output + }); + conflictWriteFork.push({ + previous: forkStateById[docId], + document: resolved.resolvedDoc + }); + var assumedMasterDoc = assumedMasterState[docId]; + conflictWriteMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, (0, _utils.ensureNotFalsy)(realMasterState), assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined, resolved.resolvedDoc._rev); } }); - var _temp5 = function () { - if (useWriteRowsToMeta.length > 0) { - return Promise.resolve(state.input.metaInstance.bulkWrite(useWriteRowsToMeta, 'replication-up-write-meta')).then(function () {}); // TODO what happens when we have conflicts here? - } - }(); - return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5); + })); + case 37: + if (!(conflictWriteFork.length > 0)) { + _context3.next = 48; + break; + } + hadConflictWrites = true; + state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1; + _context3.next = 42; + return state.input.forkInstance.bulkWrite(conflictWriteFork, 'replication-up-write-conflict'); + case 42: + forkWriteResult = _context3.sent; + /** + * Errors in the forkWriteResult must not be handled + * because they have been caused by a write to the forkInstance + * in between which will anyway trigger a new upstream cycle + * that will then resolved the conflict again. + */ + useMetaWrites = []; + Object.keys(forkWriteResult.success).forEach(function (docId) { + useMetaWrites.push(conflictWriteMeta[docId]); }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })["catch"](function (unhandledError) { + if (!(useMetaWrites.length > 0)) { + _context3.next = 48; + break; + } + _context3.next = 48; + return state.input.metaInstance.bulkWrite(useMetaWrites, 'replication-up-write-conflict-meta'); + case 48: + /** + * For better performance we do not await checkpoint writes, + * but to ensure order on parallel checkpoint writes, + * we have to use a queue. + */ + state.checkpointQueue = state.checkpointQueue.then(function () { + return (0, _checkpoint.setCheckpoint)(state, 'up', useCheckpoint); + }); + return _context3.abrupt("return", hadConflictWrites); + case 50: + case "end": + return _context3.stop(); + } + }, _callee3); + })))["catch"](function (unhandledError) { state.events.error.next(unhandledError); return false; }); diff --git a/dist/lib/replication-protocol/upstream.js.map b/dist/lib/replication-protocol/upstream.js.map index 15e6b684a14..45ffa284dec 100644 --- a/dist/lib/replication-protocol/upstream.js.map +++ b/dist/lib/replication-protocol/upstream.js.map @@ -1 +1 @@ -{"version":3,"file":"upstream.js","names":["pact","state","value","s","v","o","bind","then","observer","prototype","onFulfilled","onRejected","result","callback","e","_this","thenable","test","update","body","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","startReplicationUpstream","upstreamInitialSync","stats","up","events","canceled","getValue","checkpointQueue","getLastCheckpointDoc","lastCheckpoint","Promise","all","promises","resolvedPromises","hadConflicts","find","r","firstSyncDone","next","initialSyncStartTime","timer","input","forkInstance","getChangedDocumentsSince","pushBatchSize","upResult","documents","length","stackCheckpoints","checkpoint","push","persistToMaster","ensureNotFalsy","replicationHandler","streamQueue","processTasks","openTasks","sub","changeStream","pipe","filter","eventBulk","context","downstreamBulkWriteFlag","subscribe","forkChangeStreamEmit","task","time","waitBeforePersist","firstValueFrom","unsubscribe","active","docs","taskWithTime","shift","concat","map","documentData","promise","PROMISE_RESOLVE_FALSE","persistenceQueue","nonPersistedFromMaster","forEach","docData","docId","primaryPath","upDocsById","useCheckpoint","docIds","Object","keys","getAssumedMasterState","assumedMasterState","writeRowsToMaster","writeRowsToMasterIds","writeRowsToMeta","forkStateById","isEqual","assumedMasterDoc","_rev","parseRevision","fullDocData","height","_meta","identifier","undefined","newDocumentState","getMetaWriteRow","metaDocument","writeDocToDocState","isResolvedConflict","conflictHandler","realMasterState","writeRowsArray","values","conflictIds","Set","conflictsById","writeBatches","batchArray","writeBatch","masterWrite","masterWriteResult","conflictDoc","id","add","setCheckpoint","hadConflictWrites","size","persistToMasterHadConflicts","conflictWriteFork","conflictWriteMeta","entries","writeToMasterRow","resolveConflictError","resolved","resolvedConflicts","output","previous","document","resolvedDoc","persistToMasterConflictWrites","bulkWrite","forkWriteResult","useMetaWrites","success","metaInstance","useWriteRowsToMeta","has","processed","unhandledError","error"],"sources":["../../../src/replication-protocol/upstream.ts"],"sourcesContent":["import { firstValueFrom, filter } from 'rxjs';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowById,\n ById,\n EventBulk,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n RxStorageChangeEvent,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport {\n batchArray,\n ensureNotFalsy,\n parseRevision,\n PROMISE_RESOLVE_FALSE\n} from '../util';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { resolveConflictError } from './conflicts';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all document changes from the fork to the master.\n * The upstream runs on two modes:\n * - For initial replication, a checkpoint-iteration is used\n * - For ongoing local writes, we just subscribe to the changeStream of the fork.\n * In contrast to the master, the fork can be assumed to never loose connection,\n * so we do not have to prepare for missed out events.\n */\nexport function startReplicationUpstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n state.streamQueue.up = state.streamQueue.up.then(() => {\n return upstreamInitialSync().then(() => {\n processTasks();\n });\n });\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n let initialSyncStartTime = -1;\n\n type Task = EventBulk, any>;\n type TaskWithTime = {\n task: Task;\n time: number;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n const sub = state.input.forkInstance.changeStream()\n .pipe(\n filter(eventBulk => eventBulk.context !== state.downstreamBulkWriteFlag)\n ).subscribe(eventBulk => {\n state.stats.up.forkChangeStreamEmit = state.stats.up.forkChangeStreamEmit + 1;\n openTasks.push({\n task: eventBulk,\n time: timer++\n });\n if (state.input.waitBeforePersist) {\n return state.input.waitBeforePersist()\n .then(() => processTasks());\n } else {\n return processTasks();\n }\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n async function upstreamInitialSync() {\n state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'up'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n initialSyncStartTime = timer++;\n const upResult = await state.input.forkInstance.getChangedDocumentsSince(\n state.input.pushBatchSize,\n lastCheckpoint\n );\n if (upResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, upResult.checkpoint]);\n\n promises.push(\n persistToMaster(\n upResult.documents,\n ensureNotFalsy(lastCheckpoint)\n )\n );\n }\n\n /**\n * If we had conflicts during the initial sync,\n * it means that we likely have new writes to the fork\n * and so we have to run the initial sync again to upastream these new writes.\n */\n const resolvedPromises = await Promise.all(promises);\n const hadConflicts = resolvedPromises.find(r => !!r);\n if (hadConflicts) {\n await upstreamInitialSync();\n } else if (!state.firstSyncDone.up.getValue()) {\n state.firstSyncDone.up.next(true);\n }\n }\n\n\n /**\n * Takes all open tasks an processes them at once.\n */\n function processTasks() {\n if (\n state.events.canceled.getValue() ||\n openTasks.length === 0\n ) {\n state.events.active.up.next(false);\n return;\n }\n state.stats.up.processTasks = state.stats.up.processTasks + 1;\n state.events.active.up.next(true);\n state.streamQueue.up = state.streamQueue.up.then(() => {\n /**\n * Merge/filter all open tasks\n */\n let docs: RxDocumentData[] = [];\n let checkpoint: CheckpointType = {} as any;\n while (openTasks.length > 0) {\n const taskWithTime = ensureNotFalsy(openTasks.shift());\n /**\n * If the task came in before the last time the initial sync fetching\n * has run, we can ignore the task because the initial sync already processed\n * these documents.\n */\n if (taskWithTime.time < initialSyncStartTime) {\n continue;\n }\n\n docs = docs.concat(\n taskWithTime.task.events.map(r => {\n return r.documentData as any;\n })\n );\n checkpoint = stackCheckpoints([checkpoint, taskWithTime.task.checkpoint]);\n }\n\n const promise = docs.length === 0 ? PROMISE_RESOLVE_FALSE : persistToMaster(\n docs,\n checkpoint\n );\n return promise.then(() => {\n if (openTasks.length === 0) {\n state.events.active.up.next(false);\n } else {\n processTasks();\n }\n });\n });\n }\n\n let persistenceQueue: Promise = PROMISE_RESOLVE_FALSE;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n /**\n * Returns true if had conflicts,\n * false if not.\n */\n function persistToMaster(\n docs: RxDocumentData[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.up.persistToMaster = state.stats.up.persistToMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n\n persistenceQueue = persistenceQueue.then(async () => {\n if (state.events.canceled.getValue()) {\n return false;\n }\n\n const upDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(upDocsById);\n if (docIds.length === 0) {\n return false;\n }\n\n const assumedMasterState = await getAssumedMasterState(\n state,\n docIds\n );\n\n const writeRowsToMaster: ById> = {};\n const writeRowsToMasterIds: string[] = [];\n const writeRowsToMeta: BulkWriteRowById = {};\n const forkStateById: ById> = {};\n\n await Promise.all(\n docIds.map(async (docId) => {\n const fullDocData: RxDocumentData = upDocsById[docId];\n forkStateById[docId] = fullDocData;\n const docData: WithDeleted = writeDocToDocState(fullDocData);\n const assumedMasterDoc = assumedMasterState[docId];\n\n /**\n * If the master state is equal to the\n * fork state, we can assume that the document state is already\n * replicated.\n */\n if (\n (\n assumedMasterDoc &&\n // if the isResolvedConflict is correct, we do not have to compare the documents.\n assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev\n &&\n (await state.input.conflictHandler({\n realMasterState: assumedMasterDoc.docData,\n newDocumentState: docData\n }, 'upstream-check-if-equal')).isEqual\n )\n ||\n /**\n * If the master works with _rev fields,\n * we use that to check if our current doc state\n * is different from the assumedMasterDoc.\n */\n (\n assumedMasterDoc &&\n (assumedMasterDoc.docData as any)._rev &&\n parseRevision(fullDocData._rev).height === fullDocData._meta[state.input.identifier]\n )\n ) {\n return;\n }\n\n writeRowsToMasterIds.push(docId);\n\n writeRowsToMaster[docId] = {\n assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined,\n newDocumentState: docData\n };\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n docData,\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined\n );\n })\n );\n\n if (writeRowsToMasterIds.length === 0) {\n return false;\n }\n\n\n const writeRowsArray = Object.values(writeRowsToMaster);\n const conflictIds: Set = new Set();\n const conflictsById: ById> = {};\n\n /**\n * To always respect the push.batchSize,\n * we have to split the write rows into batches\n * to ensure that replicationHandler.masterWrite() is never\n * called with more documents than what the batchSize limits.\n */\n const writeBatches = batchArray(writeRowsArray, state.input.pushBatchSize);\n await Promise.all(\n writeBatches.map(async (writeBatch) => {\n const masterWriteResult = await replicationHandler.masterWrite(writeBatch);\n masterWriteResult.forEach(conflictDoc => {\n const id = (conflictDoc as any)[state.primaryPath];\n conflictIds.add(id);\n conflictsById[id] = conflictDoc;\n });\n })\n );\n\n\n const useWriteRowsToMeta: BulkWriteRow[] = [];\n\n\n writeRowsToMasterIds.forEach(docId => {\n if (!conflictIds.has(docId)) {\n state.events.processed.up.next(writeRowsToMaster[docId]);\n useWriteRowsToMeta.push(writeRowsToMeta[docId]);\n }\n });\n\n if (useWriteRowsToMeta.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useWriteRowsToMeta,\n 'replication-up-write-meta'\n );\n // TODO what happens when we have conflicts here?\n }\n\n /**\n * Resolve conflicts by writing a new document\n * state to the fork instance and the 'real' master state\n * to the meta instance.\n * Non-409 errors will be detected by resolveConflictError()\n */\n let hadConflictWrites = false;\n if (conflictIds.size > 0) {\n state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1;\n const conflictWriteFork: BulkWriteRow[] = [];\n const conflictWriteMeta: BulkWriteRowById = {};\n await Promise.all(\n Object\n .entries(conflictsById)\n .map(([docId, realMasterState]) => {\n const writeToMasterRow = writeRowsToMaster[docId];\n const input = {\n newDocumentState: writeToMasterRow.newDocumentState,\n assumedMasterState: writeToMasterRow.assumedMasterState,\n realMasterState\n };\n return resolveConflictError(\n state,\n input,\n forkStateById[docId]\n ).then(resolved => {\n if (resolved) {\n state.events.resolvedConflicts.next({\n input,\n output: resolved.output\n });\n conflictWriteFork.push({\n previous: forkStateById[docId],\n document: resolved.resolvedDoc\n });\n const assumedMasterDoc = assumedMasterState[docId];\n conflictWriteMeta[docId] = getMetaWriteRow(\n state,\n ensureNotFalsy(realMasterState),\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined,\n resolved.resolvedDoc._rev\n );\n }\n });\n })\n );\n\n if (conflictWriteFork.length > 0) {\n hadConflictWrites = true;\n\n state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1;\n const forkWriteResult = await state.input.forkInstance.bulkWrite(\n conflictWriteFork,\n 'replication-up-write-conflict'\n );\n /**\n * Errors in the forkWriteResult must not be handled\n * because they have been caused by a write to the forkInstance\n * in between which will anyway trigger a new upstream cycle\n * that will then resolved the conflict again.\n */\n const useMetaWrites: BulkWriteRow[] = [];\n Object\n .keys(forkWriteResult.success)\n .forEach((docId) => {\n useMetaWrites.push(\n conflictWriteMeta[docId]\n );\n });\n if (useMetaWrites.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useMetaWrites,\n 'replication-up-write-conflict-meta'\n );\n }\n // TODO what to do with conflicts while writing to the metaInstance?\n }\n }\n\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'up',\n useCheckpoint\n ));\n\n return hadConflictWrites;\n }).catch(unhandledError => {\n state.events.error.next(unhandledError);\n return false;\n });\n\n return persistenceQueue;\n }\n}\n\n"],"mappings":";;;;;;AAAA;AACA;AAaA;AAMA;AAIA;AACA;AACA;AAaO,iBAAiBA,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE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js","names":["startReplicationUpstream","state","replicationHandler","input","streamQueue","up","then","upstreamInitialSync","processTasks","timer","initialSyncStartTime","openTasks","sub","forkInstance","changeStream","pipe","filter","eventBulk","context","downstreamBulkWriteFlag","subscribe","stats","forkChangeStreamEmit","push","task","time","waitBeforePersist","firstValueFrom","events","canceled","unsubscribe","getValue","checkpointQueue","getLastCheckpointDoc","lastCheckpoint","promises","getChangedDocumentsSince","pushBatchSize","upResult","documents","length","stackCheckpoints","checkpoint","persistToMaster","ensureNotFalsy","Promise","all","resolvedPromises","hadConflicts","find","r","firstSyncDone","next","active","docs","taskWithTime","shift","concat","map","documentData","promise","PROMISE_RESOLVE_FALSE","persistenceQueue","nonPersistedFromMaster","forEach","docData","docId","primaryPath","upDocsById","useCheckpoint","docIds","Object","keys","getAssumedMasterState","assumedMasterState","writeRowsToMaster","writeRowsToMasterIds","writeRowsToMeta","forkStateById","fullDocData","writeDocToDocState","assumedMasterDoc","metaDocument","isResolvedConflict","_rev","conflictHandler","realMasterState","newDocumentState","isEqual","parseRevision","height","_meta","identifier","undefined","getMetaWriteRow","writeRowsArray","values","conflictIds","Set","conflictsById","writeBatches","batchArray","writeBatch","masterWrite","masterWriteResult","conflictDoc","id","add","useWriteRowsToMeta","has","processed","metaInstance","bulkWrite","hadConflictWrites","size","persistToMasterHadConflicts","conflictWriteFork","conflictWriteMeta","entries","writeToMasterRow","resolveConflictError","resolved","resolvedConflicts","output","previous","document","resolvedDoc","persistToMasterConflictWrites","forkWriteResult","useMetaWrites","success","setCheckpoint","unhandledError","error"],"sources":["../../../src/replication-protocol/upstream.ts"],"sourcesContent":["import { firstValueFrom, filter } from 'rxjs';\nimport { stackCheckpoints } from '../rx-storage-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowById,\n ById,\n EventBulk,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n RxStorageChangeEvent,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n WithDeleted\n} from '../types';\nimport {\n batchArray,\n ensureNotFalsy,\n parseRevision,\n PROMISE_RESOLVE_FALSE\n} from '../plugins/utils';\nimport {\n getLastCheckpointDoc,\n setCheckpoint\n} from './checkpoint';\nimport { resolveConflictError } from './conflicts';\nimport { writeDocToDocState } from './helper';\nimport {\n getAssumedMasterState,\n getMetaWriteRow\n} from './meta-instance';\n\n/**\n * Writes all document changes from the fork to the master.\n * The upstream runs on two modes:\n * - For initial replication, a checkpoint-iteration is used\n * - For ongoing local writes, we just subscribe to the changeStream of the fork.\n * In contrast to the master, the fork can be assumed to never loose connection,\n * so we do not have to prepare for missed out events.\n */\nexport function startReplicationUpstream(\n state: RxStorageInstanceReplicationState\n) {\n const replicationHandler = state.input.replicationHandler;\n state.streamQueue.up = state.streamQueue.up.then(() => {\n return upstreamInitialSync().then(() => {\n processTasks();\n });\n });\n\n // used to detect which tasks etc can in it at which order.\n let timer = 0;\n let initialSyncStartTime = -1;\n\n type Task = EventBulk, any>;\n type TaskWithTime = {\n task: Task;\n time: number;\n };\n const openTasks: TaskWithTime[] = [];\n\n\n const sub = state.input.forkInstance.changeStream()\n .pipe(\n filter(eventBulk => eventBulk.context !== state.downstreamBulkWriteFlag)\n ).subscribe(eventBulk => {\n state.stats.up.forkChangeStreamEmit = state.stats.up.forkChangeStreamEmit + 1;\n openTasks.push({\n task: eventBulk,\n time: timer++\n });\n if (state.input.waitBeforePersist) {\n return state.input.waitBeforePersist()\n .then(() => processTasks());\n } else {\n return processTasks();\n }\n });\n firstValueFrom(\n state.events.canceled.pipe(\n filter(canceled => !!canceled)\n )\n ).then(() => sub.unsubscribe());\n\n\n async function upstreamInitialSync() {\n state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1;\n if (state.events.canceled.getValue()) {\n return;\n }\n\n state.checkpointQueue = state.checkpointQueue.then(() => getLastCheckpointDoc(state, 'up'));\n let lastCheckpoint: CheckpointType = await state.checkpointQueue;\n\n const promises: Promise[] = [];\n while (!state.events.canceled.getValue()) {\n initialSyncStartTime = timer++;\n const upResult = await state.input.forkInstance.getChangedDocumentsSince(\n state.input.pushBatchSize,\n lastCheckpoint\n );\n if (upResult.documents.length === 0) {\n break;\n }\n\n lastCheckpoint = stackCheckpoints([lastCheckpoint, upResult.checkpoint]);\n\n promises.push(\n persistToMaster(\n upResult.documents,\n ensureNotFalsy(lastCheckpoint)\n )\n );\n }\n\n /**\n * If we had conflicts during the initial sync,\n * it means that we likely have new writes to the fork\n * and so we have to run the initial sync again to upstream these new writes.\n */\n const resolvedPromises = await Promise.all(promises);\n const hadConflicts = resolvedPromises.find(r => !!r);\n if (hadConflicts) {\n await upstreamInitialSync();\n } else if (!state.firstSyncDone.up.getValue()) {\n state.firstSyncDone.up.next(true);\n }\n }\n\n\n /**\n * Takes all open tasks an processes them at once.\n */\n function processTasks() {\n if (\n state.events.canceled.getValue() ||\n openTasks.length === 0\n ) {\n state.events.active.up.next(false);\n return;\n }\n state.stats.up.processTasks = state.stats.up.processTasks + 1;\n state.events.active.up.next(true);\n state.streamQueue.up = state.streamQueue.up.then(() => {\n /**\n * Merge/filter all open tasks\n */\n let docs: RxDocumentData[] = [];\n let checkpoint: CheckpointType = {} as any;\n while (openTasks.length > 0) {\n const taskWithTime = ensureNotFalsy(openTasks.shift());\n /**\n * If the task came in before the last time the initial sync fetching\n * has run, we can ignore the task because the initial sync already processed\n * these documents.\n */\n if (taskWithTime.time < initialSyncStartTime) {\n continue;\n }\n\n docs = docs.concat(\n taskWithTime.task.events.map(r => {\n return r.documentData as any;\n })\n );\n checkpoint = stackCheckpoints([checkpoint, taskWithTime.task.checkpoint]);\n }\n\n const promise = docs.length === 0 ? PROMISE_RESOLVE_FALSE : persistToMaster(\n docs,\n checkpoint\n );\n return promise.then(() => {\n if (openTasks.length === 0) {\n state.events.active.up.next(false);\n } else {\n processTasks();\n }\n });\n });\n }\n\n let persistenceQueue: Promise = PROMISE_RESOLVE_FALSE;\n const nonPersistedFromMaster: {\n checkpoint?: CheckpointType;\n docs: ById>;\n } = {\n docs: {}\n };\n\n /**\n * Returns true if had conflicts,\n * false if not.\n */\n function persistToMaster(\n docs: RxDocumentData[],\n checkpoint: CheckpointType\n ): Promise {\n state.stats.up.persistToMaster = state.stats.up.persistToMaster + 1;\n\n /**\n * Add the new docs to the non-persistend list\n */\n docs.forEach(docData => {\n const docId: string = (docData as any)[state.primaryPath];\n nonPersistedFromMaster.docs[docId] = docData;\n });\n nonPersistedFromMaster.checkpoint = checkpoint;\n\n\n persistenceQueue = persistenceQueue.then(async () => {\n if (state.events.canceled.getValue()) {\n return false;\n }\n\n const upDocsById: ById> = nonPersistedFromMaster.docs;\n nonPersistedFromMaster.docs = {};\n const useCheckpoint = nonPersistedFromMaster.checkpoint;\n const docIds = Object.keys(upDocsById);\n if (docIds.length === 0) {\n return false;\n }\n\n const assumedMasterState = await getAssumedMasterState(\n state,\n docIds\n );\n\n const writeRowsToMaster: ById> = {};\n const writeRowsToMasterIds: string[] = [];\n const writeRowsToMeta: BulkWriteRowById = {};\n const forkStateById: ById> = {};\n\n await Promise.all(\n docIds.map(async (docId) => {\n const fullDocData: RxDocumentData = upDocsById[docId];\n forkStateById[docId] = fullDocData;\n const docData: WithDeleted = writeDocToDocState(fullDocData);\n const assumedMasterDoc = assumedMasterState[docId];\n\n /**\n * If the master state is equal to the\n * fork state, we can assume that the document state is already\n * replicated.\n */\n if (\n (\n assumedMasterDoc &&\n // if the isResolvedConflict is correct, we do not have to compare the documents.\n assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev\n &&\n (await state.input.conflictHandler({\n realMasterState: assumedMasterDoc.docData,\n newDocumentState: docData\n }, 'upstream-check-if-equal')).isEqual\n )\n ||\n /**\n * If the master works with _rev fields,\n * we use that to check if our current doc state\n * is different from the assumedMasterDoc.\n */\n (\n assumedMasterDoc &&\n (assumedMasterDoc.docData as any)._rev &&\n parseRevision(fullDocData._rev).height === fullDocData._meta[state.input.identifier]\n )\n ) {\n return;\n }\n\n writeRowsToMasterIds.push(docId);\n\n writeRowsToMaster[docId] = {\n assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined,\n newDocumentState: docData\n };\n writeRowsToMeta[docId] = getMetaWriteRow(\n state,\n docData,\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined\n );\n })\n );\n\n if (writeRowsToMasterIds.length === 0) {\n return false;\n }\n\n\n const writeRowsArray = Object.values(writeRowsToMaster);\n const conflictIds: Set = new Set();\n const conflictsById: ById> = {};\n\n /**\n * To always respect the push.batchSize,\n * we have to split the write rows into batches\n * to ensure that replicationHandler.masterWrite() is never\n * called with more documents than what the batchSize limits.\n */\n const writeBatches = batchArray(writeRowsArray, state.input.pushBatchSize);\n await Promise.all(\n writeBatches.map(async (writeBatch) => {\n const masterWriteResult = await replicationHandler.masterWrite(writeBatch);\n masterWriteResult.forEach(conflictDoc => {\n const id = (conflictDoc as any)[state.primaryPath];\n conflictIds.add(id);\n conflictsById[id] = conflictDoc;\n });\n })\n );\n\n\n const useWriteRowsToMeta: BulkWriteRow[] = [];\n\n\n writeRowsToMasterIds.forEach(docId => {\n if (!conflictIds.has(docId)) {\n state.events.processed.up.next(writeRowsToMaster[docId]);\n useWriteRowsToMeta.push(writeRowsToMeta[docId]);\n }\n });\n\n if (useWriteRowsToMeta.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useWriteRowsToMeta,\n 'replication-up-write-meta'\n );\n // TODO what happens when we have conflicts here?\n }\n\n /**\n * Resolve conflicts by writing a new document\n * state to the fork instance and the 'real' master state\n * to the meta instance.\n * Non-409 errors will be detected by resolveConflictError()\n */\n let hadConflictWrites = false;\n if (conflictIds.size > 0) {\n state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1;\n const conflictWriteFork: BulkWriteRow[] = [];\n const conflictWriteMeta: BulkWriteRowById = {};\n await Promise.all(\n Object\n .entries(conflictsById)\n .map(([docId, realMasterState]) => {\n const writeToMasterRow = writeRowsToMaster[docId];\n const input = {\n newDocumentState: writeToMasterRow.newDocumentState,\n assumedMasterState: writeToMasterRow.assumedMasterState,\n realMasterState\n };\n return resolveConflictError(\n state,\n input,\n forkStateById[docId]\n ).then(resolved => {\n if (resolved) {\n state.events.resolvedConflicts.next({\n input,\n output: resolved.output\n });\n conflictWriteFork.push({\n previous: forkStateById[docId],\n document: resolved.resolvedDoc\n });\n const assumedMasterDoc = assumedMasterState[docId];\n conflictWriteMeta[docId] = getMetaWriteRow(\n state,\n ensureNotFalsy(realMasterState),\n assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined,\n resolved.resolvedDoc._rev\n );\n }\n });\n })\n );\n\n if (conflictWriteFork.length > 0) {\n hadConflictWrites = true;\n\n state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1;\n const forkWriteResult = await state.input.forkInstance.bulkWrite(\n conflictWriteFork,\n 'replication-up-write-conflict'\n );\n /**\n * Errors in the forkWriteResult must not be handled\n * because they have been caused by a write to the forkInstance\n * in between which will anyway trigger a new upstream cycle\n * that will then resolved the conflict again.\n */\n const useMetaWrites: BulkWriteRow[] = [];\n Object\n .keys(forkWriteResult.success)\n .forEach((docId) => {\n useMetaWrites.push(\n conflictWriteMeta[docId]\n );\n });\n if (useMetaWrites.length > 0) {\n await state.input.metaInstance.bulkWrite(\n useMetaWrites,\n 'replication-up-write-conflict-meta'\n );\n }\n // TODO what to do with conflicts while writing to the metaInstance?\n }\n }\n\n /**\n * For better performance we do not await checkpoint writes,\n * but to ensure order on parallel checkpoint writes,\n * we have to use a queue.\n */\n state.checkpointQueue = state.checkpointQueue.then(() => setCheckpoint(\n state,\n 'up',\n useCheckpoint\n ));\n\n return hadConflictWrites;\n }).catch(unhandledError => {\n state.events.error.next(unhandledError);\n return false;\n });\n\n return persistenceQueue;\n }\n}\n\n"],"mappings":";;;;;;;;;AAAA;AACA;AAaA;AAMA;AAIA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,wBAAwB,CACpCC,KAAmD,EACrD;EACE,IAA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K,CAAC2B,MAAM,CAACyG,KAAK,CAACjF,IAAI,CAACgF,cAAc,CAAC;MACvC,OAAO,KAAK;IAChB,CAAC,CAAC;IAEF,OAAOtE,gBAAgB;EAC3B;AACJ"} \ No newline at end of file diff --git a/dist/lib/rx-collection-helper.js b/dist/lib/rx-collection-helper.js index 84188297f86..5ff5c36ddc0 100644 --- a/dist/lib/rx-collection-helper.js +++ b/dist/lib/rx-collection-helper.js @@ -1,123 +1,19 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.createRxCollectionStorageInstance = void 0; +exports.createRxCollectionStorageInstance = createRxCollectionStorageInstance; exports.fillObjectDataBeforeInsert = fillObjectDataBeforeInsert; -exports.removeCollectionStorages = void 0; -var _util = require("./util"); +exports.removeCollectionStorages = removeCollectionStorages; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utils = require("./plugins/utils"); var _rxSchemaHelper = require("./rx-schema-helper"); var _hooks = require("./hooks"); var _rxDatabaseInternalStore = require("./rx-database-internal-store"); var _rxStorageHelper = require("./rx-storage-helper"); -/** - * Removes the main storage of the collection - * and all connected storages like the ones from the replication meta etc. - */ -var removeCollectionStorages = function removeCollectionStorages(storage, databaseInternalStorage, databaseInstanceToken, databaseName, collectionName, -/** - * If no hash function is provided, - * we assume that the whole internal store is removed anyway - * so we do not have to delete the meta documents. - */ -hashFunction) { - try { - return Promise.resolve((0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, databaseInternalStorage)).then(function (allCollectionMetaDocs) { - var relevantCollectionMetaDocs = allCollectionMetaDocs.filter(function (metaDoc) { - return metaDoc.data.name === collectionName; - }); - var removeStorages = []; - relevantCollectionMetaDocs.forEach(function (metaDoc) { - removeStorages.push({ - collectionName: metaDoc.data.name, - schema: metaDoc.data.schema, - isCollection: true - }); - metaDoc.data.connectedStorages.forEach(function (row) { - return removeStorages.push({ - collectionName: row.collectionName, - isCollection: false, - schema: row.schema - }); - }); - }); - - // ensure uniqueness - var alreadyAdded = new Set(); - removeStorages = removeStorages.filter(function (row) { - var key = row.collectionName + '||' + row.schema.version; - if (alreadyAdded.has(key)) { - return false; - } else { - alreadyAdded.add(key); - return true; - } - }); - - // remove all the storages - return Promise.resolve(Promise.all(removeStorages.map(function (row) { - try { - return Promise.resolve(storage.createStorageInstance({ - collectionName: row.collectionName, - databaseInstanceToken: databaseInstanceToken, - databaseName: databaseName, - multiInstance: false, - options: {}, - schema: row.schema - })).then(function (storageInstance) { - return Promise.resolve(storageInstance.remove()).then(function () { - var _temp2 = function () { - if (row.isCollection) { - return Promise.resolve((0, _hooks.runAsyncPluginHooks)('postRemoveRxCollection', { - storage: storage, - databaseName: databaseName, - collectionName: collectionName - })).then(function () {}); - } - }(); - if (_temp2 && _temp2.then) return _temp2.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp = function () { - if (hashFunction) { - var writeRows = relevantCollectionMetaDocs.map(function (doc) { - var writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); - writeDoc._deleted = true; - writeDoc._meta.lwt = (0, _util.now)(); - writeDoc._rev = (0, _util.createRevision)(hashFunction, writeDoc, doc); - return { - previous: doc, - document: writeDoc - }; - }); - return Promise.resolve(databaseInternalStorage.bulkWrite(writeRows, 'rx-database-remove-collection-all')).then(function () {}); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); // remove the meta documents - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.removeCollectionStorages = removeCollectionStorages; -/** - * Creates the storage instances that are used internally in the collection - */ -var createRxCollectionStorageInstance = function createRxCollectionStorageInstance(rxDatabase, storageInstanceCreationParams) { - try { - storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance; - return Promise.resolve(rxDatabase.storage.createStorageInstance(storageInstanceCreationParams)); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createRxCollectionStorageInstance = createRxCollectionStorageInstance; /** * fills in the default data. * This also clones the data. @@ -125,7 +21,7 @@ exports.createRxCollectionStorageInstance = createRxCollectionStorageInstance; function fillObjectDataBeforeInsert(schema, data) { var useJson = schema.fillObjectWithDefaults(data); useJson = (0, _rxSchemaHelper.fillPrimaryKey)(schema.primaryPath, schema.jsonSchema, useJson); - useJson._meta = (0, _util.getDefaultRxDocumentMeta)(); + useJson._meta = (0, _utils.getDefaultRxDocumentMeta)(); if (!useJson.hasOwnProperty('_deleted')) { useJson._deleted = false; } @@ -133,8 +29,156 @@ function fillObjectDataBeforeInsert(schema, data) { useJson._attachments = {}; } if (!useJson.hasOwnProperty('_rev')) { - useJson._rev = (0, _util.getDefaultRevision)(); + useJson._rev = (0, _utils.getDefaultRevision)(); } return useJson; } + +/** + * Creates the storage instances that are used internally in the collection + */ +function createRxCollectionStorageInstance(_x, _x2) { + return _createRxCollectionStorageInstance.apply(this, arguments); +} +/** + * Removes the main storage of the collection + * and all connected storages like the ones from the replication meta etc. + */ +function _createRxCollectionStorageInstance() { + _createRxCollectionStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(rxDatabase, storageInstanceCreationParams) { + var storageInstance; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance; + _context.next = 3; + return rxDatabase.storage.createStorageInstance(storageInstanceCreationParams); + case 3: + storageInstance = _context.sent; + return _context.abrupt("return", storageInstance); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _createRxCollectionStorageInstance.apply(this, arguments); +} +function removeCollectionStorages(_x3, _x4, _x5, _x6, _x7, _x8) { + return _removeCollectionStorages.apply(this, arguments); +} +function _removeCollectionStorages() { + _removeCollectionStorages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(storage, databaseInternalStorage, databaseInstanceToken, databaseName, collectionName, + /** + * If no hash function is provided, + * we assume that the whole internal store is removed anyway + * so we do not have to delete the meta documents. + */ + hashFunction) { + var allCollectionMetaDocs, relevantCollectionMetaDocs, removeStorages, alreadyAdded, writeRows; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, databaseInternalStorage); + case 2: + allCollectionMetaDocs = _context3.sent; + relevantCollectionMetaDocs = allCollectionMetaDocs.filter(function (metaDoc) { + return metaDoc.data.name === collectionName; + }); + removeStorages = []; + relevantCollectionMetaDocs.forEach(function (metaDoc) { + removeStorages.push({ + collectionName: metaDoc.data.name, + schema: metaDoc.data.schema, + isCollection: true + }); + metaDoc.data.connectedStorages.forEach(function (row) { + return removeStorages.push({ + collectionName: row.collectionName, + isCollection: false, + schema: row.schema + }); + }); + }); + + // ensure uniqueness + alreadyAdded = new Set(); + removeStorages = removeStorages.filter(function (row) { + var key = row.collectionName + '||' + row.schema.version; + if (alreadyAdded.has(key)) { + return false; + } else { + alreadyAdded.add(key); + return true; + } + }); + + // remove all the storages + _context3.next = 10; + return Promise.all(removeStorages.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(row) { + var storageInstance; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return storage.createStorageInstance({ + collectionName: row.collectionName, + databaseInstanceToken: databaseInstanceToken, + databaseName: databaseName, + multiInstance: false, + options: {}, + schema: row.schema + }); + case 2: + storageInstance = _context2.sent; + _context2.next = 5; + return storageInstance.remove(); + case 5: + if (!row.isCollection) { + _context2.next = 8; + break; + } + _context2.next = 8; + return (0, _hooks.runAsyncPluginHooks)('postRemoveRxCollection', { + storage: storage, + databaseName: databaseName, + collectionName: collectionName + }); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x9) { + return _ref.apply(this, arguments); + }; + }())); + case 10: + if (!hashFunction) { + _context3.next = 14; + break; + } + writeRows = relevantCollectionMetaDocs.map(function (doc) { + var writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); + writeDoc._deleted = true; + writeDoc._meta.lwt = (0, _utils.now)(); + writeDoc._rev = (0, _utils.createRevision)(databaseInstanceToken, doc); + return { + previous: doc, + document: writeDoc + }; + }); + _context3.next = 14; + return databaseInternalStorage.bulkWrite(writeRows, 'rx-database-remove-collection-all'); + case 14: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _removeCollectionStorages.apply(this, arguments); +} //# sourceMappingURL=rx-collection-helper.js.map \ No newline at end of file diff --git a/dist/lib/rx-collection-helper.js.map b/dist/lib/rx-collection-helper.js.map index d1e98e46754..94db28a03d1 100644 --- a/dist/lib/rx-collection-helper.js.map +++ b/dist/lib/rx-collection-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection-helper.js","names":["removeCollectionStorages","storage","databaseInternalStorage","databaseInstanceToken","databaseName","collectionName","hashFunction","getAllCollectionDocuments","statics","allCollectionMetaDocs","relevantCollectionMetaDocs","filter","metaDoc","data","name","removeStorages","forEach","push","schema","isCollection","connectedStorages","row","alreadyAdded","Set","key","version","has","add","Promise","all","map","createStorageInstance","multiInstance","options","storageInstance","remove","runAsyncPluginHooks","writeRows","doc","writeDoc","flatCloneDocWithMeta","_deleted","_meta","lwt","now","_rev","createRevision","previous","document","bulkWrite","createRxCollectionStorageInstance","rxDatabase","storageInstanceCreationParams","fillObjectDataBeforeInsert","useJson","fillObjectWithDefaults","fillPrimaryKey","primaryPath","jsonSchema","getDefaultRxDocumentMeta","hasOwnProperty","_attachments","getDefaultRevision"],"sources":["../../src/rx-collection-helper.ts"],"sourcesContent":["import type {\n HashFunction,\n InternalStoreDocType,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\nimport {\n createRevision,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now\n} from './util';\nimport {\n fillPrimaryKey\n} from './rx-schema-helper';\nimport type { RxSchema } from './rx-schema';\nimport { runAsyncPluginHooks } from './hooks';\nimport { getAllCollectionDocuments } from './rx-database-internal-store';\nimport { flatCloneDocWithMeta } from './rx-storage-helper';\n\n/**\n * fills in the default data.\n * This also clones the data.\n */\nexport function fillObjectDataBeforeInsert(\n schema: RxSchema,\n data: Partial> | any\n): RxDocumentData {\n let useJson = schema.fillObjectWithDefaults(data);\n useJson = fillPrimaryKey(\n schema.primaryPath,\n schema.jsonSchema,\n useJson\n );\n useJson._meta = getDefaultRxDocumentMeta();\n if (!useJson.hasOwnProperty('_deleted')) {\n useJson._deleted = false;\n }\n if (!useJson.hasOwnProperty('_attachments')) {\n useJson._attachments = {};\n }\n if (!useJson.hasOwnProperty('_rev')) {\n useJson._rev = getDefaultRevision();\n }\n return useJson;\n}\n\n/**\n * Creates the storage instances that are used internally in the collection\n */\nexport async function createRxCollectionStorageInstance(\n rxDatabase: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstanceCreationParams: RxStorageInstanceCreationParams\n): Promise> {\n storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance;\n const storageInstance = await rxDatabase.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n return storageInstance;\n}\n\n/**\n * Removes the main storage of the collection\n * and all connected storages like the ones from the replication meta etc.\n */\nexport async function removeCollectionStorages(\n storage: RxStorage,\n databaseInternalStorage: RxStorageInstance, any, any>,\n databaseInstanceToken: string,\n databaseName: string,\n collectionName: string,\n /**\n * If no hash function is provided,\n * we assume that the whole internal store is removed anyway\n * so we do not have to delete the meta documents.\n */\n hashFunction?: HashFunction,\n) {\n const allCollectionMetaDocs = await getAllCollectionDocuments(\n storage.statics,\n databaseInternalStorage\n );\n const relevantCollectionMetaDocs = allCollectionMetaDocs\n .filter(metaDoc => metaDoc.data.name === collectionName);\n\n let removeStorages: {\n collectionName: string;\n schema: RxJsonSchema;\n isCollection: boolean;\n }[] = [];\n relevantCollectionMetaDocs.forEach(metaDoc => {\n removeStorages.push({\n collectionName: metaDoc.data.name,\n schema: metaDoc.data.schema,\n isCollection: true\n });\n metaDoc.data.connectedStorages.forEach(row => removeStorages.push({\n collectionName: row.collectionName,\n isCollection: false,\n schema: row.schema\n }));\n });\n\n // ensure uniqueness\n const alreadyAdded = new Set();\n removeStorages = removeStorages.filter(row => {\n const key = row.collectionName + '||' + row.schema.version;\n if (alreadyAdded.has(key)) {\n return false;\n } else {\n alreadyAdded.add(key);\n return true;\n }\n });\n\n // remove all the storages\n await Promise.all(\n removeStorages\n .map(async (row) => {\n const storageInstance = await storage.createStorageInstance({\n collectionName: row.collectionName,\n databaseInstanceToken,\n databaseName,\n multiInstance: false,\n options: {},\n schema: row.schema\n });\n await storageInstance.remove();\n if (row.isCollection) {\n await runAsyncPluginHooks('postRemoveRxCollection', {\n storage,\n databaseName: databaseName,\n collectionName\n });\n }\n })\n );\n\n // remove the meta documents\n if (hashFunction) {\n const writeRows = relevantCollectionMetaDocs.map(doc => {\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n writeDoc._meta.lwt = now();\n writeDoc._rev = createRevision(\n hashFunction,\n writeDoc,\n doc\n );\n return {\n previous: doc,\n document: writeDoc\n };\n });\n await databaseInternalStorage.bulkWrite(\n writeRows,\n 'rx-database-remove-collection-all'\n );\n }\n}\n"],"mappings":";;;;;;;;AAUA;AAMA;AAIA;AACA;AACA;AA2CA;AACA;AACA;AACA;AAHA,IAIsBA,wBAAwB,YAAxBA,wBAAwB,CAC1CC,OAA4B,EAC5BC,uBAA+E,EAC/EC,qBAA6B,EAC7BC,YAAoB,EACpBC,cAAsB;AACtB;AACJ;AACA;AACA;AACA;AACIC,YAA2B;EAAA,IAC7B;IAAA,uBACsC,IAAAC,kDAAyB,EACzDN,OAAO,CAACO,OAAO,EACfN,uBAAuB,CAC1B,iB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AAC,uBACzCmB,UAAU,CAAClD,OAAO,CAAC8B,qBAAqB,CAClEqB,6BAA6B,CAChC;EAEL,CAAC;IAAA;EAAA;AAAA;AAAA;AAvCD;AACA;AACA;AACA;AACO,SAASC,0BAA0B,CACtCnC,MAA2B,EAC3BL,IAA8C,EACrB;EACzB,IAAIyC,OAAO,GAAGpC,MAAM,CAACqC,sBAAsB,CAAC1C,IAAI,CAAC;EACjDyC,OAAO,GAAG,IAAAE,8BAAc,EACpBtC,MAAM,CAACuC,WAAW,EAClBvC,MAAM,CAACwC,UAAU,EACjBJ,OAAO,CACV;EACDA,OAAO,CAACZ,KAAK,GAAG,IAAAiB,8BAAwB,GAAE;EAC1C,IAAI,CAACL,OAAO,CAACM,cAAc,CAAC,UAAU,CAAC,EAAE;IACrCN,OAAO,CAACb,QAAQ,GAAG,KAAK;EAC5B;EACA,IAAI,CAACa,OAAO,CAACM,cAAc,CAAC,cAAc,CAAC,EAAE;IACzCN,OAAO,CAACO,YAAY,GAAG,CAAC,CAAC;EAC7B;EACA,IAAI,CAACP,OAAO,CAACM,cAAc,CAAC,MAAM,CAAC,EAAE;IACjCN,OAAO,CAACT,IAAI,GAAG,IAAAiB,wBAAkB,GAAE;EACvC;EACA,OAAOR,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"rx-collection-helper.js","names":["fillObjectDataBeforeInsert","schema","data","useJson","fillObjectWithDefaults","fillPrimaryKey","primaryPath","jsonSchema","_meta","getDefaultRxDocumentMeta","hasOwnProperty","_deleted","_attachments","_rev","getDefaultRevision","createRxCollectionStorageInstance","rxDatabase","storageInstanceCreationParams","multiInstance","storage","createStorageInstance","storageInstance","removeCollectionStorages","databaseInternalStorage","databaseInstanceToken","databaseName","collectionName","hashFunction","getAllCollectionDocuments","statics","allCollectionMetaDocs","relevantCollectionMetaDocs","filter","metaDoc","name","removeStorages","forEach","push","isCollection","connectedStorages","row","alreadyAdded","Set","key","version","has","add","Promise","all","map","options","remove","runAsyncPluginHooks","writeRows","doc","writeDoc","flatCloneDocWithMeta","lwt","now","createRevision","previous","document","bulkWrite"],"sources":["../../src/rx-collection-helper.ts"],"sourcesContent":["import type {\n HashFunction,\n InternalStoreDocType,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\nimport {\n createRevision,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now\n} from './plugins/utils';\nimport {\n fillPrimaryKey\n} from './rx-schema-helper';\nimport type { RxSchema } from './rx-schema';\nimport { runAsyncPluginHooks } from './hooks';\nimport { getAllCollectionDocuments } from './rx-database-internal-store';\nimport { flatCloneDocWithMeta } from './rx-storage-helper';\n\n/**\n * fills in the default data.\n * This also clones the data.\n */\nexport function fillObjectDataBeforeInsert(\n schema: RxSchema,\n data: Partial> | any\n): RxDocumentData {\n let useJson = schema.fillObjectWithDefaults(data);\n useJson = fillPrimaryKey(\n schema.primaryPath,\n schema.jsonSchema,\n useJson\n );\n useJson._meta = getDefaultRxDocumentMeta();\n if (!useJson.hasOwnProperty('_deleted')) {\n useJson._deleted = false;\n }\n if (!useJson.hasOwnProperty('_attachments')) {\n useJson._attachments = {};\n }\n if (!useJson.hasOwnProperty('_rev')) {\n useJson._rev = getDefaultRevision();\n }\n return useJson;\n}\n\n/**\n * Creates the storage instances that are used internally in the collection\n */\nexport async function createRxCollectionStorageInstance(\n rxDatabase: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstanceCreationParams: RxStorageInstanceCreationParams\n): Promise> {\n storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance;\n const storageInstance = await rxDatabase.storage.createStorageInstance(\n storageInstanceCreationParams\n );\n return storageInstance;\n}\n\n/**\n * Removes the main storage of the collection\n * and all connected storages like the ones from the replication meta etc.\n */\nexport async function removeCollectionStorages(\n storage: RxStorage,\n databaseInternalStorage: RxStorageInstance, any, any>,\n databaseInstanceToken: string,\n databaseName: string,\n collectionName: string,\n /**\n * If no hash function is provided,\n * we assume that the whole internal store is removed anyway\n * so we do not have to delete the meta documents.\n */\n hashFunction?: HashFunction,\n) {\n const allCollectionMetaDocs = await getAllCollectionDocuments(\n storage.statics,\n databaseInternalStorage\n );\n const relevantCollectionMetaDocs = allCollectionMetaDocs\n .filter(metaDoc => metaDoc.data.name === collectionName);\n\n let removeStorages: {\n collectionName: string;\n schema: RxJsonSchema;\n isCollection: boolean;\n }[] = [];\n relevantCollectionMetaDocs.forEach(metaDoc => {\n removeStorages.push({\n collectionName: metaDoc.data.name,\n schema: metaDoc.data.schema,\n isCollection: true\n });\n metaDoc.data.connectedStorages.forEach(row => removeStorages.push({\n collectionName: row.collectionName,\n isCollection: false,\n schema: row.schema\n }));\n });\n\n // ensure uniqueness\n const alreadyAdded = new Set();\n removeStorages = removeStorages.filter(row => {\n const key = row.collectionName + '||' + row.schema.version;\n if (alreadyAdded.has(key)) {\n return false;\n } else {\n alreadyAdded.add(key);\n return true;\n }\n });\n\n // remove all the storages\n await Promise.all(\n removeStorages\n .map(async (row) => {\n const storageInstance = await storage.createStorageInstance({\n collectionName: row.collectionName,\n databaseInstanceToken,\n databaseName,\n multiInstance: false,\n options: {},\n schema: row.schema\n });\n await storageInstance.remove();\n if (row.isCollection) {\n await runAsyncPluginHooks('postRemoveRxCollection', {\n storage,\n databaseName: databaseName,\n collectionName\n });\n }\n })\n );\n\n // remove the meta documents\n if (hashFunction) {\n const writeRows = relevantCollectionMetaDocs.map(doc => {\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n writeDoc._meta.lwt = now();\n writeDoc._rev = createRevision(\n databaseInstanceToken,\n doc\n );\n return {\n previous: doc,\n document: writeDoc\n };\n });\n await databaseInternalStorage.bulkWrite(\n writeRows,\n 'rx-database-remove-collection-all'\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA;AAMA;AAIA;AACA;AACA;AAEA;AACA;AACA;AACA;AACO,SAASA,0BAA0B,CACtCC,MAA2B,EAC3BC,IAA8C,EACr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20a01b7 100644 --- a/dist/lib/rx-collection.js +++ b/dist/lib/rx-collection.js @@ -7,9 +7,11 @@ Object.defineProperty(exports, "__esModule", { exports.RxCollectionBase = void 0; exports.createRxCollection = createRxCollection; exports.isRxCollection = isRxCollection; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxCollectionHelper = require("./rx-collection-helper"); var _rxQuery = require("./rx-query"); var _rxError = require("./rx-error"); @@ -20,6 +22,8 @@ var _hooks = require("./hooks"); var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); var _rxStorageHelper = require("./rx-storage-helper"); var _replicationProtocol = require("./replication-protocol"); +var _incrementalWrite = require("./incremental-write"); +var _rxDocument = require("./rx-document"); var HOOKS_WHEN = ['pre', 'post']; var HOOKS_KEYS = ['insert', 'save', 'remove', 'create']; var hooksApplied = false; @@ -39,11 +43,12 @@ var RxCollectionBase = /*#__PURE__*/function () { var conflictHandler = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : _replicationProtocol.defaultConflictHandler; this.storageInstance = {}; this.timeouts = new Set(); - this._atomicUpsertQueues = new Map(); + this.incrementalWriteQueue = {}; + this._incrementalUpsertQueues = new Map(); this.synced = false; this.hooks = {}; this._subs = []; - this._docCache = new _docCache.DocCache(); + this._docCache = {}; this._queryCache = (0, _queryCache.createQueryCache)(); this.$ = {}; this._changeEventBuffer = {}; @@ -64,79 +69,87 @@ var RxCollectionBase = /*#__PURE__*/function () { _applyHookFunctions(this.asRxCollection); } var _proto = RxCollectionBase.prototype; - _proto.prepare = function prepare() { - try { + _proto.prepare = /*#__PURE__*/function () { + var _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var _this = this; - _this.storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(_this.database, _this.internalStorageInstance, _this.schema.jsonSchema); - _this.$ = _this.database.eventBulks$.pipe((0, _operators.filter)(function (changeEventBulk) { - return changeEventBulk.collectionName === _this.name; - }), (0, _operators.mergeMap)(function (changeEventBulk) { - return changeEventBulk.events; - })); - _this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(_this.asRxCollection); - - /** - * Instead of resolving the EventBulk array here and spit it into - * single events, we should fully work with event bulks internally - * to save performance. - */ - return Promise.resolve(_this.database.storageToken).then(function (databaseStorageToken) { - var subDocs = _this.storageInstance.changeStream().subscribe(function (eventBulk) { - var changeEventBulk = { - id: eventBulk.id, - internal: false, - collectionName: _this.name, - storageToken: databaseStorageToken, - events: eventBulk.events.map(function (ev) { - return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(false, ev, _this); - }), - databaseToken: _this.database.token, - checkpoint: eventBulk.checkpoint, - context: eventBulk.context - }; - _this.database.$emit(changeEventBulk); - }); - _this._subs.push(subDocs); - - /** - * When a write happens to the collection - * we find the changed document in the docCache - * and tell it that it has to change its data. - */ - _this._subs.push(_this.$.pipe((0, _operators.filter)(function (cE) { - return !cE.isLocal; - })).subscribe(function (cE) { - // when data changes, send it to RxDocument in docCache - var doc = _this._docCache.get(cE.documentId); - if (doc) { - doc._handleChangeEvent(cE); - } - })); + var databaseStorageToken, subDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + this.storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(this.database, this.internalStorageInstance, this.schema.jsonSchema); + this.incrementalWriteQueue = new _incrementalWrite.IncrementalWriteQueue(this.storageInstance, this.schema.primaryPath, function (newData, oldData) { + return (0, _rxDocument.beforeDocumentUpdateWrite)(_this, newData, oldData); + }, function (result) { + return _this._runHooks('post', 'save', result); + }); + this.$ = this.database.eventBulks$.pipe((0, _operators.filter)(function (changeEventBulk) { + return changeEventBulk.collectionName === _this.name; + }), (0, _operators.mergeMap)(function (changeEventBulk) { + return changeEventBulk.events; + })); + this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(this.asRxCollection); + this._docCache = new _docCache.DocumentCache(this.schema.primaryPath, this.$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })), function (docData) { + return (0, _rxDocumentPrototypeMerge.createNewRxDocument)(_this.asRxCollection, docData); + }); - /** - * Resolve the conflict tasks - * of the RxStorageInstance - */ - _this._subs.push(_this.storageInstance.conflictResultionTasks().subscribe(function (task) { - _this.conflictHandler(task.input, task.context).then(function (output) { - _this.storageInstance.resolveConflictResultionTask({ - id: task.id, - output: output + /** + * Instead of resolving the EventBulk array here and spit it into + * single events, we should fully work with event bulks internally + * to save performance. + */ + _context.next = 7; + return this.database.storageToken; + case 7: + databaseStorageToken = _context.sent; + subDocs = this.storageInstance.changeStream().subscribe(function (eventBulk) { + var changeEventBulk = { + id: eventBulk.id, + internal: false, + collectionName: _this.name, + storageToken: databaseStorageToken, + events: eventBulk.events.map(function (ev) { + return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(false, ev, _this); + }), + databaseToken: _this.database.token, + checkpoint: eventBulk.checkpoint, + context: eventBulk.context + }; + _this.database.$emit(changeEventBulk); }); - }); - })); - return _util.PROMISE_RESOLVE_VOID; - }); - } catch (e) { - return Promise.reject(e); + this._subs.push(subDocs); + + /** + * Resolve the conflict tasks + * of the RxStorageInstance + */ + this._subs.push(this.storageInstance.conflictResultionTasks().subscribe(function (task) { + _this.conflictHandler(task.input, task.context).then(function (output) { + _this.storageInstance.resolveConflictResultionTask({ + id: task.id, + output: output + }); + }); + })); + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 12: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function prepare() { + return _prepare.apply(this, arguments); } - } // overwritte by migration-plugin + return prepare; + }() // overwritte by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { - throw (0, _util.pluginMissing)('migration'); + throw (0, _utils.pluginMissing)('migration'); }; _proto.getDataMigrator = function getDataMigrator() { - throw (0, _util.pluginMissing)('migration'); + throw (0, _utils.pluginMissing)('migration'); }; _proto.migrate = function migrate() { var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; @@ -146,182 +159,272 @@ var RxCollectionBase = /*#__PURE__*/function () { var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; return this.getDataMigrator().migratePromise(batchSize); }; - _proto.insert = function insert(json) { - try { - var _this2 = this; - // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later - var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this2.schema, json); - return Promise.resolve(_this2.bulkInsert([useJson])).then(function (writeResult) { - var isError = writeResult.error[0]; - (0, _rxStorageHelper.throwIfIsStorageWriteError)(_this2, useJson[_this2.schema.primaryPath], json, isError); - var insertResult = (0, _util.ensureNotFalsy)(writeResult.success[0]); - return insertResult; - }); - } catch (e) { - return Promise.reject(e); + _proto.insert = /*#__PURE__*/function () { + var _insert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(json) { + var useJson, writeResult, isError, insertResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later + useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this.schema, json); + _context2.next = 3; + return this.bulkInsert([useJson]); + case 3: + writeResult = _context2.sent; + isError = writeResult.error[0]; + (0, _rxStorageHelper.throwIfIsStorageWriteError)(this, useJson[this.schema.primaryPath], json, isError); + insertResult = (0, _utils.ensureNotFalsy)(writeResult.success[0]); + return _context2.abrupt("return", insertResult); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function insert(_x) { + return _insert.apply(this, arguments); } - }; - _proto.bulkInsert = function bulkInsert(docsData) { - try { - var _temp3 = function _temp3(docs) { - var docsMap = new Map(); - var insertRows = docs.map(function (doc) { - docsMap.set(doc[_this3.schema.primaryPath], doc); - var docData = Object.assign(doc, { - _attachments: {}, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _deleted: false - }); - var row = { - document: docData - }; - return row; - }); - return Promise.resolve(_this3.storageInstance.bulkWrite(insertRows, 'rx-collection-bulk-insert')).then(function (results) { - function _temp2() { - return { + return insert; + }(); + _proto.bulkInsert = /*#__PURE__*/function () { + var _bulkInsert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(docsData) { + var _this2 = this; + var useDocs, docs, docsMap, insertRows, results, successDocData, rxDocuments; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!(docsData.length === 0)) { + _context3.next = 2; + break; + } + return _context3.abrupt("return", { + success: [], + error: [] + }); + case 2: + useDocs = docsData.map(function (docData) { + var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this2.schema, docData); + return useDocData; + }); + if (!this.hasHooks('pre', 'insert')) { + _context3.next = 9; + break; + } + _context3.next = 6; + return Promise.all(useDocs.map(function (doc) { + return _this2._runHooks('pre', 'insert', doc).then(function () { + return doc; + }); + })); + case 6: + _context3.t0 = _context3.sent; + _context3.next = 10; + break; + case 9: + _context3.t0 = useDocs; + case 10: + docs = _context3.t0; + docsMap = new Map(); + insertRows = docs.map(function (doc) { + docsMap.set(doc[_this2.schema.primaryPath], doc); + var docData = Object.assign(doc, { + _attachments: {}, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _deleted: false + }); + var row = { + document: docData + }; + return row; + }); + _context3.next = 15; + return this.storageInstance.bulkWrite(insertRows, 'rx-collection-bulk-insert'); + case 15: + results = _context3.sent; + // create documents + successDocData = Object.values(results.success); + rxDocuments = successDocData.map(function (writtenDocData) { + return _this2._docCache.getCachedRxDocument(writtenDocData); + }); + if (!this.hasHooks('post', 'insert')) { + _context3.next = 21; + break; + } + _context3.next = 21; + return Promise.all(rxDocuments.map(function (doc) { + return _this2._runHooks('post', 'insert', docsMap.get(doc.primary), doc); + })); + case 21: + return _context3.abrupt("return", { success: rxDocuments, error: Object.values(results.error) - }; - } - // create documents - var successDocData = Object.values(results.success); - var rxDocuments = successDocData.map(function (writtenDocData) { - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this3, writtenDocData); - return doc; - }); - var _temp = function () { - if (_this3.hasHooks('post', 'insert')) { - return Promise.resolve(Promise.all(rxDocuments.map(function (doc) { - return _this3._runHooks('post', 'insert', docsMap.get(doc.primary), doc); - }))).then(function () {}); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - }; - var _this3 = this; - /** - * Optimization shortcut, - * do nothing when called with an empty array - */ - if (docsData.length === 0) { - return Promise.resolve({ - success: [], - error: [] - }); - } - var useDocs = docsData.map(function (docData) { - var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this3.schema, docData); - return useDocData; - }); - var _this3$hasHooks = _this3.hasHooks('pre', 'insert'); - return Promise.resolve(_this3$hasHooks ? Promise.resolve(Promise.all(useDocs.map(function (doc) { - return _this3._runHooks('pre', 'insert', doc).then(function () { - return doc; - }); - }))).then(_temp3) : _temp3(useDocs)); - } catch (e) { - return Promise.reject(e); + }); + case 22: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function bulkInsert(_x2) { + return _bulkInsert.apply(this, arguments); } - }; - _proto.bulkRemove = function bulkRemove(ids) { - try { - var _this4 = this; - /** - * Optimization shortcut, - * do nothing when called with an empty array - */ - if (ids.length === 0) { - return Promise.resolve({ - success: [], - error: [] - }); - } - return Promise.resolve(_this4.findByIds(ids)).then(function (rxDocumentMap) { - var docsData = []; - var docsMap = new Map(); - Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { - var data = (0, _util.clone)(rxDocument.toJSON(true)); - docsData.push(data); - docsMap.set(rxDocument.primary, data); - }); - return Promise.resolve(Promise.all(docsData.map(function (doc) { - var primary = doc[_this4.schema.primaryPath]; - return _this4._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); - }))).then(function () { - var removeDocs = docsData.map(function (doc) { - var writeDoc = (0, _util.flatClone)(doc); - writeDoc._deleted = true; - return { - previous: doc, - document: writeDoc - }; - }); - return Promise.resolve(_this4.storageInstance.bulkWrite(removeDocs, 'rx-collection-bulk-remove')).then(function (results) { - var successIds = Object.keys(results.success); - - // run hooks - return Promise.resolve(Promise.all(successIds.map(function (id) { - return _this4._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); - }))).then(function () { - var rxDocuments = successIds.map(function (id) { - return rxDocumentMap.get(id); - }); + return bulkInsert; + }(); + _proto.bulkRemove = /*#__PURE__*/function () { + var _bulkRemove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ids) { + var _this3 = this; + var rxDocumentMap, docsData, docsMap, removeDocs, results, successIds, rxDocuments; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(ids.length === 0)) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", { + success: [], + error: [] + }); + case 2: + _context4.next = 4; + return this.findByIds(ids).exec(); + case 4: + rxDocumentMap = _context4.sent; + docsData = []; + docsMap = new Map(); + Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { + var data = rxDocument.toMutableJSON(true); + docsData.push(data); + docsMap.set(rxDocument.primary, data); + }); + _context4.next = 10; + return Promise.all(docsData.map(function (doc) { + var primary = doc[_this3.schema.primaryPath]; + return _this3._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); + })); + case 10: + removeDocs = docsData.map(function (doc) { + var writeDoc = (0, _utils.flatClone)(doc); + writeDoc._deleted = true; return { - success: rxDocuments, - error: Object.values(results.error) + previous: doc, + document: writeDoc }; }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); + _context4.next = 13; + return this.storageInstance.bulkWrite(removeDocs, 'rx-collection-bulk-remove'); + case 13: + results = _context4.sent; + successIds = Object.keys(results.success); // run hooks + _context4.next = 17; + return Promise.all(successIds.map(function (id) { + return _this3._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); + })); + case 17: + rxDocuments = successIds.map(function (id) { + return (0, _utils.getFromMapOrThrow)(rxDocumentMap, id); + }); + return _context4.abrupt("return", { + success: rxDocuments, + error: Object.values(results.error) + }); + case 19: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function bulkRemove(_x3) { + return _bulkRemove.apply(this, arguments); } - } + return bulkRemove; + }() /** * same as bulkInsert but overwrites existing document with same primary */ ; - _proto.bulkUpsert = function bulkUpsert(docsData) { - try { - var _this5 = this; - var insertData = []; - var useJsonByDocId = new Map(); - docsData.forEach(function (docData) { - var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this5.schema, docData); - var primary = useJson[_this5.schema.primaryPath]; - if (!primary) { - throw (0, _rxError.newRxError)('COL3', { - primaryPath: _this5.schema.primaryPath, - data: useJson, - schema: _this5.schema.jsonSchema - }); + _proto.bulkUpsert = + /*#__PURE__*/ + function () { + var _bulkUpsert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(docsData) { + var _this4 = this; + var insertData, useJsonByDocId, insertResult, ret, updatedDocs; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + insertData = []; + useJsonByDocId = new Map(); + docsData.forEach(function (docData) { + var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this4.schema, docData); + var primary = useJson[_this4.schema.primaryPath]; + if (!primary) { + throw (0, _rxError.newRxError)('COL3', { + primaryPath: _this4.schema.primaryPath, + data: useJson, + schema: _this4.schema.jsonSchema + }); + } + useJsonByDocId.set(primary, useJson); + insertData.push(useJson); + }); + _context6.next = 5; + return this.bulkInsert(insertData); + case 5: + insertResult = _context6.sent; + ret = insertResult.success.slice(0); + _context6.next = 9; + return Promise.all(insertResult.error.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(error) { + var id, writeData, docDataInDb, doc, newDoc; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!(error.status !== 409)) { + _context5.next = 2; + break; + } + throw (0, _rxError.newRxError)('VD2', { + collection: _this4.name, + writeError: error + }); + case 2: + id = error.documentId; + writeData = (0, _utils.getFromMapOrThrow)(useJsonByDocId, id); + docDataInDb = (0, _utils.ensureNotFalsy)(error.documentInDb); + doc = _this4._docCache.getCachedRxDocument(docDataInDb); + _context5.next = 8; + return doc.incrementalModify(function () { + return writeData; + }); + case 8: + newDoc = _context5.sent; + return _context5.abrupt("return", newDoc); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x5) { + return _ref.apply(this, arguments); + }; + }())); + case 9: + updatedDocs = _context6.sent; + ret = ret.concat(updatedDocs); + return _context6.abrupt("return", ret); + case 12: + case "end": + return _context6.stop(); } - useJsonByDocId.set(primary, useJson); - insertData.push(useJson); - }); - return Promise.resolve(_this5.bulkInsert(insertData)).then(function (insertResult) { - var ret = insertResult.success.slice(0); - return Promise.resolve(Promise.all(insertResult.error.map(function (error) { - var id = error.documentId; - var writeData = (0, _util.getFromMapOrThrow)(useJsonByDocId, id); - var docDataInDb = (0, _util.ensureNotFalsy)(error.documentInDb); - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this5.asRxCollection, docDataInDb); - return doc.atomicUpdate(function () { - return writeData; - }); - }))).then(function (updatedDocs) { - ret = ret.concat(updatedDocs); - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); + }, _callee6, this); + })); + function bulkUpsert(_x4) { + return _bulkUpsert.apply(this, arguments); } - } + return bulkUpsert; + }() /** * same as insert but overwrites existing document with same primary */ @@ -333,10 +436,10 @@ var RxCollectionBase = /*#__PURE__*/function () { } /** - * upserts to a RxDocument, uses atomicUpdate if document already exists + * upserts to a RxDocument, uses incrementalModify if document already exists */; - _proto.atomicUpsert = function atomicUpsert(json) { - var _this6 = this; + _proto.incrementalUpsert = function incrementalUpsert(json) { + var _this5 = this; var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this.schema, json); var primary = useJson[this.schema.primaryPath]; if (!primary) { @@ -346,22 +449,20 @@ var RxCollectionBase = /*#__PURE__*/function () { } // ensure that it won't try 2 parallel runs - var queue = this._atomicUpsertQueues.get(primary); + var queue = this._incrementalUpsertQueues.get(primary); if (!queue) { - queue = _util.PROMISE_RESOLVE_VOID; + queue = _utils.PROMISE_RESOLVE_VOID; } queue = queue.then(function () { - return _atomicUpsertEnsureRxDocumentExists(_this6, primary, useJson); + return _incrementalUpsertEnsureRxDocumentExists(_this5, primary, useJson); }).then(function (wasInserted) { if (!wasInserted.inserted) { - return _atomicUpsertUpdate(wasInserted.doc, useJson).then(function () { - return wasInserted.doc; - }); + return _incrementalUpsertUpdate(wasInserted.doc, useJson); } else { return wasInserted.doc; } }); - this._atomicUpsertQueues.set(primary, queue); + this._incrementalUpsertQueues.set(primary, queue); return queue; }; _proto.find = function find(queryObj) { @@ -373,7 +474,7 @@ var RxCollectionBase = /*#__PURE__*/function () { if (!queryObj) { queryObj = (0, _rxQuery._getDefaultQuery)(); } - var query = (0, _rxQuery.createRxQuery)('find', queryObj, this.asRxCollection); + var query = (0, _rxQuery.createRxQuery)('find', queryObj, this); return query; }; _proto.findOne = function findOne(queryObj) { @@ -394,7 +495,7 @@ var RxCollectionBase = /*#__PURE__*/function () { throw (0, _rxError.newRxError)('QU6'); } queryObj.limit = 1; - query = (0, _rxQuery.createRxQuery)('findOne', queryObj, this.asRxCollection); + query = (0, _rxQuery.createRxQuery)('findOne', queryObj, this); } if (typeof queryObj === 'number' || Array.isArray(queryObj)) { throw (0, _rxError.newRxTypeError)('COL6', { @@ -407,7 +508,7 @@ var RxCollectionBase = /*#__PURE__*/function () { if (!queryObj) { queryObj = (0, _rxQuery._getDefaultQuery)(); } - var query = (0, _rxQuery.createRxQuery)('count', queryObj, this.asRxCollection); + var query = (0, _rxQuery.createRxQuery)('count', queryObj, this); return query; } @@ -416,158 +517,21 @@ var RxCollectionBase = /*#__PURE__*/function () { * has way better performance then running multiple findOne() or a find() with a complex $or-selected */; _proto.findByIds = function findByIds(ids) { - try { - var _this7 = this; - var ret = new Map(); - var mustBeQueried = []; - - // first try to fill from docCache - ids.forEach(function (id) { - var doc = _this7._docCache.get(id); - if (doc) { - ret.set(id, doc); - } else { - mustBeQueried.push(id); - } - }); - - // find everything which was not in docCache - var _temp4 = function () { - if (mustBeQueried.length > 0) { - return Promise.resolve(_this7.storageInstance.findDocumentsById(mustBeQueried, false)).then(function (docs) { - Object.values(docs).forEach(function (docData) { - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this7, docData); - ret.set(doc.primary, doc); - }); - }); - } - }(); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(function () { - return ret; - }) : ret); - } catch (e) { - return Promise.reject(e); - } - } - /** - * like this.findByIds but returns an observable - * that always emits the current state - */ - ; - _proto.findByIds$ = function findByIds$(ids) { - var _this8 = this; - var currentValue = null; - var lastChangeEvent = -1; - - /** - * Ensure we do not process events in parallel - */ - var queue = _util.PROMISE_RESOLVE_VOID; - var initialPromise = this.findByIds(ids).then(function (docsMap) { - lastChangeEvent = _this8._changeEventBuffer.counter; - currentValue = docsMap; - }); - var firstEmitDone = false; - return this.$.pipe((0, _operators.startWith)(null), - /** - * Optimization shortcut. - * Do not proceed if the emitted RxChangeEvent - * is not relevant for the query. - */ - (0, _operators.filter)(function (changeEvent) { - if ( - // first emit has no event - changeEvent && ( - // local documents are not relevant for the query - changeEvent.isLocal || - // document of the change is not in the ids list. - !ids.includes(changeEvent.documentId))) { - return false; - } else { - return true; - } - }), (0, _operators.mergeMap)(function () { - return initialPromise; - }), - /** - * Because shareReplay with refCount: true - * will often subscribe/unsusbscribe - * we always ensure that we handled all missed events - * since the last subscription. - */ - (0, _operators.mergeMap)(function () { - queue = queue.then(function () { - try { - var _temp7 = function _temp7(_result) { - if (_exit) return _result; - firstEmitDone = true; - return currentValue; - }; - var _exit = false; - /** - * We first have to clone the Map - * to ensure we do not create side effects by mutating - * a Map that has already been returned before. - */ - currentValue = new Map((0, _util.ensureNotFalsy)(currentValue)); - var missedChangeEvents = _this8._changeEventBuffer.getFrom(lastChangeEvent + 1); - lastChangeEvent = _this8._changeEventBuffer.counter; - var _temp6 = function () { - if (missedChangeEvents === null) { - /** - * changeEventBuffer is of bounds -> we must re-execute over the database - * because we cannot calculate the new results just from the events. - */ - return Promise.resolve(_this8.findByIds(ids)).then(function (newResult) { - lastChangeEvent = _this8._changeEventBuffer.counter; - _exit = true; - return newResult; - }); - } else { - var resultHasChanged = false; - missedChangeEvents.forEach(function (rxChangeEvent) { - var docId = rxChangeEvent.documentId; - if (!ids.includes(docId)) { - // document is not relevant for the result set - return; - } - var op = rxChangeEvent.operation; - if (op === 'INSERT' || op === 'UPDATE') { - resultHasChanged = true; - var rxDocument = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this8.asRxCollection, rxChangeEvent.documentData); - (0, _util.ensureNotFalsy)(currentValue).set(docId, rxDocument); - } else { - if ((0, _util.ensureNotFalsy)(currentValue).has(docId)) { - resultHasChanged = true; - (0, _util.ensureNotFalsy)(currentValue)["delete"](docId); - } - } - }); - - // nothing happened that affects the result -> do not emit - if (!resultHasChanged && firstEmitDone) { - var _temp5 = false; - _exit = true; - return _temp5; - } - } - }(); - return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(_temp7) : _temp7(_temp6)); - } catch (e) { - return Promise.reject(e); - } - }); - return queue; - }), (0, _operators.filter)(function (x) { - return !!x; - }), (0, _operators.shareReplay)(_util.RXJS_SHARE_REPLAY_DEFAULTS)); + var _selector2; + var mangoQuery = { + selector: (_selector2 = {}, _selector2[this.schema.primaryPath] = { + $in: ids.slice(0) + }, _selector2) + }; + var query = (0, _rxQuery.createRxQuery)('findByIds', mangoQuery, this); + return query; } /** * Export collection to a JSON friendly format. */; _proto.exportJSON = function exportJSON() { - throw (0, _util.pluginMissing)('json-dump'); + throw (0, _utils.pluginMissing)('json-dump'); } /** @@ -575,33 +539,10 @@ var RxCollectionBase = /*#__PURE__*/function () { * @param _exportedJSON The previously exported data from the `.exportJSON()` method. */; _proto.importJSON = function importJSON(_exportedJSON) { - throw (0, _util.pluginMissing)('json-dump'); + throw (0, _utils.pluginMissing)('json-dump'); }; _proto.insertCRDT = function insertCRDT(_updateObj) { - throw (0, _util.pluginMissing)('crdt'); - } - - /** - * sync with a CouchDB endpoint - */; - _proto.syncCouchDB = function syncCouchDB(_syncOptions) { - throw (0, _util.pluginMissing)('replication'); - } - - /** - * sync with a GraphQL endpoint - */; - _proto.syncGraphQL = function syncGraphQL(_options) { - throw (0, _util.pluginMissing)('replication-graphql'); - }; - _proto.syncCouchDBNew = function syncCouchDBNew(_syncOptions) { - throw (0, _util.pluginMissing)('replication-couchdb-new'); - }; - _proto.syncP2P = function syncP2P(_syncOptions) { - throw (0, _util.pluginMissing)('replication-p2p'); - }; - _proto.syncFirestore = function syncFirestore(_syncOptions) { - throw (0, _util.pluginMissing)('replication-firestore'); + throw (0, _utils.pluginMissing)('crdt'); } /** @@ -663,7 +604,7 @@ var RxCollectionBase = /*#__PURE__*/function () { _proto._runHooks = function _runHooks(when, key, data, instance) { var hooks = this.getHooks(when, key); if (!hooks) { - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } // run parallel: false @@ -672,7 +613,7 @@ var RxCollectionBase = /*#__PURE__*/function () { return hook(data, instance); }; }); - return (0, _util.promiseSeries)(tasks) + return (0, _utils.promiseSeries)(tasks) // run parallel: true .then(function () { return Promise.all(hooks.parallel.map(function (hook) { @@ -698,20 +639,20 @@ var RxCollectionBase = /*#__PURE__*/function () { * so that no running timeouts prevent the exit of the JavaScript process. */; _proto.promiseWait = function promiseWait(time) { - var _this9 = this; + var _this6 = this; var ret = new Promise(function (res) { var timeout = setTimeout(function () { - _this9.timeouts["delete"](timeout); + _this6.timeouts["delete"](timeout); res(); }, time); - _this9.timeouts.add(timeout); + _this6.timeouts.add(timeout); }); return ret; }; _proto.destroy = function destroy() { - var _this10 = this; + var _this7 = this; if (this.destroyed) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } /** @@ -736,11 +677,11 @@ var RxCollectionBase = /*#__PURE__*/function () { * but the change is not added to the changes collection. */ return this.database.requestIdlePromise().then(function () { - return Promise.all(_this10.onDestroy.map(function (fn) { + return Promise.all(_this7.onDestroy.map(function (fn) { return fn(); })); }).then(function () { - return _this10.storageInstance.close(); + return _this7.storageInstance.close(); }).then(function () { /** * Unsubscribing must be done AFTER the storageInstance.close() @@ -748,11 +689,11 @@ var RxCollectionBase = /*#__PURE__*/function () { * otherwise there might be open conflicts to be resolved which * will then stuck and never resolve. */ - _this10._subs.forEach(function (sub) { + _this7._subs.forEach(function (sub) { return sub.unsubscribe(); }); - delete _this10.database.collections[_this10.name]; - return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', _this10).then(function () { + delete _this7.database.collections[_this7.name]; + return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', _this7).then(function () { return true; }); }); @@ -761,16 +702,29 @@ var RxCollectionBase = /*#__PURE__*/function () { /** * remove all data of the collection */; - _proto.remove = function remove() { - try { - var _this11 = this; - return Promise.resolve(_this11.destroy()).then(function () { - return Promise.resolve((0, _rxCollectionHelper.removeCollectionStorages)(_this11.database.storage, _this11.database.internalStore, _this11.database.token, _this11.database.name, _this11.name, _this11.database.hashFunction)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + _proto.remove = + /*#__PURE__*/ + function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.destroy(); + case 2: + _context7.next = 4; + return (0, _rxCollectionHelper.removeCollectionStorages)(this.database.storage, this.database.internalStore, this.database.token, this.database.name, this.name, this.database.hashFunction); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); (0, _createClass2["default"])(RxCollectionBase, [{ key: "insert$", get: function get() { @@ -811,20 +765,16 @@ function _applyHookFunctions(collection) { var colProto = Object.getPrototypeOf(collection); HOOKS_KEYS.forEach(function (key) { HOOKS_WHEN.map(function (when) { - var fnName = when + (0, _util.ucfirst)(key); + var fnName = when + (0, _utils.ucfirst)(key); colProto[fnName] = function (fun, parallel) { return this.addHook(when, key, fun, parallel); }; }); }); } -function _atomicUpsertUpdate(doc, json) { - return doc.atomicUpdate(function (_innerDoc) { +function _incrementalUpsertUpdate(doc, json) { + return doc.incrementalModify(function (_innerDoc) { return json; - }).then(function () { - return (0, _util.nextTick)(); - }).then(function () { - return doc; }); } @@ -832,15 +782,15 @@ function _atomicUpsertUpdate(doc, json) { * ensures that the given document exists * @return promise that resolves with new doc and flag if inserted */ -function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { +function _incrementalUpsertEnsureRxDocumentExists(rxCollection, primary, json) { /** * Optimisation shortcut, * first try to find the document in the doc-cache */ - var docFromCache = rxCollection._docCache.get(primary); - if (docFromCache) { + var docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary); + if (docDataFromCache) { return Promise.resolve({ - doc: docFromCache, + doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache), inserted: false }); } @@ -864,30 +814,30 @@ function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { /** * creates and prepares a new collection */ -function createRxCollection(_ref) { - var database = _ref.database, - name = _ref.name, - schema = _ref.schema, - _ref$instanceCreation = _ref.instanceCreationOptions, - instanceCreationOptions = _ref$instanceCreation === void 0 ? {} : _ref$instanceCreation, - _ref$migrationStrateg = _ref.migrationStrategies, - migrationStrategies = _ref$migrationStrateg === void 0 ? {} : _ref$migrationStrateg, - _ref$autoMigrate = _ref.autoMigrate, - autoMigrate = _ref$autoMigrate === void 0 ? true : _ref$autoMigrate, - _ref$statics = _ref.statics, - statics = _ref$statics === void 0 ? {} : _ref$statics, - _ref$methods = _ref.methods, - methods = _ref$methods === void 0 ? {} : _ref$methods, - _ref$attachments = _ref.attachments, - attachments = _ref$attachments === void 0 ? {} : _ref$attachments, - _ref$options = _ref.options, - options = _ref$options === void 0 ? {} : _ref$options, - _ref$localDocuments = _ref.localDocuments, - localDocuments = _ref$localDocuments === void 0 ? false : _ref$localDocuments, - _ref$cacheReplacement = _ref.cacheReplacementPolicy, - cacheReplacementPolicy = _ref$cacheReplacement === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref$cacheReplacement, - _ref$conflictHandler = _ref.conflictHandler, - conflictHandler = _ref$conflictHandler === void 0 ? _replicationProtocol.defaultConflictHandler : _ref$conflictHandler; +function createRxCollection(_ref2) { + var database = _ref2.database, + name = _ref2.name, + schema = _ref2.schema, + _ref2$instanceCreatio = _ref2.instanceCreationOptions, + instanceCreationOptions = _ref2$instanceCreatio === void 0 ? {} : _ref2$instanceCreatio, + _ref2$migrationStrate = _ref2.migrationStrategies, + migrationStrategies = _ref2$migrationStrate === void 0 ? {} : _ref2$migrationStrate, + _ref2$autoMigrate = _ref2.autoMigrate, + autoMigrate = _ref2$autoMigrate === void 0 ? true : _ref2$autoMigrate, + _ref2$statics = _ref2.statics, + statics = _ref2$statics === void 0 ? {} : _ref2$statics, + _ref2$methods = _ref2.methods, + methods = _ref2$methods === void 0 ? {} : _ref2$methods, + _ref2$attachments = _ref2.attachments, + attachments = _ref2$attachments === void 0 ? {} : _ref2$attachments, + _ref2$options = _ref2.options, + options = _ref2$options === void 0 ? {} : _ref2$options, + _ref2$localDocuments = _ref2.localDocuments, + localDocuments = _ref2$localDocuments === void 0 ? false : _ref2$localDocuments, + _ref2$cacheReplacemen = _ref2.cacheReplacementPolicy, + cacheReplacementPolicy = _ref2$cacheReplacemen === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref2$cacheReplacemen, + _ref2$conflictHandler = _ref2.conflictHandler, + conflictHandler = _ref2$conflictHandler === void 0 ? _replicationProtocol.defaultConflictHandler : _ref2$conflictHandler; var storageInstanceCreationParams = { databaseInstanceToken: database.token, databaseName: database.name, @@ -902,16 +852,16 @@ function createRxCollection(_ref) { var collection = new RxCollectionBase(database, name, schema, storageInstance, instanceCreationOptions, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics, conflictHandler); return collection.prepare().then(function () { // ORM add statics - Object.entries(statics).forEach(function (_ref2) { - var funName = _ref2[0], - fun = _ref2[1]; + Object.entries(statics).forEach(function (_ref3) { + var funName = _ref3[0], + fun = _ref3[1]; Object.defineProperty(collection, funName, { get: function get() { return fun.bind(collection); } }); }); - var ret = _util.PROMISE_RESOLVE_VOID; + var ret = _utils.PROMISE_RESOLVE_VOID; if (autoMigrate && collection.schema.version !== 0) { ret = collection.migratePromise(); } diff --git a/dist/lib/rx-collection.js.map b/dist/lib/rx-collection.js.map index 87907069eba..8e2717f440e 100644 --- a/dist/lib/rx-collection.js.map +++ b/dist/lib/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","defaultCacheReplacementPolicy","statics","conflictHandler","defaultConflictHandler","storageInstance","timeouts","Set","_atomicUpsertQueues","Map","synced","hooks","_subs","_docCache","DocCache","_queryCache","createQueryCache","$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","prepare","getWrappedStorageInstance","jsonSchema","eventBulks$","pipe","filter","changeEventBulk","collectionName","mergeMap","events","createChangeEventBuffer","storageToken","databaseStorageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","map","ev","storageChangeEventToRxChangeEvent","databaseToken","token","checkpoint","context","$emit","push","cE","isLocal","doc","get","documentId","_handleChangeEvent","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","migrationNeeded","pluginMissing","getDataMigrator","migrate","batchSize","migratePromise","insert","json","useJson","fillObjectDataBeforeInsert","bulkInsert","writeResult","isError","error","throwIfIsStorageWriteError","primaryPath","insertResult","ensureNotFalsy","success","docsData","docs","docsMap","insertRows","set","docData","Object","assign","_attachments","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_deleted","row","document","bulkWrite","results","rxDocuments","values","successDocData","writtenDocData","createRxDocument","hasHooks","Promise","all","_runHooks","primary","length","useDocs","useDocData","bulkRemove","ids","findByIds","rxDocumentMap","Array","from","forEach","rxDocument","data","clone","toJSON","removeDocs","writeDoc","flatClone","previous","successIds","keys","bulkUpsert","insertData","useJsonByDocId","newRxError","ret","slice","writeData","getFromMapOrThrow","docDataInDb","documentInDb","atomicUpdate","updatedDocs","concat","upsert","result","atomicUpsert","queue","_atomicUpsertEnsureRxDocumentExists","wasInserted","inserted","_atomicUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","selector","limit","isArray","newRxTypeError","count","mustBeQueried","findDocumentsById","findByIds$","currentValue","lastChangeEvent","initialPromise","counter","firstEmitDone","startWith","changeEvent","includes","missedChangeEvents","getFrom","newResult","resultHasChanged","rxChangeEvent","docId","op","operation","documentData","has","x","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","syncCouchDB","_syncOptions","syncGraphQL","_options","syncCouchDBNew","syncP2P","syncFirestore","addHook","when","key","fun","parallel","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","res","timeout","setTimeout","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","hashFunction","collection","colProto","getPrototypeOf","fnName","ucfirst","_innerDoc","nextTick","rxCollection","docFromCache","resolve","exec","newDoc","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n startWith,\n mergeMap,\n shareReplay\n} from 'rxjs/operators';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n clone,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID,\n RXJS_SHARE_REPLAY_DEFAULTS,\n getDefaultRxDocumentMeta,\n getDefaultRevision,\n nextTick\n} from './util';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCouchDBReplicationState,\n MigrationState,\n SyncOptions,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n SyncOptionsGraphQL,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageBulkWriteError,\n RxDocumentData,\n RxDocumentWriteData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex\n} from './types';\nimport type {\n RxGraphQLReplicationState\n} from './plugins/replication-graphql';\nimport type {\n RxCouchDBNewReplicationState,\n SyncOptionsCouchDBNew\n} from './plugins/replication-couchdb-new';\nimport type {\n SyncOptionsP2P,\n RxP2PReplicationPool\n} from './plugins/replication-p2p';\nimport type {\n RxFirestoreReplicationState,\n SyncOptionsFirestore\n} from './plugins/replication-firestore';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: RxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: KeyFunctionMap = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _atomicUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocCache> = new DocCache();\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n\n this.$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * When a write happens to the collection\n * we find the changed document in the docCache\n * and tell it that it has to change its data.\n */\n this._subs.push(\n this.$\n .pipe(\n filter((cE: RxChangeEvent) => !cE.isLocal)\n )\n .subscribe(cE => {\n // when data changes, send it to RxDocument in docCache\n const doc = this._docCache.get(cE.documentId);\n if (doc) {\n doc._handleChangeEvent(cE);\n }\n })\n );\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n // overwritte by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n\n // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later\n const useJson: RxDocumentWriteData = fillObjectDataBeforeInsert(this.schema, json);\n\n const writeResult = await this.bulkInsert([useJson]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, useJson[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageBulkWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[this.schema.primaryPath] as any, doc);\n const docData = Object.assign(doc, {\n _attachments: {},\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _deleted: false\n });\n const row: BulkWriteRow = { document: docData };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const successDocData: RxDocumentData[] = Object.values(results.success);\n const rxDocuments: any[] = successDocData\n .map((writtenDocData) => {\n const doc = createRxDocument(this as any, writtenDocData);\n return doc;\n });\n\n if (this.hasHooks('post', 'insert')) {\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageBulkWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids);\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = clone(rxDocument.toJSON(true)) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = Object.keys(results.success);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments: any[] = successIds.map(id => {\n return rxDocumentMap.get(id);\n });\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise[]> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(error => {\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = createRxDocument(this.asRxCollection, docDataInDb);\n return doc.atomicUpdate(() => writeData);\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[0]);\n }\n\n /**\n * upserts to a RxDocument, uses atomicUpdate if document already exists\n */\n atomicUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._atomicUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _atomicUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _atomicUpsertUpdate(wasInserted.doc, useJson)\n .then(() => wasInserted.doc);\n } else {\n return wasInserted.doc;\n }\n });\n this._atomicUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this.asRxCollection);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null\n > {\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n // cannot have limit on findOne queries because it will be overwritte\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this.asRxCollection);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this.asRxCollection);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n async findByIds(\n ids: string[]\n ): Promise>> {\n\n const ret = new Map();\n const mustBeQueried: string[] = [];\n\n // first try to fill from docCache\n ids.forEach(id => {\n const doc = this._docCache.get(id);\n if (doc) {\n ret.set(id, doc);\n } else {\n mustBeQueried.push(id);\n }\n });\n\n // find everything which was not in docCache\n if (mustBeQueried.length > 0) {\n const docs = await this.storageInstance.findDocumentsById(mustBeQueried, false);\n Object.values(docs).forEach(docData => {\n const doc = createRxDocument(this as any, docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret;\n }\n\n /**\n * like this.findByIds but returns an observable\n * that always emits the current state\n */\n findByIds$(\n ids: string[]\n ): Observable>> {\n let currentValue: Map> | null = null;\n let lastChangeEvent: number = -1;\n\n /**\n * Ensure we do not process events in parallel\n */\n let queue: Promise = PROMISE_RESOLVE_VOID;\n\n const initialPromise = this.findByIds(ids).then(docsMap => {\n lastChangeEvent = this._changeEventBuffer.counter;\n currentValue = docsMap;\n });\n let firstEmitDone = false;\n\n return this.$.pipe(\n startWith(null),\n /**\n * Optimization shortcut.\n * Do not proceed if the emitted RxChangeEvent\n * is not relevant for the query.\n */\n filter(changeEvent => {\n if (\n // first emit has no event\n changeEvent &&\n (\n // local documents are not relevant for the query\n changeEvent.isLocal ||\n // document of the change is not in the ids list.\n !ids.includes(changeEvent.documentId)\n )\n ) {\n return false;\n } else {\n return true;\n }\n }),\n mergeMap(() => initialPromise),\n /**\n * Because shareReplay with refCount: true\n * will often subscribe/unsusbscribe\n * we always ensure that we handled all missed events\n * since the last subscription.\n */\n mergeMap(() => {\n queue = queue.then(async () => {\n /**\n * We first have to clone the Map\n * to ensure we do not create side effects by mutating\n * a Map that has already been returned before.\n */\n currentValue = new Map(ensureNotFalsy(currentValue));\n const missedChangeEvents = this._changeEventBuffer.getFrom(lastChangeEvent + 1);\n lastChangeEvent = this._changeEventBuffer.counter;\n if (missedChangeEvents === null) {\n /**\n * changeEventBuffer is of bounds -> we must re-execute over the database\n * because we cannot calculate the new results just from the events.\n */\n const newResult = await this.findByIds(ids);\n lastChangeEvent = this._changeEventBuffer.counter;\n return newResult;\n } else {\n let resultHasChanged = false;\n missedChangeEvents\n .forEach(rxChangeEvent => {\n const docId = rxChangeEvent.documentId;\n if (!ids.includes(docId)) {\n // document is not relevant for the result set\n return;\n }\n const op = rxChangeEvent.operation;\n if (op === 'INSERT' || op === 'UPDATE') {\n resultHasChanged = true;\n const rxDocument = createRxDocument(\n this.asRxCollection,\n rxChangeEvent.documentData\n );\n ensureNotFalsy(currentValue).set(docId, rxDocument);\n } else {\n if (ensureNotFalsy(currentValue).has(docId)) {\n resultHasChanged = true;\n ensureNotFalsy(currentValue).delete(docId);\n }\n }\n });\n\n // nothing happened that affects the result -> do not emit\n if (!resultHasChanged && firstEmitDone) {\n return false as any;\n }\n }\n firstEmitDone = true;\n return currentValue;\n });\n return queue;\n }),\n filter(x => !!x),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * sync with a CouchDB endpoint\n */\n syncCouchDB(_syncOptions: SyncOptions): RxCouchDBReplicationState {\n throw pluginMissing('replication');\n }\n\n /**\n * sync with a GraphQL endpoint\n */\n syncGraphQL(_options: SyncOptionsGraphQL): RxGraphQLReplicationState {\n throw pluginMissing('replication-graphql');\n }\n\n syncCouchDBNew(_syncOptions: SyncOptionsCouchDBNew): RxCouchDBNewReplicationState {\n throw pluginMissing('replication-couchdb-new');\n }\n\n syncP2P(_syncOptions: SyncOptionsP2P): RxP2PReplicationPool {\n throw pluginMissing('replication-p2p');\n }\n syncFirestore(_syncOptions: SyncOptionsFirestore): RxFirestoreReplicationState {\n throw pluginMissing('replication-firestore');\n }\n\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _atomicUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.atomicUpdate((_innerDoc: RxDocumentData) => {\n return json;\n })\n .then(() => nextTick())\n .then(() => {\n return doc;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _atomicUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docFromCache = rxCollection._docCache.get(primary);\n if (docFromCache) {\n return Promise.resolve({\n doc: docFromCache,\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;;;;;;;;AAAA;AAOA;AAeA;AAKA;AAIA;AAOA;AAGA;AAKA;AAIA;AAgEA;AAGA;AAKA;AAEA,IAAMA,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAU;AAE3C,IAAMC,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAU;AAElE,IAAIC,YAAY,GAAG,KAAK;AAAC,IAEZC,gBAAgB;EAQzB;AACJ;AACA;;EAII,0BACWC,QAAyE,EACzEC,IAAY,EACZC,MAAgC,EAChCC,uBAAwF,EASjG;IAAA,IARSC,uBAAgD,uEAAG,CAAC,CAAC;IAAA,IACrDC,mBAAmC,uEAAG,CAAC,CAAC;IAAA,IACxCC,OAAuB,uEAAG,CAAC,CAAC;IAAA,IAC5BC,WAA2B,uEAAG,CAAC,CAAC;IAAA,IAChCC,OAAY,uEAAG,CAAC,CAAC;IAAA,IACjBC,sBAAgD,uEAAGC,yCAA6B;IAAA,IAChFC,OAAuB,0EAAG,CAAC,CAAC;IAAA,IAC5BC,eAAkD,0EAAGC,2CAAsB;IAAA,KAf/EC,eAAe,GAAoE,CAAC,CAAC;IAAA,KAC5EC,QAAQ,GAAuC,IAAIC,GAAG,EAAE;IAAA,KAmCjEC,mBAAmB,GAA8B,IAAIC,GAAG,EAAE;IAAA,KAE1DC,MAAM,GAAY,KAAK;IAAA,KAC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8B,UAAU,CAAC;UAAA;QAC5C,CAAC,CAAC;MACN,CAAC,CAAC;MAEN,IAAIpG,GAAG,GAAGxE,0BAAoB;MAC9B,IAAIyL,WAAW,IAAIb,UAAU,CAAClP,MAAM,CAAC2Q,OAAO,KAAK,CAAC,EAAE;QAChD7H,GAAG,GAAGoG,UAAU,CAACtK,cAAc,EAAE;MACrC;MACA,OAAOkE,GAAG;IACd,CAAC,CAAC,CACD3E,IAAI,CAAC,YAAM;MACR,IAAAmM,qBAAc,EAAC,oBAAoB,EAAE;QACjCpB,UAAU,EAAVA,UAAU;QACV0B,OAAO,EAAE;UACL7Q,IAAI,EAAJA,IAAI;UACJC,MAAM,EAANA,MAAM;UACNY,eAAe,EAAfA,eAAe;UACfV,uBAAuB,EAAvBA,uBAAuB;UACvBC,mBAAmB,EAAnBA,mBAAmB;UACnBC,OAAO,EAAPA,OAAO;UACPC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA,OAAO;UACPC,sBAAsB,EAAtBA,sBAAsB;UACtByP,cAAc,EAAdA,cAAc;UACdvP,OAAO,EAAPA;QACJ;MACJ,CAAC,CAAC;MACF,OAAOyO,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,SAIM,CAAC,UAAA2B,GAAG,EAAI;MACV,OAAOjQ,eAAe,CAAC4N,KAAK,EAAE,CACzBrK,IAAI,CAAC;QAAA,OAAM+C,OAAO,CAAC4J,MAAM,CAACD,GAAG,CAAC;MAAA,EAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAASE,cAAc,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYnR,gBAAgB;AAC1C"} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","defaultCacheReplacementPolicy","statics","conflictHandler","defaultConflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","createQueryCache","$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","eventBulks$","pipe","filter","changeEventBulk","collectionName","mergeMap","events","createChangeEventBuffer","DocumentCache","cE","isLocal","docData","createNewRxDocument","storageToken","databaseStorageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","map","ev","storageChangeEventToRxChangeEvent","databaseToken","token","checkpoint","context","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","migrationNeeded","pluginMissing","getDataMigrator","migrate","batchSize","migratePromise","insert","json","useJson","fillObjectDataBeforeInsert","bulkInsert","writeResult","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","hasHooks","Promise","all","doc","docs","docsMap","insertRows","set","Object","assign","_attachments","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_deleted","row","document","bulkWrite","results","successDocData","values","rxDocuments","writtenDocData","getCachedRxDocument","get","primary","bulkRemove","ids","findByIds","exec","rxDocumentMap","Array","from","forEach","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","previous","successIds","keys","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","newRxError","ret","slice","status","collection","writeError","documentId","writeData","docDataInDb","documentInDb","incrementalModify","newDoc","updatedDocs","concat","upsert","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","selector","limit","isArray","newRxTypeError","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","res","timeout","setTimeout","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","hashFunction","operation","colProto","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","password","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","err","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n mergeMap\n} from 'rxjs/operators';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID,\n getDefaultRxDocumentMeta,\n getDefaultRevision\n} from './plugins/utils';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error';\nimport type {\n DataMigrator\n} from './plugins/migration';\nimport {\n DocumentCache\n} from './doc-cache';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n MigrationState,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxDocumentWriteData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex\n} from './types';\n\nimport {\n RxSchema\n} from './rx-schema';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper';\nimport { defaultConflictHandler } from './replication-protocol';\nimport { IncrementalWriteQueue } from './incremental-write';\nimport { beforeDocumentUpdateWrite } from './rx-document';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: KeyFunctionMap = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n this.$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n // overwritte by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getDataMigrator(): DataMigrator {\n throw pluginMissing('migration');\n }\n migrate(batchSize: number = 10): Observable {\n return this.getDataMigrator().migrate(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getDataMigrator().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n\n // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later\n const useJson: RxDocumentWriteData = fillObjectDataBeforeInsert(this.schema, json);\n\n const writeResult = await this.bulkInsert([useJson]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, useJson[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const docsMap: Map = new Map();\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n docsMap.set((doc as any)[this.schema.primaryPath] as any, doc);\n const docData = Object.assign(doc, {\n _attachments: {},\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _deleted: false\n });\n const row: BulkWriteRow = { document: docData };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const successDocData: RxDocumentData[] = Object.values(results.success);\n const rxDocuments: any[] = successDocData\n .map((writtenDocData) => this._docCache.getCachedRxDocument(writtenDocData));\n\n if (this.hasHooks('post', 'insert')) {\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = Object.keys(results.success);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: Object.values(results.error)\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise[]> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n let ret = insertResult.success.slice(0);\n const updatedDocs = await Promise.all(\n insertResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('VD2', {\n collection: this.name,\n writeError: error\n });\n }\n const id = error.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(error.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n return newDoc;\n })\n );\n ret = ret.concat(updatedDocs);\n return ret;\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n upsert(json: Partial): Promise> {\n return this.bulkUpsert([json]).then(result => result[0]);\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\n if (typeof queryObj === 'string') {\n throw newRxError('COL5', {\n queryObj\n });\n }\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null\n > {\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n // cannot have limit on findOne queries because it will be overwritte\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery>> {\n const mangoQuery: MangoQuery = {\n selector: {\n [this.schema.primaryPath]: {\n $in: ids.slice(0)\n }\n } as any\n };\n const query = createRxQuery('findByIds', mangoQuery, this as any);\n return query as any;\n }\n\n /**\n * Export collection to a JSON friendly format.\n */\n exportJSON(): Promise>;\n exportJSON(): Promise>;\n exportJSON(): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n */\n importJSON(_exportedJSON: RxDumpCollectionAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n insertCRDT(_updateObj: CRDTEntry | CRDTEntry[]): RxDocument {\n throw pluginMissing('crdt');\n }\n\n /**\n * HOOKS\n */\n addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel = false) {\n if (typeof fun !== 'function') {\n throw newRxTypeError('COL7', {\n key,\n when\n });\n }\n\n if (!HOOKS_WHEN.includes(when)) {\n throw newRxTypeError('COL8', {\n key,\n when\n });\n }\n\n if (!HOOKS_KEYS.includes(key)) {\n throw newRxError('COL9', {\n key\n });\n }\n\n if (when === 'post' && key === 'create' && parallel === true) {\n throw newRxError('COL10', {\n when,\n key,\n parallel\n });\n }\n\n // bind this-scope to hook-function\n const boundFun = fun.bind(this);\n\n const runName = parallel ? 'parallel' : 'series';\n\n this.hooks[key] = this.hooks[key] || {};\n this.hooks[key][when] = this.hooks[key][when] || {\n series: [],\n parallel: []\n };\n this.hooks[key][when][runName].push(boundFun);\n }\n\n getHooks(when: HookWhenType, key: HookKeyType) {\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return {\n series: [],\n parallel: []\n };\n }\n return this.hooks[key][when];\n }\n\n hasHooks(when: HookWhenType, key: HookKeyType) {\n const hooks = this.getHooks(when, key);\n if (!hooks) {\n return false;\n }\n return hooks.series.length > 0 || hooks.parallel.length > 0;\n }\n\n _runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise {\n const hooks = this.getHooks(when, key);\n\n if (!hooks) {\n return PROMISE_RESOLVE_VOID;\n }\n\n // run parallel: false\n const tasks = hooks.series.map((hook: any) => () => hook(data, instance));\n return promiseSeries(tasks)\n // run parallel: true\n .then(() => Promise.all(\n hooks.parallel\n .map((hook: any) => hook(data, instance))\n ));\n }\n\n /**\n * does the same as ._runHooks() but with non-async-functions\n */\n _runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any) {\n const hooks = this.getHooks(when, key);\n if (!hooks) return;\n hooks.series.forEach((hook: any) => hook(data, instance));\n }\n\n /**\n * Returns a promise that resolves after the given time.\n * Ensures that is properly cleans up when the collection is destroyed\n * so that no running timeouts prevent the exit of the JavaScript process.\n */\n promiseWait(time: number): Promise {\n const ret = new Promise(res => {\n const timeout = setTimeout(() => {\n this.timeouts.delete(timeout);\n res();\n }, time);\n this.timeouts.add(timeout);\n });\n return ret;\n }\n\n destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * Settings destroyed = true\n * must be the first thing to do,\n * so for example the replication can directly stop\n * instead of sending requests to a closed storage.\n */\n this.destroyed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.destroy();\n }\n /**\n * First wait until the whole database is idle.\n * This ensures that the storage does not get closed\n * while some operation is running.\n * It is important that we do not intercept a running call\n * because it might lead to undefined behavior like when a doc is written\n * but the change is not added to the changes collection.\n */\n return this.database.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n .then(() => this.storageInstance.close())\n .then(() => {\n /**\n * Unsubscribing must be done AFTER the storageInstance.close()\n * Because the conflict handling is part of the subscriptions and\n * otherwise there might be open conflicts to be resolved which\n * will then stuck and never resolve.\n */\n this._subs.forEach(sub => sub.unsubscribe());\n\n delete this.database.collections[this.name];\n return runAsyncPluginHooks('postDestroyRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.destroy();\n await removeCollectionStorages(\n this.database.storage,\n this.database.internalStore,\n this.database.token,\n this.database.name,\n this.name,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAKA;AAYA;AAKA;AAIA;AAOA;AAGA;AAKA;AAIA;AA8CA;AAGA;AAMA;AACA;AACA;AAEA,IAAMA,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAU;AAE3C,IAAMC,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAU;AAElE,IAAIC,YAAY,GAAG,KAAK;AAAC,IAEZC,gBAAgB;EAQzB;AACJ;AACA;;EAKI,0BACWC,QAAyE,EACzEC,IAAY,EACZC,MAAgC,EAChCC,uBAAwF,EASjG;IAAA,IARSC,uBAAgD,uEAAG,CAAC,CAAC;IAAA,IACrDC,mBAAmC,uEAAG,CAAC,CAAC;IAAA,IACxCC,OAAuB,uEAAG,CAAC,CAAC;IAAA,IAC5BC,WAA2B,uEAAG,CAAC,CAAC;IAAA,IAChCC,OAAY,uEAAG,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MAAM,CAACsP,OAAO,KAAK,CAAC,EAAE;QAChDlG,GAAG,GAAGG,UAAU,CAACrE,cAAc,EAAE;MACrC;MACA,OAAOkE,GAAG;IACd,CAAC,CAAC,CACD3E,IAAI,CAAC,YAAM;MACR,IAAAwK,qBAAc,EAAC,oBAAoB,EAAE;QACjC1F,UAAU,EAAVA,UAAU;QACVgG,OAAO,EAAE;UACLxP,IAAI,EAAJA,IAAI;UACJC,MAAM,EAANA,MAAM;UACNY,eAAe,EAAfA,eAAe;UACfV,uBAAuB,EAAvBA,uBAAuB;UACvBC,mBAAmB,EAAnBA,mBAAmB;UACnBC,OAAO,EAAPA,OAAO;UACPC,WAAW,EAAXA,WAAW;UACXC,OAAO,EAAPA,OAAO;UACPC,sBAAsB,EAAtBA,sBAAsB;UACtBoO,cAAc,EAAdA,cAAc;UACdlO,OAAO,EAAPA;QACJ;MACJ,CAAC,CAAC;MACF,OAAO8I,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,SAIM,CAAC,UAAAiG,GAAG,EAAI;MACV,OAAO5O,eAAe,CAACyM,KAAK,EAAE,CACzB5I,IAAI,CAAC;QAAA,OAAM2B,OAAO,CAACqJ,MAAM,CAACD,GAAG,CAAC;MAAA,EAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAASE,cAAc,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAY9P,gBAAgB;AAC1C"} \ No newline at end of file diff --git a/dist/lib/rx-database-internal-store.js b/dist/lib/rx-database-internal-store.js index 28541d8cba4..9159bbe0bed 100644 --- a/dist/lib/rx-database-internal-store.js +++ b/dist/lib/rx-database-internal-store.js @@ -1,319 +1,21 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.STORAGE_TOKEN_DOCUMENT_KEY = exports.STORAGE_TOKEN_DOCUMENT_ID = exports.INTERNAL_STORE_SCHEMA_TITLE = exports.INTERNAL_STORE_SCHEMA = exports.INTERNAL_CONTEXT_STORAGE_TOKEN = exports.INTERNAL_CONTEXT_COLLECTION = void 0; exports._collectionNamePrimary = _collectionNamePrimary; -exports.getAllCollectionDocuments = exports.ensureStorageTokenDocumentExists = exports.addConnectedStorageToCollection = void 0; +exports.addConnectedStorageToCollection = addConnectedStorageToCollection; +exports.ensureStorageTokenDocumentExists = ensureStorageTokenDocumentExists; +exports.getAllCollectionDocuments = getAllCollectionDocuments; exports.getPrimaryKeyOfInternalDocument = getPrimaryKeyOfInternalDocument; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxError = require("./rx-error"); var _rxSchemaHelper = require("./rx-schema-helper"); var _rxStorageHelper = require("./rx-storage-helper"); -var _util = require("./util"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -var addConnectedStorageToCollection = function addConnectedStorageToCollection(collection, storageCollectionName, schema) { - try { - var _exit = false; - var collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema); - var collectionDocId = getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION); - return Promise.resolve(_for(function () { - return !_exit; - }, void 0, function () { - return Promise.resolve((0, _rxStorageHelper.getSingleDocument)(collection.database.internalStore, collectionDocId)).then(function (collectionDoc) { - var saveData = (0, _util.clone)((0, _util.ensureNotFalsy)(collectionDoc)); - /** - * Add array if not exist for backwards compatibility - * TODO remove this in 2023 - */ - if (!saveData.data.connectedStorages) { - saveData.data.connectedStorages = []; - } - - // do nothing if already in array - var alreadyThere = saveData.data.connectedStorages.find(function (row) { - return row.collectionName === storageCollectionName && row.schema.version === schema.version; - }); - if (alreadyThere) { - _exit = true; - return; - } - - // otherwise add to array and save - saveData.data.connectedStorages.push({ - collectionName: storageCollectionName, - schema: schema - }); - return _catch(function () { - return Promise.resolve((0, _rxStorageHelper.writeSingle)(collection.database.internalStore, { - previous: (0, _util.ensureNotFalsy)(collectionDoc), - document: saveData - }, 'add-connected-storage-to-collection')).then(function () {}); - }, function (err) { - if (!(0, _rxError.isBulkWriteConflictError)(err)) { - throw err; - } - }); - }); - })); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * returns the primary for a given collection-data - * used in the internal store of a RxDatabase - */ -exports.addConnectedStorageToCollection = addConnectedStorageToCollection; -var ensureStorageTokenDocumentExists = function ensureStorageTokenDocumentExists(rxDatabase) { - try { - /** - * To have less read-write cycles, - * we just try to insert a new document - * and only fetch the existing one if a conflict happened. - */ - var storageToken = (0, _util.randomCouchString)(10); - var passwordHash = rxDatabase.password ? (0, _util.fastUnsecureHash)(rxDatabase.password) : undefined; - var docData = { - id: STORAGE_TOKEN_DOCUMENT_ID, - context: INTERNAL_CONTEXT_STORAGE_TOKEN, - key: STORAGE_TOKEN_DOCUMENT_KEY, - data: { - token: storageToken, - /** - * We add the instance token here - * to be able to detect if a given RxDatabase instance - * is the first instance that was ever created - * or if databases have existed earlier on that storage - * with the same database name. - */ - instanceToken: rxDatabase.token, - passwordHash: passwordHash - }, - _deleted: false, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }; - return Promise.resolve(rxDatabase.internalStore.bulkWrite([{ - document: docData - }], 'internal-add-storage-token')).then(function (writeResult) { - if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) { - return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]; - } - - /** - * If we get a 409 error, - * it means another instance already inserted the storage token. - * So we get that token from the database and return that one. - */ - var error = (0, _util.ensureNotFalsy)(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]); - if (error.isError && error.status === 409) { - var conflictError = error; - if (passwordHash && passwordHash !== (0, _util.ensureNotFalsy)(conflictError.documentInDb).data.passwordHash) { - throw (0, _rxError.newRxError)('DB1', { - passwordHash: passwordHash, - existingPasswordHash: (0, _util.ensureNotFalsy)(conflictError.documentInDb).data.passwordHash - }); - } - var storageTokenDocInDb = conflictError.documentInDb; - return (0, _util.ensureNotFalsy)(storageTokenDocInDb); - } - throw error; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.ensureStorageTokenDocumentExists = ensureStorageTokenDocumentExists; -/** - * Returns all internal documents - * with context 'collection' - */ -var getAllCollectionDocuments = function getAllCollectionDocuments(storageStatics, storageInstance) { - try { - var getAllQueryPrepared = storageStatics.prepareQuery(storageInstance.schema, { - selector: { - context: INTERNAL_CONTEXT_COLLECTION - }, - sort: [{ - id: 'asc' - }], - skip: 0 - }); - return Promise.resolve(storageInstance.query(getAllQueryPrepared)).then(function (queryResult) { - var allDocs = queryResult.documents; - return allDocs; - }); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * to not confuse multiInstance-messages with other databases that have the same - * name and adapter, but do not share state with this one (for example in-memory-instances), - * we set a storage-token and use it in the broadcast-channel - */ -exports.getAllCollectionDocuments = getAllCollectionDocuments; +var _utils = require("./plugins/utils"); var INTERNAL_CONTEXT_COLLECTION = 'collection'; exports.INTERNAL_CONTEXT_COLLECTION = INTERNAL_CONTEXT_COLLECTION; var INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token'; @@ -377,10 +79,209 @@ function getPrimaryKeyOfInternalDocument(key, context) { context: context }); } + +/** + * Returns all internal documents + * with context 'collection' + */ +function getAllCollectionDocuments(_x, _x2) { + return _getAllCollectionDocuments.apply(this, arguments); +} +/** + * to not confuse multiInstance-messages with other databases that have the same + * name and adapter, but do not share state with this one (for example in-memory-instances), + * we set a storage-token and use it in the broadcast-channel + */ +function _getAllCollectionDocuments() { + _getAllCollectionDocuments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageStatics, storageInstance) { + var getAllQueryPrepared, queryResult, allDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + getAllQueryPrepared = storageStatics.prepareQuery(storageInstance.schema, { + selector: { + context: INTERNAL_CONTEXT_COLLECTION + }, + sort: [{ + id: 'asc' + }], + skip: 0 + }); + _context.next = 3; + return storageInstance.query(getAllQueryPrepared); + case 3: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getAllCollectionDocuments.apply(this, arguments); +} var STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken'; exports.STORAGE_TOKEN_DOCUMENT_KEY = STORAGE_TOKEN_DOCUMENT_KEY; var STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(STORAGE_TOKEN_DOCUMENT_KEY, INTERNAL_CONTEXT_STORAGE_TOKEN); exports.STORAGE_TOKEN_DOCUMENT_ID = STORAGE_TOKEN_DOCUMENT_ID; +function ensureStorageTokenDocumentExists(_x3) { + return _ensureStorageTokenDocumentExists.apply(this, arguments); +} +function _ensureStorageTokenDocumentExists() { + _ensureStorageTokenDocumentExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxDatabase) { + var storageToken, passwordHash, docData, writeResult, error, conflictError, storageTokenDocInDb; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + /** + * To have less read-write cycles, + * we just try to insert a new document + * and only fetch the existing one if a conflict happened. + */ + storageToken = (0, _utils.randomCouchString)(10); + passwordHash = rxDatabase.password ? (0, _utils.fastUnsecureHash)(rxDatabase.password) : undefined; + docData = { + id: STORAGE_TOKEN_DOCUMENT_ID, + context: INTERNAL_CONTEXT_STORAGE_TOKEN, + key: STORAGE_TOKEN_DOCUMENT_KEY, + data: { + token: storageToken, + /** + * We add the instance token here + * to be able to detect if a given RxDatabase instance + * is the first instance that was ever created + * or if databases have existed earlier on that storage + * with the same database name. + */ + instanceToken: rxDatabase.token, + passwordHash: passwordHash + }, + _deleted: false, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }; + _context2.next = 5; + return rxDatabase.internalStore.bulkWrite([{ + document: docData + }], 'internal-add-storage-token'); + case 5: + writeResult = _context2.sent; + if (!writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) { + _context2.next = 8; + break; + } + return _context2.abrupt("return", writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]); + case 8: + /** + * If we get a 409 error, + * it means another instance already inserted the storage token. + * So we get that token from the database and return that one. + */ + error = (0, _utils.ensureNotFalsy)(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]); + if (!(error.isError && error.status === 409)) { + _context2.next = 15; + break; + } + conflictError = error; + if (!(passwordHash && passwordHash !== conflictError.documentInDb.data.passwordHash)) { + _context2.next = 13; + break; + } + throw (0, _rxError.newRxError)('DB1', { + passwordHash: passwordHash, + existingPasswordHash: conflictError.documentInDb.data.passwordHash + }); + case 13: + storageTokenDocInDb = conflictError.documentInDb; + return _context2.abrupt("return", (0, _utils.ensureNotFalsy)(storageTokenDocInDb)); + case 15: + throw error; + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _ensureStorageTokenDocumentExists.apply(this, arguments); +} +function addConnectedStorageToCollection(_x4, _x5, _x6) { + return _addConnectedStorageToCollection.apply(this, arguments); +} +/** + * returns the primary for a given collection-data + * used in the internal store of a RxDatabase + */ +function _addConnectedStorageToCollection() { + _addConnectedStorageToCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collection, storageCollectionName, schema) { + var collectionNameWithVersion, collectionDocId, collectionDoc, saveData, alreadyThere; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema); + collectionDocId = getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION); + case 2: + if (!true) { + _context3.next = 23; + break; + } + _context3.next = 5; + return (0, _rxStorageHelper.getSingleDocument)(collection.database.internalStore, collectionDocId); + case 5: + collectionDoc = _context3.sent; + saveData = (0, _utils.clone)((0, _utils.ensureNotFalsy)(collectionDoc)); + /** + * Add array if not exist for backwards compatibility + * TODO remove this in 2023 + */ + if (!saveData.data.connectedStorages) { + saveData.data.connectedStorages = []; + } + + // do nothing if already in array + alreadyThere = saveData.data.connectedStorages.find(function (row) { + return row.collectionName === storageCollectionName && row.schema.version === schema.version; + }); + if (!alreadyThere) { + _context3.next = 11; + break; + } + return _context3.abrupt("return"); + case 11: + // otherwise add to array and save + saveData.data.connectedStorages.push({ + collectionName: storageCollectionName, + schema: schema + }); + _context3.prev = 12; + _context3.next = 15; + return (0, _rxStorageHelper.writeSingle)(collection.database.internalStore, { + previous: (0, _utils.ensureNotFalsy)(collectionDoc), + document: saveData + }, 'add-connected-storage-to-collection'); + case 15: + _context3.next = 21; + break; + case 17: + _context3.prev = 17; + _context3.t0 = _context3["catch"](12); + if ((0, _rxError.isBulkWriteConflictError)(_context3.t0)) { + _context3.next = 21; + break; + } + throw _context3.t0; + case 21: + _context3.next = 2; + break; + case 23: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[12, 17]]); + })); + return _addConnectedStorageToCollection.apply(this, arguments); +} function _collectionNamePrimary(name, schema) { return name + '-' + schema.version; } diff --git a/dist/lib/rx-database-internal-store.js.map b/dist/lib/rx-database-internal-store.js.map index ea9c659318f..31d7429cbec 100644 --- a/dist/lib/rx-database-internal-store.js.map +++ b/dist/lib/rx-database-internal-store.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database-internal-store.js","names":["body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","addConnectedStorageToCollection","collection","storageCollectionName","schema","collectionNameWithVersion","_collectionNamePrimary","name","jsonSchema","collectionDocId","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","getSingleDocument","database","internalStore","collectionDoc","saveData","clone","ensureNotFalsy","data","connectedStorages","alreadyThere","find","row","collectionName","version","push","writeSingle","previous","document","err","isBulkWriteConflictError","ensureStorageTokenDocumentExists","rxDatabase","storageToken","randomCouchString","passwordHash","password","fastUnsecureHash","undefined","docData","id","STORAGE_TOKEN_DOCUMENT_ID","context","INTERNAL_CONTEXT_STORAGE_TOKEN","key","STORAGE_TOKEN_DOCUMENT_KEY","token","instanceToken","_deleted","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","bulkWrite","writeResult","success","error","isError","status","conflictError","documentInDb","newRxError","existingPasswordHash","storageTokenDocInDb","getAllCollectionDocuments","storageStatics","storageInstance","getAllQueryPrepared","prepareQuery","selector","sort","skip","query","queryResult","allDocs","documents","INTERNAL_STORE_SCHEMA_TITLE","INTERNAL_STORE_SCHEMA","fillWithDefaultSettings","title","primaryKey","fields","separator","type","properties","maxLength","additionalProperties","indexes","required","sharding","shards","mode","getComposedPrimaryKeyOfDocumentData"],"sources":["../../src/rx-database-internal-store.ts"],"sourcesContent":["import { isBulkWriteConflictError, newRxError } from './rx-error';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from './rx-schema-helper';\nimport { getSingleDocument, writeSingle } from './rx-storage-helper';\nimport type {\n CollectionsOfDatabase,\n InternalStoreCollectionDocType,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorageBulkWriteError,\n RxStorageInstance,\n RxStorageStatics\n} from './types';\nimport {\n clone,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n randomCouchString\n} from './util';\n\nexport const INTERNAL_CONTEXT_COLLECTION = 'collection';\nexport const INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token';\n\n/**\n * Do not change the title,\n * we have to flag the internal schema so that\n * some RxStorage implementations are able\n * to detect if the created RxStorageInstance\n * is from the internals or not,\n * to do some optimizations in some cases.\n */\nexport const INTERNAL_STORE_SCHEMA_TITLE = 'RxInternalDocument';\n\nexport const INTERNAL_STORE_SCHEMA: RxJsonSchema>> = fillWithDefaultSettings({\n version: 0,\n title: INTERNAL_STORE_SCHEMA_TITLE,\n primaryKey: {\n key: 'id',\n fields: [\n 'context',\n 'key'\n ],\n separator: '|'\n },\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 200\n },\n key: {\n type: 'string'\n },\n context: {\n type: 'string',\n enum: [\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_CONTEXT_STORAGE_TOKEN,\n 'OTHER'\n ]\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n indexes: [],\n required: [\n 'key',\n 'context',\n 'data'\n ],\n additionalProperties: false,\n /**\n * If the sharding plugin is used,\n * it must not shard on the internal RxStorageInstance\n * because that one anyway has only a small amount of documents\n * and also its creation is in the hot path of the initial page load,\n * so we should spend less time creating multiple RxStorageInstances.\n */\n sharding: {\n shards: 1,\n mode: 'collection'\n }\n});\n\n\nexport function getPrimaryKeyOfInternalDocument(\n key: string,\n context: string\n): string {\n return getComposedPrimaryKeyOfDocumentData(\n INTERNAL_STORE_SCHEMA,\n {\n key,\n context\n }\n );\n}\n\n/**\n * Returns all internal documents\n * with context 'collection'\n */\nexport async function getAllCollectionDocuments(\n storageStatics: RxStorageStatics,\n storageInstance: RxStorageInstance, any, any>\n): Promise[]> {\n const getAllQueryPrepared = storageStatics.prepareQuery(\n storageInstance.schema,\n {\n selector: {\n context: INTERNAL_CONTEXT_COLLECTION\n },\n sort: [{ id: 'asc' }],\n skip: 0\n }\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n}\n\n/**\n * to not confuse multiInstance-messages with other databases that have the same\n * name and adapter, but do not share state with this one (for example in-memory-instances),\n * we set a storage-token and use it in the broadcast-channel\n */\nexport const STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken';\n\nexport const STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(\n STORAGE_TOKEN_DOCUMENT_KEY,\n INTERNAL_CONTEXT_STORAGE_TOKEN\n);\n\nexport async function ensureStorageTokenDocumentExists(\n rxDatabase: RxDatabase\n): Promise> {\n\n /**\n * To have less read-write cycles,\n * we just try to insert a new document\n * and only fetch the existing one if a conflict happened.\n */\n const storageToken = randomCouchString(10);\n\n const passwordHash = rxDatabase.password ? fastUnsecureHash(rxDatabase.password) : undefined;\n\n const docData: RxDocumentData = {\n id: STORAGE_TOKEN_DOCUMENT_ID,\n context: INTERNAL_CONTEXT_STORAGE_TOKEN,\n key: STORAGE_TOKEN_DOCUMENT_KEY,\n data: {\n token: storageToken,\n /**\n * We add the instance token here\n * to be able to detect if a given RxDatabase instance\n * is the first instance that was ever created\n * or if databases have existed earlier on that storage\n * with the same database name.\n */\n instanceToken: rxDatabase.token,\n passwordHash\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n const writeResult = await rxDatabase.internalStore.bulkWrite(\n [{ document: docData }],\n 'internal-add-storage-token'\n );\n if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) {\n return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID];\n }\n\n /**\n * If we get a 409 error,\n * it means another instance already inserted the storage token.\n * So we get that token from the database and return that one.\n */\n const error = ensureNotFalsy(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]);\n if (\n error.isError &&\n (error as RxStorageBulkWriteError).status === 409\n ) {\n const conflictError = (error as RxStorageBulkWriteError);\n\n\n if (\n passwordHash &&\n passwordHash !== ensureNotFalsy(conflictError.documentInDb).data.passwordHash\n ) {\n throw newRxError('DB1', {\n passwordHash,\n existingPasswordHash: ensureNotFalsy(conflictError.documentInDb).data.passwordHash\n });\n }\n\n const storageTokenDocInDb = conflictError.documentInDb;\n return ensureNotFalsy(storageTokenDocInDb);\n }\n throw error;\n}\n\n\n\n\n\nexport async function addConnectedStorageToCollection(\n collection: RxCollection,\n storageCollectionName: string,\n schema: RxJsonSchema\n) {\n const collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema);\n const collectionDocId = getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n );\n\n while (true) {\n const collectionDoc = await getSingleDocument(\n collection.database.internalStore,\n collectionDocId\n );\n const saveData: RxDocumentData = clone(ensureNotFalsy(collectionDoc));\n /**\n * Add array if not exist for backwards compatibility\n * TODO remove this in 2023\n */\n if (!saveData.data.connectedStorages) {\n saveData.data.connectedStorages = [];\n }\n\n // do nothing if already in array\n const alreadyThere = saveData.data.connectedStorages\n .find(row => row.collectionName === storageCollectionName && row.schema.version === schema.version);\n if (alreadyThere) {\n return;\n }\n\n // otherwise add to array and save\n saveData.data.connectedStorages.push({\n collectionName: storageCollectionName,\n schema\n });\n try {\n await writeSingle(\n collection.database.internalStore,\n {\n previous: ensureNotFalsy(collectionDoc),\n document: saveData\n },\n 'add-connected-storage-to-collection'\n );\n } catch (err) {\n if (!isBulkWriteConflictError(err)) {\n throw err;\n }\n // retry on conflict\n }\n }\n}\n\n\n/**\n * returns the primary for a given collection-data\n * used in the internal store of a RxDatabase\n */\nexport function _collectionNamePrimary(name: string, schema: RxJsonSchema) {\n return name + '-' + schema.version;\n}\n"],"mappings":";;;;;;;;;AAAA;AACA;AAIA;AAcA;AA+hBO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AArhBO,iBAAiBG,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ,IAAID,KAAK,iBAAiB,EAAE;MAC3B,IAAIA,KAAK,CAACC,CAAC,EAAE;QACZ,IAAIF,KAAK,GAAG,CAAC,EAAE;UACdA,KAAK,GAAGC,KAAK,CAACC,CAAC;QAChB;QACAD,KAAK,GAAGA,KAAK,CAACE,CAAC;MAChB,CAAC,MAAM;QACNF,KAAK,CAACG,CAAC,GAAG,QAAQC,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC;QACzC;MACD;IACD;IACA,IAAIC,KAAK,IAAIA,KAAK,CAACH,IAAI,EAAE;MACxBG,KAAK,CAACH,IAAI,CAAC,QAAQO,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAEC,KAAK,CAAC,EAAE,QAAQK,IAAI,CAAC,IAAI,EAAEN,IAAI,EAAE,CAAC,CAAC,CAAC;MACxE;IACD;IACAA,IAAI,CAACG,CAAC,GAAGF,KAAK;IACdD,IAAI,CAAC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K,EACL,SAAS,EACT,MAAM,CACT;EACDF,oBAAoB,EAAE,KAAK;EAC3B;AACJ;AACA;AACA;AACA;AACA;AACA;EACIG,QAAQ,EAAE;IACNC,MAAM,EAAE,CAAC;IACTC,IAAI,EAAE;EACV;AACJ,CAAC,CAAC;AAAC;AAGI,SAASnF,+BAA+B,CAC3CmC,GAAW,EACXF,OAAe,EACT;EACN,OAAO,IAAAmD,mDAAmC,EACtCf,qBAAqB,EACrB;IACIlC,GAAG,EAAHA,GAAG;IACHF,OAAO,EAAPA;EACJ,CAAC,CACJ;AACL;AA8BO,IAAMG,0BAA0B,GAAG,cAAc;AAAC;AAElD,IAAMJ,yBAAyB,GAAGhC,+BAA+B,CACpEoC,0BAA0B,EAC1BF,8BAA8B,CACjC;AAAC;AA0IK,SAAStC,sBAAsB,CAACC,IAAY,EAAEH,MAAyB,EAAE;EAC5E,OAAOG,IAAI,GAAG,GAAG,GAAGH,MAAM,CAACqB,OAAO;AACtC"} \ No newline at end of file +{"version":3,"file":"rx-database-internal-store.js","names":["INTERNAL_CONTEXT_COLLECTION","INTERNAL_CONTEXT_STORAGE_TOKEN","INTERNAL_STORE_SCHEMA_TITLE","INTERNAL_STORE_SCHEMA","fillWithDefaultSettings","version","title","primaryKey","key","fields","separator","type","properties","id","maxLength","context","data","additionalProperties","indexes","required","sharding","shards","mode","getPrimaryKeyOfInternalDocument","getComposedPrimaryKeyOfDocumentData","getAllCollectionDocuments","storageStatics","storageInstance","getAllQueryPrepared","prepareQuery","schema","selector","sort","skip","query","queryResult","allDocs","documents","STORAGE_TOKEN_DOCUMENT_KEY","STORAGE_TOKEN_DOCUMENT_ID","ensureStorageTokenDocumentExists","rxDatabase","storageToken","randomCouchString","passwordHash","password","fastUnsecureHash","undefined","docData","token","instanceToken","_deleted","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","internalStore","bulkWrite","document","writeResult","success","error","ensureNotFalsy","isError","status","conflictError","documentInDb","newRxError","existingPasswordHash","storageTokenDocInDb","addConnectedStorageToCollection","collection","storageCollectionName","collectionNameWithVersion","_collectionNamePrimary","name","jsonSchema","collectionDocId","getSingleDocument","database","collectionDoc","saveData","clone","connectedStorages","alreadyThere","find","row","collectionName","push","writeSingle","previous","isBulkWriteConflictError"],"sources":["../../src/rx-database-internal-store.ts"],"sourcesContent":["import {\n isBulkWriteConflictError,\n newRxError\n} from './rx-error';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData\n} from './rx-schema-helper';\nimport { getSingleDocument, writeSingle } from './rx-storage-helper';\nimport type {\n CollectionsOfDatabase,\n InternalStoreCollectionDocType,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageInstance,\n RxStorageStatics,\n RxStorageWriteErrorConflict\n} from './types';\nimport {\n clone,\n ensureNotFalsy,\n fastUnsecureHash,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n randomCouchString\n} from './plugins/utils';\n\nexport const INTERNAL_CONTEXT_COLLECTION = 'collection';\nexport const INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token';\n\n/**\n * Do not change the title,\n * we have to flag the internal schema so that\n * some RxStorage implementations are able\n * to detect if the created RxStorageInstance\n * is from the internals or not,\n * to do some optimizations in some cases.\n */\nexport const INTERNAL_STORE_SCHEMA_TITLE = 'RxInternalDocument';\n\nexport const INTERNAL_STORE_SCHEMA: RxJsonSchema>> = fillWithDefaultSettings({\n version: 0,\n title: INTERNAL_STORE_SCHEMA_TITLE,\n primaryKey: {\n key: 'id',\n fields: [\n 'context',\n 'key'\n ],\n separator: '|'\n },\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 200\n },\n key: {\n type: 'string'\n },\n context: {\n type: 'string',\n enum: [\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_CONTEXT_STORAGE_TOKEN,\n 'OTHER'\n ]\n },\n data: {\n type: 'object',\n additionalProperties: true\n }\n },\n indexes: [],\n required: [\n 'key',\n 'context',\n 'data'\n ],\n additionalProperties: false,\n /**\n * If the sharding plugin is used,\n * it must not shard on the internal RxStorageInstance\n * because that one anyway has only a small amount of documents\n * and also its creation is in the hot path of the initial page load,\n * so we should spend less time creating multiple RxStorageInstances.\n */\n sharding: {\n shards: 1,\n mode: 'collection'\n }\n});\n\n\nexport function getPrimaryKeyOfInternalDocument(\n key: string,\n context: string\n): string {\n return getComposedPrimaryKeyOfDocumentData(\n INTERNAL_STORE_SCHEMA,\n {\n key,\n context\n }\n );\n}\n\n/**\n * Returns all internal documents\n * with context 'collection'\n */\nexport async function getAllCollectionDocuments(\n storageStatics: RxStorageStatics,\n storageInstance: RxStorageInstance, any, any>\n): Promise[]> {\n const getAllQueryPrepared = storageStatics.prepareQuery(\n storageInstance.schema,\n {\n selector: {\n context: INTERNAL_CONTEXT_COLLECTION\n },\n sort: [{ id: 'asc' }],\n skip: 0\n }\n );\n const queryResult = await storageInstance.query(getAllQueryPrepared);\n const allDocs = queryResult.documents;\n return allDocs;\n}\n\n/**\n * to not confuse multiInstance-messages with other databases that have the same\n * name and adapter, but do not share state with this one (for example in-memory-instances),\n * we set a storage-token and use it in the broadcast-channel\n */\nexport const STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken';\n\nexport const STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(\n STORAGE_TOKEN_DOCUMENT_KEY,\n INTERNAL_CONTEXT_STORAGE_TOKEN\n);\n\nexport async function ensureStorageTokenDocumentExists(\n rxDatabase: RxDatabase\n): Promise> {\n\n /**\n * To have less read-write cycles,\n * we just try to insert a new document\n * and only fetch the existing one if a conflict happened.\n */\n const storageToken = randomCouchString(10);\n\n const passwordHash = rxDatabase.password ? fastUnsecureHash(rxDatabase.password) : undefined;\n\n const docData: RxDocumentData = {\n id: STORAGE_TOKEN_DOCUMENT_ID,\n context: INTERNAL_CONTEXT_STORAGE_TOKEN,\n key: STORAGE_TOKEN_DOCUMENT_KEY,\n data: {\n token: storageToken,\n /**\n * We add the instance token here\n * to be able to detect if a given RxDatabase instance\n * is the first instance that was ever created\n * or if databases have existed earlier on that storage\n * with the same database name.\n */\n instanceToken: rxDatabase.token,\n passwordHash\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n\n const writeResult = await rxDatabase.internalStore.bulkWrite(\n [{ document: docData }],\n 'internal-add-storage-token'\n );\n if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) {\n return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID];\n }\n\n /**\n * If we get a 409 error,\n * it means another instance already inserted the storage token.\n * So we get that token from the database and return that one.\n */\n const error = ensureNotFalsy(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]);\n if (\n error.isError &&\n (error as RxStorageWriteError).status === 409\n ) {\n const conflictError = (error as RxStorageWriteErrorConflict);\n\n\n if (\n passwordHash &&\n passwordHash !== conflictError.documentInDb.data.passwordHash\n ) {\n throw newRxError('DB1', {\n passwordHash,\n existingPasswordHash: conflictError.documentInDb.data.passwordHash\n });\n }\n\n const storageTokenDocInDb = conflictError.documentInDb;\n return ensureNotFalsy(storageTokenDocInDb);\n }\n throw error;\n}\n\n\n\n\n\nexport async function addConnectedStorageToCollection(\n collection: RxCollection,\n storageCollectionName: string,\n schema: RxJsonSchema\n) {\n const collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema);\n const collectionDocId = getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n );\n\n while (true) {\n const collectionDoc = await getSingleDocument(\n collection.database.internalStore,\n collectionDocId\n );\n const saveData: RxDocumentData = clone(ensureNotFalsy(collectionDoc));\n /**\n * Add array if not exist for backwards compatibility\n * TODO remove this in 2023\n */\n if (!saveData.data.connectedStorages) {\n saveData.data.connectedStorages = [];\n }\n\n // do nothing if already in array\n const alreadyThere = saveData.data.connectedStorages\n .find(row => row.collectionName === storageCollectionName && row.schema.version === schema.version);\n if (alreadyThere) {\n return;\n }\n\n // otherwise add to array and save\n saveData.data.connectedStorages.push({\n collectionName: storageCollectionName,\n schema\n });\n try {\n await writeSingle(\n collection.database.internalStore,\n {\n previous: ensureNotFalsy(collectionDoc),\n document: saveData\n },\n 'add-connected-storage-to-collection'\n );\n } catch (err) {\n if (!isBulkWriteConflictError(err)) {\n throw err;\n }\n // retry on conflict\n }\n }\n}\n\n\n/**\n * returns the primary for a given collection-data\n * used in the internal store of a RxDatabase\n */\nexport function _collectionNamePrimary(name: string, schema: RxJsonSchema) {\n return name + '-' + schema.version;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAIA;AAIA;AAeA;AASO,IAAMA,2BAA2B,GAAG,YAAY;AAAC;AACjD,IAAMC,8BAA8B,GAAG,eAAe;;AAE7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAPA;AAQO,IAAMC,2BAA2B,GAAG,oBAAoB;AAAC;AAEzD,IAAMC,qBAA8E,GAAG,IAAAC,uCAAuB,EAAC;EAClHC,OAAO,EAAE,CAAC;EACVC,KAAK,EAAEJ,2BAA2B;EAClCK,UAAU,EAAE;IACRC,GAAG,EAAE,IAAI;IACTC,MAAM,EAAE,CACJ,SAAS,EACT,KAAK,CACR;IACDC,SAAS,EAAE;EACf,CAAC;EACDC,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRC,EAAE,EAAE;MACAF,IAAI,EAAE,QAAQ;MACdG,SAAS,EAAE;IACf,CAAC;IACDN,GAAG,EAAE;MACDG,IAAI,EAAE;IACV,CAAC;IACDI,OAAO,EAAE;MACLJ,IAAI,EAAE,QAAQ;MACd,QAAM,CACFX,2BAA2B,EAC3BC,8BAA8B,EAC9B,OAAO;IAEf,CAAC;IACDe,IAAI,EAAE;MACFL,IAAI,EAAE,QAAQ;MACdM,oBAAoB,EAAE;IAC1B;EACJ,CAAC;EACDC,OAAO,EAAE,EAAE;EACXC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AAA;UAIhB;UACAH,QAAQ,CAAClE,IAAI,CAACoE,iBAAiB,CAACK,IAAI,CAAC;YACjCD,cAAc,EAAEf,qBAAqB;YACrC3C,MAAM,EAANA;UACJ,CAAC,CAAC;UAAC;UAAA;UAAA,OAEO,IAAA4D,4BAAW,EACblB,UAAU,CAACQ,QAAQ,CAACvB,aAAa,EACjC;YACIkC,QAAQ,EAAE,IAAA5B,qBAAc,EAACkB,aAAa,CAAC;YACvCtB,QAAQ,EAAEuB;UACd,CAAC,EACD,qCAAqC,CACxC;QAAA;UAAA;UAAA;QAAA;UAAA;UAAA;UAAA,IAEI,IAAAU,iCAAwB,eAAK;YAAA;YAAA;UAAA;UAAA;QAAA;UAAA;UAAA;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAM7C;EAAA;AAAA;AAOM,SAASjB,sBAAsB,CAACC,IAAY,EAAE9C,MAAyB,EAAE;EAC5E,OAAO8C,IAAI,GAAG,GAAG,GAAG9C,MAAM,CAACzB,OAAO;AACtC"} \ No newline at end of file diff --git a/dist/lib/rx-database.js b/dist/lib/rx-database.js index 07aa3029ba0..acf5c3e78ba 100644 --- a/dist/lib/rx-database.js +++ b/dist/lib/rx-database.js @@ -6,14 +6,17 @@ Object.defineProperty(exports, "__esModule", { }); exports.RxDatabaseBase = void 0; exports.createRxDatabase = createRxDatabase; -exports.createRxDatabaseStorageInstance = void 0; +exports.createRxDatabaseStorageInstance = createRxDatabaseStorageInstance; exports.dbCount = dbCount; -exports.ensureNoStartupErrors = void 0; +exports.ensureNoStartupErrors = ensureNoStartupErrors; exports.isRxDatabase = isRxDatabase; -exports.removeRxDatabase = exports.isRxDatabaseFirstTimeInstantiated = void 0; +exports.isRxDatabaseFirstTimeInstantiated = isRxDatabaseFirstTimeInstantiated; +exports.removeRxDatabase = removeRxDatabase; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _customIdleQueue = require("custom-idle-queue"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _rxSchema = require("./rx-schema"); var _hooks = require("./hooks"); @@ -24,96 +27,6 @@ var _rxStorageHelper = require("./rx-storage-helper"); var _obliviousSet = require("oblivious-set"); var _rxDatabaseInternalStore = require("./rx-database-internal-store"); var _rxCollectionHelper = require("./rx-collection-helper"); -/** - * For better performance some tasks run async - * and are awaited later. - * But we still have to ensure that there have been no errors - * on database creation. - */ -var ensureNoStartupErrors = function ensureNoStartupErrors(rxDatabase) { - try { - return Promise.resolve(rxDatabase.storageToken).then(function () { - if (rxDatabase.startupErrors[0]) { - throw rxDatabase.startupErrors[0]; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.ensureNoStartupErrors = ensureNoStartupErrors; -/** - * Returns true if the given RxDatabase was the first - * instance that was created on the storage with this name. - * - * Can be used for some optimizations because on the first instantiation, - * we can assume that no data was written before. - */ -var isRxDatabaseFirstTimeInstantiated = function isRxDatabaseFirstTimeInstantiated(database) { - try { - return Promise.resolve(database.storageTokenDocument).then(function (tokenDoc) { - return tokenDoc.data.instanceToken === database.token; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.isRxDatabaseFirstTimeInstantiated = isRxDatabaseFirstTimeInstantiated; -/** - * Removes the database and all its known data - * with all known collections and all internal meta data. - * - * Returns the names of the removed collections. - */ -var removeRxDatabase = function removeRxDatabase(databaseName, storage) { - try { - var databaseInstanceToken = (0, _util.randomCouchString)(10); - return Promise.resolve(createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, {}, false)).then(function (dbInternalsStorageInstance) { - return Promise.resolve((0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, dbInternalsStorageInstance)).then(function (collectionDocs) { - var collectionNames = new Set(); - collectionDocs.forEach(function (doc) { - return collectionNames.add(doc.data.name); - }); - var removedCollectionNames = Array.from(collectionNames); - return Promise.resolve(Promise.all(removedCollectionNames.map(function (collectionName) { - return (0, _rxCollectionHelper.removeCollectionStorages)(storage, dbInternalsStorageInstance, databaseInstanceToken, databaseName, collectionName); - }))).then(function () { - return Promise.resolve((0, _hooks.runAsyncPluginHooks)('postRemoveRxDatabase', { - databaseName: databaseName, - storage: storage - })).then(function () { - return Promise.resolve(dbInternalsStorageInstance.remove()).then(function () { - return removedCollectionNames; - }); - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.removeRxDatabase = removeRxDatabase; -/** - * Creates the storage instances that are used internally in the database - * to store schemas and other configuration stuff. - */ -var createRxDatabaseStorageInstance = function createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, options, multiInstance, password) { - try { - return Promise.resolve(storage.createStorageInstance({ - databaseInstanceToken: databaseInstanceToken, - databaseName: databaseName, - collectionName: _rxStorageHelper.INTERNAL_STORAGE_NAME, - schema: _rxDatabaseInternalStore.INTERNAL_STORE_SCHEMA, - options: options, - multiInstance: multiInstance, - password: password - })); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createRxDatabaseStorageInstance = createRxDatabaseStorageInstance; /** * stores the used database names * so we can throw when the same database is created more then once. @@ -148,8 +61,8 @@ var RxDatabaseBase = /*#__PURE__*/function () { this.observable$ = this.eventBulks$.pipe((0, _operators.mergeMap)(function (changeEventBulk) { return changeEventBulk.events; })); - this.storageToken = _util.PROMISE_RESOLVE_FALSE; - this.storageTokenDocument = _util.PROMISE_RESOLVE_FALSE; + this.storageToken = _utils.PROMISE_RESOLVE_FALSE; + this.storageTokenDocument = _utils.PROMISE_RESOLVE_FALSE; this.emittedEventBulkIds = new _obliviousSet.ObliviousSet(60 * 1000); this.name = name; this.token = token; @@ -222,27 +135,45 @@ var RxDatabaseBase = /*#__PURE__*/function () { /** * removes the collection-doc from the internalStore */; - _proto.removeCollectionDoc = function removeCollectionDoc(name, schema) { - try { - var _this2 = this; - return Promise.resolve((0, _rxStorageHelper.getSingleDocument)(_this2.internalStore, (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)((0, _rxDatabaseInternalStore._collectionNamePrimary)(name, schema), _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION))).then(function (doc) { - if (!doc) { - throw (0, _rxError.newRxError)('SNH', { - name: name, - schema: schema - }); + _proto.removeCollectionDoc = + /*#__PURE__*/ + function () { + var _removeCollectionDoc = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(name, schema) { + var doc, writeDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _rxStorageHelper.getSingleDocument)(this.internalStore, (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)((0, _rxDatabaseInternalStore._collectionNamePrimary)(name, schema), _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION)); + case 2: + doc = _context.sent; + if (doc) { + _context.next = 5; + break; + } + throw (0, _rxError.newRxError)('SNH', { + name: name, + schema: schema + }); + case 5: + writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); + writeDoc._deleted = true; + _context.next = 9; + return this.internalStore.bulkWrite([{ + document: writeDoc, + previous: doc + }], 'rx-database-remove-collection'); + case 9: + case "end": + return _context.stop(); } - var writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); - writeDoc._deleted = true; - return Promise.resolve(_this2.internalStore.bulkWrite([{ - document: writeDoc, - previous: doc - }], 'rx-database-remove-collection')).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + }, _callee, this); + })); + function removeCollectionDoc(_x, _x2) { + return _removeCollectionDoc.apply(this, arguments); } - } + return removeCollectionDoc; + }() /** * creates multiple RxCollections at once * to be much faster by saving db txs and doing stuff in bulk-operations @@ -250,111 +181,146 @@ var RxDatabaseBase = /*#__PURE__*/function () { * So it must be as fast as possible. */ ; - _proto.addCollections = function addCollections(collectionCreators) { - try { - var _this3 = this; - var jsonSchemas = {}; - var schemas = {}; - var bulkPutDocs = []; - var useArgsByCollectionName = {}; - Object.entries(collectionCreators).forEach(function (_ref) { - var name = _ref[0], - args = _ref[1]; - var collectionName = name; - var rxJsonSchema = args.schema; - jsonSchemas[collectionName] = rxJsonSchema; - var schema = (0, _rxSchema.createRxSchema)(rxJsonSchema); - schemas[collectionName] = schema; - - // collection already exists - if (_this3.collections[name]) { - throw (0, _rxError.newRxError)('DB3', { - name: name - }); - } - var collectionNameWithVersion = (0, _rxDatabaseInternalStore._collectionNamePrimary)(name, rxJsonSchema); - var collectionDocData = { - id: (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)(collectionNameWithVersion, _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION), - key: collectionNameWithVersion, - context: _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION, - data: { - name: collectionName, - schemaHash: schema.hash, - schema: schema.jsonSchema, - version: schema.version, - connectedStorages: [] - }, - _deleted: false, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }; - bulkPutDocs.push({ - document: collectionDocData - }); - var useArgs = Object.assign({}, args, { - name: collectionName, - schema: schema, - database: _this3 - }); + _proto.addCollections = + /*#__PURE__*/ + function () { + var _addCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collectionCreators) { + var _this2 = this; + var jsonSchemas, schemas, bulkPutDocs, useArgsByCollectionName, putDocsResult, ret; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + jsonSchemas = {}; + schemas = {}; + bulkPutDocs = []; + useArgsByCollectionName = {}; + Object.entries(collectionCreators).forEach(function (_ref) { + var name = _ref[0], + args = _ref[1]; + var collectionName = name; + var rxJsonSchema = args.schema; + jsonSchemas[collectionName] = rxJsonSchema; + var schema = (0, _rxSchema.createRxSchema)(rxJsonSchema); + schemas[collectionName] = schema; - // run hooks - var hookData = (0, _util.flatClone)(args); - hookData.database = _this3; - hookData.name = name; - (0, _hooks.runPluginHooks)('preCreateRxCollection', hookData); - useArgs.conflictHandler = hookData.conflictHandler; - useArgsByCollectionName[collectionName] = useArgs; - }); - return Promise.resolve(_this3.internalStore.bulkWrite(bulkPutDocs, 'rx-database-add-collection')).then(function (putDocsResult) { - return Promise.resolve(ensureNoStartupErrors(_this3)).then(function () { - Object.entries(putDocsResult.error).forEach(function (_ref2) { - var _id = _ref2[0], - error = _ref2[1]; - var docInDb = (0, _util.ensureNotFalsy)(error.documentInDb); - var collectionName = docInDb.data.name; - var schema = schemas[collectionName]; - // collection already exists but has different schema - if (docInDb.data.schemaHash !== schema.hash) { - throw (0, _rxError.newRxError)('DB6', { - database: _this3.name, - collection: collectionName, - previousSchemaHash: docInDb.data.schemaHash, - schemaHash: schema.hash, - previousSchema: docInDb.data.schema, - schema: (0, _util.ensureNotFalsy)(jsonSchemas[collectionName]) + // collection already exists + if (_this2.collections[name]) { + throw (0, _rxError.newRxError)('DB3', { + name: name + }); + } + var collectionNameWithVersion = (0, _rxDatabaseInternalStore._collectionNamePrimary)(name, rxJsonSchema); + var collectionDocData = { + id: (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)(collectionNameWithVersion, _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION), + key: collectionNameWithVersion, + context: _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION, + data: { + name: collectionName, + schemaHash: schema.hash, + schema: schema.jsonSchema, + version: schema.version, + connectedStorages: [] + }, + _deleted: false, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }; + bulkPutDocs.push({ + document: collectionDocData }); - } - }); - var ret = {}; - return Promise.resolve(Promise.all(Object.keys(collectionCreators).map(function (collectionName) { - try { - var useArgs = useArgsByCollectionName[collectionName]; - return Promise.resolve((0, _rxCollection.createRxCollection)(useArgs)).then(function (collection) { - ret[collectionName] = collection; - - // set as getter to the database - _this3.collections[collectionName] = collection; - if (!_this3[collectionName]) { - Object.defineProperty(_this3, collectionName, { - get: function get() { - return _this3.collections[collectionName]; - } - }); - } + var useArgs = Object.assign({}, args, { + name: collectionName, + schema: schema, + database: _this2 }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + + // run hooks + var hookData = (0, _utils.flatClone)(args); + hookData.database = _this2; + hookData.name = name; + (0, _hooks.runPluginHooks)('preCreateRxCollection', hookData); + useArgs.conflictHandler = hookData.conflictHandler; + useArgsByCollectionName[collectionName] = useArgs; + }); + _context3.next = 7; + return this.internalStore.bulkWrite(bulkPutDocs, 'rx-database-add-collection'); + case 7: + putDocsResult = _context3.sent; + _context3.next = 10; + return ensureNoStartupErrors(this); + case 10: + Object.entries(putDocsResult.error).forEach(function (_ref2) { + var _id = _ref2[0], + error = _ref2[1]; + if (error.status !== 409) { + throw (0, _rxError.newRxError)('DB12', { + database: _this2.name, + writeError: error + }); + } + var docInDb = (0, _utils.ensureNotFalsy)(error.documentInDb); + var collectionName = docInDb.data.name; + var schema = schemas[collectionName]; + // collection already exists but has different schema + if (docInDb.data.schemaHash !== schema.hash) { + throw (0, _rxError.newRxError)('DB6', { + database: _this2.name, + collection: collectionName, + previousSchemaHash: docInDb.data.schemaHash, + schemaHash: schema.hash, + previousSchema: docInDb.data.schema, + schema: (0, _utils.ensureNotFalsy)(jsonSchemas[collectionName]) + }); + } + }); + ret = {}; + _context3.next = 14; + return Promise.all(Object.keys(collectionCreators).map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collectionName) { + var useArgs, collection; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + useArgs = useArgsByCollectionName[collectionName]; + _context2.next = 3; + return (0, _rxCollection.createRxCollection)(useArgs); + case 3: + collection = _context2.sent; + ret[collectionName] = collection; + + // set as getter to the database + _this2.collections[collectionName] = collection; + if (!_this2[collectionName]) { + Object.defineProperty(_this2, collectionName, { + get: function get() { + return _this2.collections[collectionName]; + } + }); + } + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 14: + return _context3.abrupt("return", ret); + case 15: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function addCollections(_x3) { + return _addCollections.apply(this, arguments); } - } + return addCollections; + }() /** * runs the given function between idleQueue-locking */ @@ -370,7 +336,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { * Export database to a JSON friendly format. */; _proto.exportJSON = function exportJSON(_collections) { - throw (0, _util.pluginMissing)('json-dump'); + throw (0, _utils.pluginMissing)('json-dump'); } /** @@ -380,96 +346,114 @@ var RxDatabaseBase = /*#__PURE__*/function () { * since data could be encrypted. */; _proto.importJSON = function importJSON(_exportedJSON) { - throw (0, _util.pluginMissing)('json-dump'); - }; - _proto.serverCouchDB = function serverCouchDB(_options) { - throw (0, _util.pluginMissing)('server-couchdb'); + throw (0, _utils.pluginMissing)('json-dump'); }; _proto.backup = function backup(_options) { - throw (0, _util.pluginMissing)('backup'); + throw (0, _utils.pluginMissing)('backup'); }; _proto.leaderElector = function leaderElector() { - throw (0, _util.pluginMissing)('leader-election'); + throw (0, _utils.pluginMissing)('leader-election'); }; _proto.isLeader = function isLeader() { - throw (0, _util.pluginMissing)('leader-election'); + throw (0, _utils.pluginMissing)('leader-election'); } /** * returns a promise which resolves when the instance becomes leader */; _proto.waitForLeadership = function waitForLeadership() { - throw (0, _util.pluginMissing)('leader-election'); + throw (0, _utils.pluginMissing)('leader-election'); }; _proto.migrationStates = function migrationStates() { - throw (0, _util.pluginMissing)('migration'); + throw (0, _utils.pluginMissing)('migration'); } /** * destroys the database-instance and all collections */; - _proto.destroy = function destroy() { - try { - var _this4 = this; - if (_this4.destroyed) { - return Promise.resolve(_util.PROMISE_RESOLVE_FALSE); - } - - // settings destroyed = true must be the first thing to do. - _this4.destroyed = true; - return Promise.resolve((0, _hooks.runAsyncPluginHooks)('preDestroyRxDatabase', _this4)).then(function () { - /** - * Complete the event stream - * to stop all subscribers who forgot to unsubscribe. - */ - _this4.eventBulks$.complete(); - DB_COUNT--; - _this4._subs.map(function (sub) { - return sub.unsubscribe(); - }); + _proto.destroy = + /*#__PURE__*/ + function () { + var _destroy = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var _this3 = this; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!this.destroyed) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", _utils.PROMISE_RESOLVE_FALSE); + case 2: + // settings destroyed = true must be the first thing to do. + this.destroyed = true; + _context4.next = 5; + return (0, _hooks.runAsyncPluginHooks)('preDestroyRxDatabase', this); + case 5: + /** + * Complete the event stream + * to stop all subscribers who forgot to unsubscribe. + */ + this.eventBulks$.complete(); + DB_COUNT--; + this._subs.map(function (sub) { + return sub.unsubscribe(); + }); - /** - * Destroying the pseudo instance will throw - * because stulff is missing - * TODO we should not need the pseudo instance on runtime. - * we should generate the property list on build time. - */ - return _this4.name === 'pseudoInstance' ? _util.PROMISE_RESOLVE_FALSE : _this4.requestIdlePromise().then(function () { - return Promise.all(_this4.onDestroy.map(function (fn) { - return fn(); - })); - }) - // destroy all collections - .then(function () { - return Promise.all(Object.keys(_this4.collections).map(function (key) { - return _this4.collections[key]; - }).map(function (col) { - return col.destroy(); - })); - }) - // destroy internal storage instances - .then(function () { - return _this4.internalStore.close(); - }) - // remove combination from USED_COMBINATIONS-map - .then(function () { - return USED_DATABASE_NAMES["delete"](_this4.name); - }).then(function () { - return true; - }); - }); - } catch (e) { - return Promise.reject(e); + /** + * Destroying the pseudo instance will throw + * because stulff is missing + * TODO we should not need the pseudo instance on runtime. + * we should generate the property list on build time. + */ + if (!(this.name === 'pseudoInstance')) { + _context4.next = 10; + break; + } + return _context4.abrupt("return", _utils.PROMISE_RESOLVE_FALSE); + case 10: + return _context4.abrupt("return", this.requestIdlePromise().then(function () { + return Promise.all(_this3.onDestroy.map(function (fn) { + return fn(); + })); + }) + // destroy all collections + .then(function () { + return Promise.all(Object.keys(_this3.collections).map(function (key) { + return _this3.collections[key]; + }).map(function (col) { + return col.destroy(); + })); + }) + // destroy internal storage instances + .then(function () { + return _this3.internalStore.close(); + }) + // remove combination from USED_COMBINATIONS-map + .then(function () { + return USED_DATABASE_NAMES["delete"](_this3.name); + }).then(function () { + return true; + })); + case 11: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function destroy() { + return _destroy.apply(this, arguments); } - } + return destroy; + }() /** * deletes the database and its stored data. * Returns the names of all removed collections. */ ; _proto.remove = function remove() { - var _this5 = this; + var _this4 = this; return this.destroy().then(function () { - return removeRxDatabase(_this5.name, _this5.storage); + return removeRxDatabase(_this4.name, _this4.storage); }); }; (0, _createClass2["default"])(RxDatabaseBase, [{ @@ -500,26 +484,61 @@ function throwIfDatabaseNameUsed(name) { }); } } -function createRxDatabase(_ref3) { - var storage = _ref3.storage, - instanceCreationOptions = _ref3.instanceCreationOptions, - name = _ref3.name, - password = _ref3.password, - _ref3$multiInstance = _ref3.multiInstance, - multiInstance = _ref3$multiInstance === void 0 ? true : _ref3$multiInstance, - _ref3$eventReduce = _ref3.eventReduce, - eventReduce = _ref3$eventReduce === void 0 ? false : _ref3$eventReduce, - _ref3$ignoreDuplicate = _ref3.ignoreDuplicate, - ignoreDuplicate = _ref3$ignoreDuplicate === void 0 ? false : _ref3$ignoreDuplicate, - _ref3$options = _ref3.options, - options = _ref3$options === void 0 ? {} : _ref3$options, - cleanupPolicy = _ref3.cleanupPolicy, - _ref3$allowSlowCount = _ref3.allowSlowCount, - allowSlowCount = _ref3$allowSlowCount === void 0 ? false : _ref3$allowSlowCount, - _ref3$localDocuments = _ref3.localDocuments, - localDocuments = _ref3$localDocuments === void 0 ? false : _ref3$localDocuments, - _ref3$hashFunction = _ref3.hashFunction, - hashFunction = _ref3$hashFunction === void 0 ? _util.defaultHashFunction : _ref3$hashFunction; + +/** + * Creates the storage instances that are used internally in the database + * to store schemas and other configuration stuff. + */ +function createRxDatabaseStorageInstance(_x5, _x6, _x7, _x8, _x9, _x10) { + return _createRxDatabaseStorageInstance.apply(this, arguments); +} +function _createRxDatabaseStorageInstance() { + _createRxDatabaseStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(databaseInstanceToken, storage, databaseName, options, multiInstance, password) { + var internalStore; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return storage.createStorageInstance({ + databaseInstanceToken: databaseInstanceToken, + databaseName: databaseName, + collectionName: _rxStorageHelper.INTERNAL_STORAGE_NAME, + schema: _rxDatabaseInternalStore.INTERNAL_STORE_SCHEMA, + options: options, + multiInstance: multiInstance, + password: password + }); + case 2: + internalStore = _context5.sent; + return _context5.abrupt("return", internalStore); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _createRxDatabaseStorageInstance.apply(this, arguments); +} +function createRxDatabase(_ref4) { + var storage = _ref4.storage, + instanceCreationOptions = _ref4.instanceCreationOptions, + name = _ref4.name, + password = _ref4.password, + _ref4$multiInstance = _ref4.multiInstance, + multiInstance = _ref4$multiInstance === void 0 ? true : _ref4$multiInstance, + _ref4$eventReduce = _ref4.eventReduce, + eventReduce = _ref4$eventReduce === void 0 ? false : _ref4$eventReduce, + _ref4$ignoreDuplicate = _ref4.ignoreDuplicate, + ignoreDuplicate = _ref4$ignoreDuplicate === void 0 ? false : _ref4$ignoreDuplicate, + _ref4$options = _ref4.options, + options = _ref4$options === void 0 ? {} : _ref4$options, + cleanupPolicy = _ref4.cleanupPolicy, + _ref4$allowSlowCount = _ref4.allowSlowCount, + allowSlowCount = _ref4$allowSlowCount === void 0 ? false : _ref4$allowSlowCount, + _ref4$localDocuments = _ref4.localDocuments, + localDocuments = _ref4$localDocuments === void 0 ? false : _ref4$localDocuments, + _ref4$hashFunction = _ref4.hashFunction, + hashFunction = _ref4$hashFunction === void 0 ? _utils.defaultHashFunction : _ref4$hashFunction; (0, _hooks.runPluginHooks)('preCreateRxDatabase', { storage: storage, instanceCreationOptions: instanceCreationOptions, @@ -536,7 +555,7 @@ function createRxDatabase(_ref3) { throwIfDatabaseNameUsed(name); } USED_DATABASE_NAMES.add(name); - var databaseInstanceToken = (0, _util.randomCouchString)(10); + var databaseInstanceToken = (0, _utils.randomCouchString)(10); return createRxDatabaseStorageInstance(databaseInstanceToken, storage, name, instanceCreationOptions, multiInstance, password) /** * Creating the internal store might fail @@ -566,10 +585,123 @@ function createRxDatabase(_ref3) { }); }); } + +/** + * Removes the database and all its known data + * with all known collections and all internal meta data. + * + * Returns the names of the removed collections. + */ +function removeRxDatabase(_x11, _x12) { + return _removeRxDatabase.apply(this, arguments); +} +function _removeRxDatabase() { + _removeRxDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(databaseName, storage) { + var databaseInstanceToken, dbInternalsStorageInstance, collectionDocs, collectionNames, removedCollectionNames; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + databaseInstanceToken = (0, _utils.randomCouchString)(10); + _context6.next = 3; + return createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, {}, false); + case 3: + dbInternalsStorageInstance = _context6.sent; + _context6.next = 6; + return (0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, dbInternalsStorageInstance); + case 6: + collectionDocs = _context6.sent; + collectionNames = new Set(); + collectionDocs.forEach(function (doc) { + return collectionNames.add(doc.data.name); + }); + removedCollectionNames = Array.from(collectionNames); + _context6.next = 12; + return Promise.all(removedCollectionNames.map(function (collectionName) { + return (0, _rxCollectionHelper.removeCollectionStorages)(storage, dbInternalsStorageInstance, databaseInstanceToken, databaseName, collectionName); + })); + case 12: + _context6.next = 14; + return (0, _hooks.runAsyncPluginHooks)('postRemoveRxDatabase', { + databaseName: databaseName, + storage: storage + }); + case 14: + _context6.next = 16; + return dbInternalsStorageInstance.remove(); + case 16: + return _context6.abrupt("return", removedCollectionNames); + case 17: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _removeRxDatabase.apply(this, arguments); +} function isRxDatabase(obj) { return obj instanceof RxDatabaseBase; } function dbCount() { return DB_COUNT; } + +/** + * Returns true if the given RxDatabase was the first + * instance that was created on the storage with this name. + * + * Can be used for some optimizations because on the first instantiation, + * we can assume that no data was written before. + */ +function isRxDatabaseFirstTimeInstantiated(_x13) { + return _isRxDatabaseFirstTimeInstantiated.apply(this, arguments); +} +/** + * For better performance some tasks run async + * and are awaited later. + * But we still have to ensure that there have been no errors + * on database creation. + */ +function _isRxDatabaseFirstTimeInstantiated() { + _isRxDatabaseFirstTimeInstantiated = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(database) { + var tokenDoc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return database.storageTokenDocument; + case 2: + tokenDoc = _context7.sent; + return _context7.abrupt("return", tokenDoc.data.instanceToken === database.token); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return _isRxDatabaseFirstTimeInstantiated.apply(this, arguments); +} +function ensureNoStartupErrors(_x14) { + return _ensureNoStartupErrors.apply(this, arguments); +} +function _ensureNoStartupErrors() { + _ensureNoStartupErrors = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(rxDatabase) { + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return rxDatabase.storageToken; + case 2: + if (!rxDatabase.startupErrors[0]) { + _context8.next = 4; + break; + } + throw rxDatabase.startupErrors[0]; + case 4: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + return _ensureNoStartupErrors.apply(this, arguments); +} //# sourceMappingURL=rx-database.js.map \ No newline at end of file diff --git a/dist/lib/rx-database.js.map b/dist/lib/rx-database.js.map index 84439509634..e2c2010e7bf 100644 --- a/dist/lib/rx-database.js.map +++ b/dist/lib/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["ensureNoStartupErrors","rxDatabase","storageToken","startupErrors","isRxDatabaseFirstTimeInstantiated","database","storageTokenDocument","tokenDoc","data","instanceToken","token","removeRxDatabase","databaseName","storage","databaseInstanceToken","randomCouchString","createRxDatabaseStorageInstance","dbInternalsStorageInstance","getAllCollectionDocuments","statics","collectionDocs","collectionNames","Set","forEach","doc","add","name","removedCollectionNames","Array","from","Promise","all","map","collectionName","removeCollectionStorages","runAsyncPluginHooks","remove","options","multiInstance","password","createStorageInstance","INTERNAL_STORAGE_NAME","schema","INTERNAL_STORE_SCHEMA","USED_DATABASE_NAMES","DB_COUNT","RxDatabaseBase","instanceCreationOptions","eventReduce","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","IdleQueue","_subs","onDestroy","destroyed","collections","eventBulks$","Subject","observable$","pipe","mergeMap","changeEventBulk","events","PROMISE_RESOLVE_FALSE","emittedEventBulkIds","ObliviousSet","getWrappedStorageInstance","asRxDatabase","ensureStorageTokenDocumentExists","err","push","then","$emit","has","id","next","removeCollectionDoc","getSingleDocument","getPrimaryKeyOfInternalDocument","_collectionNamePrimary","INTERNAL_CONTEXT_COLLECTION","newRxError","writeDoc","flatCloneDocWithMeta","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","args","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","error","_id","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","importJSON","_exportedJSON","serverCouchDB","_options","backup","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","complete","sub","unsubscribe","col","close","throwIfDatabaseNameUsed","link","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashFunction","storageInstance","creator","isRxDatabase","obj","dbCount"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n CouchDBServerOptions,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n AllMigrationStates,\n CouchDBServerResponse,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashFunction\n} from './util';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store';\nimport { removeCollectionStorages } from './rx-collection-helper';\n\n/**\n * stores the used database names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Beceause having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n Object.entries(collectionCreators).forEach(([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this,\n\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n });\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, error]) => {\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n });\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n serverCouchDB(_options?: CouchDBServerOptions): Promise {\n throw pluginMissing('server-couchdb');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stulff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashFunction\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n > {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name);\n }\n USED_DATABASE_NAMES.add(name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAiCA;AAUA;AAGA;AAIA;AAIA;AAKA;AAGA;AAGA;AAOA;AACA;AAQA;AA+mBA;AACA;AACA;AACA;AACA;AACA;AALA,IAMsBA,qBAAqB,YAArBA,qBAAqB,CACvCC,UAAyC;EAAA,IAC3C;IAAA,uBACQA,UAAU,CAACC,YAAY;MAAA,IACzBD,UAAU,CAACE,aAAa,CAAC,CAAC,CAAC;QAC3B,MAAMF,UAAU,CAACE,aAAa,CAAC,CAAC,CAAC;MAAC;IAAA;EAE1C,CAAC;IAAA;EAAA;AAAA;AAAA;AA5BD;AACA;AACA;AACA;AACA;AACA;AACA;AANA,IAOsBC,iCAAiC,YAAjCA,iCAAiC,CACnDC,QAAoB;EAAA,IACJ;IAAA,uBACOA,QAAQ,CAACC,oBAAoB,iBAA9CC,QAAQ;MACd,OAAOA,QAAQ,CAACC,IAAI,CAACC,aAAa,KAAKJ,QAAQ,CAACK,KAAK;IAAC;EAC1D,CAAC;IAAA;EAAA;AAAA;AAAA;AApED;AACA;AACA;AACA;AACA;AACA;AALA,IAMsBC,gBAAgB,YAAhBA,gBAAgB,CAClCC,YAAoB,EACpBC,OAA4B;EAAA,IACX;IACjB,IAAMC,qBAAqB,GAAG,IAAAC,uBAAiB,EAAC,EAAE,CAAC;IAAC,uBACXC,+BAA+B,CACpEF,qBAAqB,EACrBD,OAAO,EACPD,YAAY,EACZ,CAAC,CAAC,EACF,KAAK,CACR,iBAN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GAAG,IAAI6C,cAAc,CAC1DpB,IAAI,EACJZ,qBAAqB,EACrBD,OAAO,EACPkC,uBAAuB,EACvBR,QAAQ,EACRD,aAAa,EACbU,WAAW,EACXX,OAAO,EACP+H,eAAe,EACflH,YAAY,EACZC,aAAa,EACbC,cAAc,CACV;IAER,OAAO,IAAAjB,0BAAmB,EAAC,kBAAkB,EAAE;MAC3C9B,QAAQ,EAAEJ,UAAU;MACpBoK,OAAO,EAAE;QACLxJ,OAAO,EAAPA,OAAO;QACPkC,uBAAuB,EAAvBA,uBAAuB;QACvBrB,IAAI,EAAJA,IAAI;QACJa,QAAQ,EAARA,QAAQ;QACRD,aAAa,EAAbA,aAAa;QACbU,WAAW,EAAXA,WAAW;QACXiH,eAAe,EAAfA,eAAe;QACf5H,OAAO,EAAPA,OAAO;QACP6H,cAAc,EAAdA;MACJ;IACJ,CAAC,CAAC,CAACxF,IAAI,CAAC;MAAA,OAAMzE,UAAU;IAAA,EAAC;EAC7B,CAAC,CAAC;AACV;AAiDO,SAASqK,YAAY,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYzH,cAAc;AACxC;AAEO,SAAS0H,OAAO,GAAW;EAC9B,OAAO3H,QAAQ;AACnB"} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","IdleQueue","_subs","startupErrors","onDestroy","destroyed","collections","eventBulks$","Subject","observable$","pipe","mergeMap","changeEventBulk","events","storageToken","PROMISE_RESOLVE_FALSE","storageTokenDocument","emittedEventBulkIds","ObliviousSet","getWrappedStorageInstance","asRxDatabase","INTERNAL_STORE_SCHEMA","ensureStorageTokenDocumentExists","err","push","then","doc","data","$emit","has","id","add","next","removeCollectionDoc","schema","getSingleDocument","getPrimaryKeyOfInternalDocument","_collectionNamePrimary","INTERNAL_CONTEXT_COLLECTION","newRxError","writeDoc","flatCloneDocWithMeta","_deleted","bulkWrite","document","previous","addCollections","collectionCreators","jsonSchemas","schemas","bulkPutDocs","useArgsByCollectionName","Object","entries","forEach","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","database","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","_id","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","Promise","all","keys","map","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","remove","removeRxDatabase","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashFunction","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","getAllCollectionDocuments","statics","collectionDocs","collectionNames","removedCollectionNames","Array","from","removeCollectionStorages","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n AllMigrationStates,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashFunction\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME\n} from './rx-storage-helper';\nimport type { RxBackupState } from './plugins/backup';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store';\nimport { removeCollectionStorages } from './rx-collection-helper';\n\n/**\n * stores the used database names\n * so we can throw when the same database is created more then once.\n */\nconst USED_DATABASE_NAMES: Set = new Set();\n\nlet DB_COUNT = 0;\n\nexport class RxDatabaseBase<\n Internals,\n InstanceCreationOptions,\n Collections = CollectionsOfDatabase,\n> {\n\n public readonly idleQueue: IdleQueue = new IdleQueue();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\n DB_COUNT++;\n\n /**\n * In the dev-mode, we create a pseudoInstance\n * to get all properties of RxDatabase and ensure they do not\n * conflict with the collection names etc.\n * So only if it is not pseudoInstance,\n * we have all values to prepare a real RxDatabase.\n *\n * TODO this is ugly, we should use a different way in the dev-mode\n * so that all non-dev-mode code can be cleaner.\n */\n if (this.name !== 'pseudoInstance') {\n /**\n * Wrap the internal store\n * to ensure that calls to it also end up in\n * calculation of the idle state and the hooks.\n */\n this.internalStore = getWrappedStorageInstance(\n this.asRxDatabase,\n internalStore,\n INTERNAL_STORE_SCHEMA\n );\n\n /**\n * Start writing the storage token.\n * Do not await the creation because it would run\n * in a critical path that increases startup time.\n *\n * Writing the token takes about 20 milliseconds\n * even on a fast adapter, so this is worth it.\n */\n this.storageTokenDocument = ensureStorageTokenDocumentExists(this.asRxDatabase)\n .catch(err => this.startupErrors.push(err) as any);\n this.storageToken = this.storageTokenDocument\n .then(doc => doc.data.token)\n .catch(err => this.startupErrors.push(err) as any);\n }\n }\n\n get $(): Observable> {\n return this.observable$;\n }\n\n public _subs: Subscription[] = [];\n\n /**\n * Beceause having unhandled exceptions would fail,\n * we have to store the async errors of the constructor here\n * so we can throw them later.\n */\n public startupErrors: (RxError | RxTypeError)[] = [];\n\n /**\n * When the database is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed: boolean = false;\n public collections: Collections = {} as any;\n public readonly eventBulks$: Subject> = new Subject();\n private observable$: Observable> = this.eventBulks$\n .pipe(\n mergeMap(changeEventBulk => changeEventBulk.events)\n );\n\n /**\n * Unique token that is stored with the data.\n * Used to detect if the dataset has been deleted\n * and if two RxDatabase instances work on the same dataset or not.\n *\n * Because reading and writing the storageToken runs in the hot path\n * of database creation, we do not await the storageWrites but instead\n * work with the promise when we need the value.\n */\n public storageToken: Promise = PROMISE_RESOLVE_FALSE as any;\n /**\n * Stores the whole state of the internal storage token document.\n * We need this in some plugins.\n */\n public storageTokenDocument: Promise> = PROMISE_RESOLVE_FALSE as any;\n\n /**\n * Contains the ids of all event bulks that have been emitted\n * by the database.\n * Used to detect duplicates that come in again via BroadcastChannel\n * or other streams.\n * TODO instead of having this here, we should add a test to ensure each RxStorage\n * behaves equal and does never emit duplicate eventBulks.\n */\n public emittedEventBulkIds: ObliviousSet = new ObliviousSet(60 * 1000);\n\n /**\n * This is the main handle-point for all change events\n * ChangeEvents created by this instance go:\n * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance\n * ChangeEvents created by other instances go:\n * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase\n */\n $emit(changeEventBulk: RxChangeEventBulk) {\n if (this.emittedEventBulkIds.has(changeEventBulk.id)) {\n return;\n }\n this.emittedEventBulkIds.add(changeEventBulk.id);\n\n // emit into own stream\n this.eventBulks$.next(changeEventBulk);\n }\n\n /**\n * removes the collection-doc from the internalStore\n */\n async removeCollectionDoc(name: string, schema: any): Promise {\n const doc = await getSingleDocument(\n this.internalStore,\n getPrimaryKeyOfInternalDocument(\n _collectionNamePrimary(name, schema),\n INTERNAL_CONTEXT_COLLECTION\n )\n );\n if (!doc) {\n throw newRxError('SNH', { name, schema });\n }\n const writeDoc = flatCloneDocWithMeta(doc);\n writeDoc._deleted = true;\n\n await this.internalStore.bulkWrite([{\n document: writeDoc,\n previous: doc\n }], 'rx-database-remove-collection');\n }\n\n /**\n * creates multiple RxCollections at once\n * to be much faster by saving db txs and doing stuff in bulk-operations\n * This function is not called often, but mostly in the critical path at the initial page load\n * So it must be as fast as possible.\n */\n async addCollections>(collectionCreators: {\n [key in keyof CreatedCollections]: RxCollectionCreator\n }): Promise<{ [key in keyof CreatedCollections]: RxCollection }> {\n const jsonSchemas: { [key in keyof CreatedCollections]: RxJsonSchema } = {} as any;\n const schemas: { [key in keyof CreatedCollections]: RxSchema } = {} as any;\n const bulkPutDocs: BulkWriteRow[] = [];\n const useArgsByCollectionName: any = {};\n\n Object.entries(collectionCreators).forEach(([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n });\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n Object.entries(putDocsResult.error).forEach(([_id, error]) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n });\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stulff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\n return this as any;\n }\n}\n\n/**\n * checks if an instance with same name and adapter already exists\n * @throws {RxError} if used\n */\nfunction throwIfDatabaseNameUsed(\n name: string\n) {\n if (!USED_DATABASE_NAMES.has(name)) {\n return;\n } else {\n throw newRxError('DB8', {\n name,\n link: 'https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate'\n });\n }\n}\n\n/**\n * Creates the storage instances that are used internally in the database\n * to store schemas and other configuration stuff.\n */\nexport async function createRxDatabaseStorageInstance(\n databaseInstanceToken: string,\n storage: RxStorage,\n databaseName: string,\n options: InstanceCreationOptions,\n multiInstance: boolean,\n password?: string\n): Promise> {\n const internalStore = await storage.createStorageInstance(\n {\n databaseInstanceToken,\n databaseName,\n collectionName: INTERNAL_STORAGE_NAME,\n schema: INTERNAL_STORE_SCHEMA,\n options,\n multiInstance,\n password\n }\n );\n return internalStore;\n}\n\nexport function createRxDatabase<\n Collections = { [key: string]: RxCollection; },\n Internals = any,\n InstanceCreationOptions = any\n>(\n {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance = true,\n eventReduce = false,\n ignoreDuplicate = false,\n options = {},\n cleanupPolicy,\n allowSlowCount = false,\n localDocuments = false,\n hashFunction = defaultHashFunction\n }: RxDatabaseCreator\n): Promise<\n RxDatabase\n> {\n runPluginHooks('preCreateRxDatabase', {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n });\n // check if combination already used\n if (!ignoreDuplicate) {\n throwIfDatabaseNameUsed(name);\n }\n USED_DATABASE_NAMES.add(name);\n\n const databaseInstanceToken = randomCouchString(10);\n\n return createRxDatabaseStorageInstance<\n Internals,\n InstanceCreationOptions\n >(\n databaseInstanceToken,\n storage,\n name,\n instanceCreationOptions as any,\n multiInstance,\n password\n )\n /**\n * Creating the internal store might fail\n * if some RxStorage wrapper is used that does some checks\n * and then throw.\n * In that case we have to properly clean up the database.\n */\n .catch(err => {\n USED_DATABASE_NAMES.delete(name);\n throw err;\n })\n .then(storageInstance => {\n const rxDatabase: RxDatabase = new RxDatabaseBase(\n name,\n databaseInstanceToken,\n storage,\n instanceCreationOptions,\n password,\n multiInstance,\n eventReduce,\n options,\n storageInstance,\n hashFunction,\n cleanupPolicy,\n allowSlowCount\n ) as any;\n\n return runAsyncPluginHooks('createRxDatabase', {\n database: rxDatabase,\n creator: {\n storage,\n instanceCreationOptions,\n name,\n password,\n multiInstance,\n eventReduce,\n ignoreDuplicate,\n options,\n localDocuments\n }\n }).then(() => rxDatabase);\n });\n}\n\n/**\n * Removes the database and all its known data\n * with all known collections and all internal meta data.\n *\n * Returns the names of the removed collections.\n */\nexport async function removeRxDatabase(\n databaseName: string,\n storage: RxStorage\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false\n );\n\n const collectionDocs = await getAllCollectionDocuments(\n storage.statics,\n dbInternalsStorageInstance\n );\n\n const collectionNames = new Set();\n collectionDocs.forEach(doc => collectionNames.add(doc.data.name));\n const removedCollectionNames: string[] = Array.from(collectionNames);\n\n await Promise.all(\n removedCollectionNames.map(collectionName => removeCollectionStorages(\n storage,\n dbInternalsStorageInstance,\n databaseInstanceToken,\n databaseName,\n collectionName\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AA+BA;AAUA;AAGA;AAIA;AAIA;AAKA;AAGA;AAGA;AAOA;AACA;AAQA;AAEA;AACA;AACA;AACA;AACA,IAAMA,mBAAgC,GAAG,IAAIC,GAAG,EAAE;AAElD,IAAIC,QAAQ,GAAG,CAAC;AAAC,IAEJC,cAAc;EAQvB,wBACoBC,IAAY;EAC5B;AACR;AACA;AACA;EACwBC,KAAa,EACbC,OAAsD,EACtDC,uBAAgD,EAChDC,QAAa,EACbC,aAAsB,EAUxC;IAAA;IAAA,IATkBC,WAAoB,uEA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A,OAEIqJ,0BAA0B,CAACjB,MAAM,EAAE;QAAA;UAAA,kCAClCsB,sBAAsB;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAChC;EAAA;AAAA;AAEM,SAASI,YAAY,CAACC,GAAQ,EAAE;EACnC,OAAOA,GAAG,YAAYlK,cAAc;AACxC;AAEO,SAASmK,OAAO,GAAW;EAC9B,OAAOpK,QAAQ;AACnB;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AANA,SAOsBqK,iCAAiC;EAAA;AAAA;AAQvD;AACA;AACA;AACA;AACA;AACA;AALA;EAAA,mHARO,kBACH5E,QAAoB;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEGA,QAAQ,CAAC3D,oBAAoB;QAAA;UAA9CwI,QAAQ;UAAA,kCACPA,QAAQ,CAAC7H,IAAI,CAAC8H,aAAa,KAAK9E,QAAQ,CAACtF,KAAK;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CACxD;EAAA;AAAA;AAAA,SASqB4F,qBAAqB;EAAA;AAAA;AAAA;EAAA,uGAApC,kBACHwD,UAAyC;IAAA;MAAA;QAAA;UAAA;UAAA,OAEnCA,UAAU,CAAC3H,YAAY;QAAA;UAAA,KACzB2H,UAAU,CAACtI,aAAa,CAAC,CAAC,CAAC;YAAA;YAAA;UAAA;UAAA,MACrBsI,UAAU,CAACtI,aAAa,CAAC,CAAC,CAAC;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAExC;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/rx-document-prototype-merge.js b/dist/lib/rx-document-prototype-merge.js index dd0d20adbee..d3484aab18c 100644 --- a/dist/lib/rx-document-prototype-merge.js +++ b/dist/lib/rx-document-prototype-merge.js @@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -exports.createRxDocument = createRxDocument; -exports.createRxDocuments = createRxDocuments; +exports.createNewRxDocument = createNewRxDocument; exports.getDocumentOrmPrototype = getDocumentOrmPrototype; exports.getDocumentPrototype = getDocumentPrototype; exports.getRxDocumentConstructor = getRxDocumentConstructor; @@ -20,46 +19,41 @@ var _overwritable = require("./overwritable"); * In the future we should do this by chaining the __proto__ objects */ -// caches -var protoForCollection = new WeakMap(); var constructorForCollection = new WeakMap(); function getDocumentPrototype(rxCollection) { - if (!protoForCollection.has(rxCollection)) { - var schemaProto = rxCollection.schema.getDocumentPrototype(); - var ormProto = getDocumentOrmPrototype(rxCollection); - var baseProto = _rxDocument.basePrototype; - var proto = {}; - [schemaProto, ormProto, baseProto].forEach(function (obj) { - var props = Object.getOwnPropertyNames(obj); - props.forEach(function (key) { - var desc = Object.getOwnPropertyDescriptor(obj, key); + var schemaProto = rxCollection.schema.getDocumentPrototype(); + var ormProto = getDocumentOrmPrototype(rxCollection); + var baseProto = _rxDocument.basePrototype; + var proto = {}; + [schemaProto, ormProto, baseProto].forEach(function (obj) { + var props = Object.getOwnPropertyNames(obj); + props.forEach(function (key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); - /** - * When enumerable is true, it will show on console.dir(instance) - * To not pollute the output, only getters and methods are enumerable - */ - var enumerable = true; - if (key.startsWith('_') || key.endsWith('_') || key.startsWith('$') || key.endsWith('$')) enumerable = false; - if (typeof desc.value === 'function') { - // when getting a function, we automatically do a .bind(this) - Object.defineProperty(proto, key, { - get: function get() { - return desc.value.bind(this); - }, - enumerable: enumerable, - configurable: false - }); - } else { - desc.enumerable = enumerable; - desc.configurable = false; - if (desc.writable) desc.writable = false; - Object.defineProperty(proto, key, desc); - } - }); + /** + * When enumerable is true, it will show on console.dir(instance) + * To not pollute the output, only getters and methods are enumerable + */ + var enumerable = true; + if (key.startsWith('_') || key.endsWith('_') || key.startsWith('$') || key.endsWith('$')) enumerable = false; + if (typeof desc.value === 'function') { + // when getting a function, we automatically do a .bind(this) + Object.defineProperty(proto, key, { + get: function get() { + return desc.value.bind(this); + }, + enumerable: enumerable, + configurable: false + }); + } else { + desc.enumerable = enumerable; + desc.configurable = false; + if (desc.writable) desc.writable = false; + Object.defineProperty(proto, key, desc); + } }); - protoForCollection.set(rxCollection, proto); - } - return protoForCollection.get(rxCollection); + }); + return proto; } function getRxDocumentConstructor(rxCollection) { if (!constructorForCollection.has(rxCollection)) { @@ -72,33 +66,16 @@ function getRxDocumentConstructor(rxCollection) { /** * Create a RxDocument-instance from the jsonData * and the prototype merge. - * If the document already exists in the _docCache, - * return that instead to ensure we have no duplicates. + * You should never call this method directly, + * instead you should get the document from collection._docCache.getCachedRxDocument(). */ -function createRxDocument(rxCollection, docData) { - var primary = docData[rxCollection.schema.primaryPath]; - - // return from cache if exists - var cacheDoc = rxCollection._docCache.get(primary); - if (cacheDoc) { - return cacheDoc; - } +function createNewRxDocument(rxCollection, docData) { var doc = (0, _rxDocument.createWithConstructor)(getRxDocumentConstructor(rxCollection), rxCollection, _overwritable.overwritable.deepFreezeWhenDevMode(docData)); - rxCollection._docCache.set(primary, doc); rxCollection._runHooksSync('post', 'create', docData, doc); (0, _hooks.runPluginHooks)('postCreateRxDocument', doc); return doc; } -/** - * create RxDocument from the docs-array - */ -function createRxDocuments(rxCollection, docsJSON) { - return docsJSON.map(function (json) { - return createRxDocument(rxCollection, json); - }); -} - /** * returns the prototype-object * that contains the orm-methods, diff --git a/dist/lib/rx-document-prototype-merge.js.map b/dist/lib/rx-document-prototype-merge.js.map index 2132c520239..b3e5df87c4e 100644 --- a/dist/lib/rx-document-prototype-merge.js.map +++ b/dist/lib/rx-document-prototype-merge.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-document-prototype-merge.js","names":["protoForCollection","WeakMap","constructorForCollection","getDocumentPrototype","rxCollection","has","schemaProto","schema","ormProto","getDocumentOrmPrototype","baseProto","basePrototype","proto","forEach","obj","props","Object","getOwnPropertyNames","key","desc","getOwnPropertyDescriptor","enumerable","startsWith","endsWith","value","defineProperty","get","bind","configurable","writable","set","getRxDocumentConstructor","ret","createRxDocumentConstructor","createRxDocument","docData","primary","primaryPath","cacheDoc","_docCache","doc","createRxDocumentWithConstructor","overwritable","deepFreezeWhenDevMode","_runHooksSync","runPluginHooks","createRxDocuments","docsJSON","map","json","entries","methods","k","v"],"sources":["../../src/rx-document-prototype-merge.ts"],"sourcesContent":["/**\n * For the ORM capabilities,\n * we have to merge the document prototype\n * with the ORM functions and the data\n * We do this iterating over the properties and\n * adding them to a new object.\n * In the future we should do this by chaining the __proto__ objects\n */\n\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n createRxDocumentConstructor,\n basePrototype,\n createWithConstructor as createRxDocumentWithConstructor\n} from './rx-document';\nimport {\n runPluginHooks\n} from './hooks';\nimport { overwritable } from './overwritable';\n\n// caches\nconst protoForCollection: WeakMap = new WeakMap();\nconst constructorForCollection: WeakMap = new WeakMap();\n\nexport function getDocumentPrototype(\n rxCollection: RxCollection\n): any {\n if (!protoForCollection.has(rxCollection)) {\n const schemaProto = rxCollection.schema.getDocumentPrototype();\n const ormProto = getDocumentOrmPrototype(rxCollection);\n const baseProto = basePrototype;\n const proto = {};\n [\n schemaProto,\n ormProto,\n baseProto\n ].forEach(obj => {\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(key => {\n const desc: any = Object.getOwnPropertyDescriptor(obj, key);\n\n\n /**\n * When enumerable is true, it will show on console.dir(instance)\n * To not pollute the output, only getters and methods are enumerable\n */\n let enumerable = true;\n if (\n key.startsWith('_') ||\n key.endsWith('_') ||\n key.startsWith('$') ||\n key.endsWith('$')\n ) enumerable = false;\n\n if (typeof desc.value === 'function') {\n // when getting a function, we automatically do a .bind(this)\n Object.defineProperty(proto, key, {\n get() {\n return desc.value.bind(this);\n },\n enumerable,\n configurable: false\n });\n\n } else {\n desc.enumerable = enumerable;\n desc.configurable = false;\n if (desc.writable)\n desc.writable = false;\n Object.defineProperty(proto, key, desc);\n }\n });\n });\n protoForCollection.set(rxCollection, proto);\n\n }\n return protoForCollection.get(rxCollection);\n}\n\nexport function getRxDocumentConstructor(\n rxCollection: RxCollection\n) {\n if (!constructorForCollection.has(rxCollection)) {\n const ret = createRxDocumentConstructor(\n getDocumentPrototype(rxCollection)\n );\n constructorForCollection.set(rxCollection, ret);\n }\n return constructorForCollection.get(rxCollection);\n}\n\n/**\n * Create a RxDocument-instance from the jsonData\n * and the prototype merge.\n * If the document already exists in the _docCache,\n * return that instead to ensure we have no duplicates.\n */\nexport function createRxDocument(\n rxCollection: RxCollection,\n docData: RxDocumentData\n): RxDocument {\n const primary: string = docData[rxCollection.schema.primaryPath] as any;\n\n // return from cache if exists\n const cacheDoc = rxCollection._docCache.get(primary);\n if (cacheDoc) {\n return cacheDoc as any;\n }\n\n const doc = createRxDocumentWithConstructor(\n getRxDocumentConstructor(rxCollection as any),\n rxCollection as any,\n overwritable.deepFreezeWhenDevMode(docData as any)\n );\n\n rxCollection._docCache.set(primary, doc as any);\n rxCollection._runHooksSync('post', 'create', docData, doc);\n runPluginHooks('postCreateRxDocument', doc);\n return doc as any;\n}\n\n/**\n * create RxDocument from the docs-array\n */\nexport function createRxDocuments(\n rxCollection: RxCollection,\n docsJSON: any[]\n): RxDocument[] {\n return docsJSON.map(\n json => createRxDocument(rxCollection as any, json)\n );\n}\n\n/**\n * returns the prototype-object\n * that contains the orm-methods,\n * used in the proto-merge\n */\nexport function getDocumentOrmPrototype(rxCollection: RxCollection): any {\n const proto: any = {};\n Object\n .entries(rxCollection.methods)\n .forEach(([k, v]) => {\n proto[k] = v;\n });\n return proto;\n}\n"],"mappings":";;;;;;;;;;AAcA;AAKA;AAGA;AAtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAiBA;AACA,IAAMA,kBAA8C,GAAG,IAAIC,OAAO,EAAE;AACpE,IAAMC,wBAAoD,GAAG,IAAID,OAAO,EAAE;AAEnE,SAASE,oBAAoB,CAChCC,YAA0B,EACvB;EACH,IAAI,CAACJ,kBAAkB,CAACK,GAAG,CAACD,YAAY,CAAC,EAAE;IACvC,IAAME,WAAW,GAAGF,YAAY,CAACG,MAAM,CAACJ,oBAAoB,E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AQ,CAACC,GAAG,CACf,UAAAC,IAAI;IAAA,OAAIf,gBAAgB,CAAS9B,YAAY,EAAS6C,IAAI,CAAC;EAAA,EAC9D;AACL;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASxC,uBAAuB,CAACL,YAA0B,EAAO;EACrE,IAAMQ,KAAU,GAAG,CAAC,CAAC;EACrBI,MAAM,CACDkC,OAAO,CAAC9C,YAAY,CAAC+C,OAAO,CAAC,CAC7BtC,OAAO,CAAC,gBAAY;IAAA,IAAVuC,CAAC;MAAEC,CAAC;IACXzC,KAAK,CAACwC,CAAC,CAAC,GAAGC,CAAC;EAChB,CAAC,CAAC;EACN,OAAOzC,KAAK;AAChB"} \ No newline at end of file +{"version":3,"file":"rx-document-prototype-merge.js","names":["constructorForCollection","WeakMap","getDocumentPrototype","rxCollection","schemaProto","schema","ormProto","getDocumentOrmPrototype","baseProto","basePrototype","proto","forEach","obj","props","Object","getOwnPropertyNames","key","desc","getOwnPropertyDescriptor","enumerable","startsWith","endsWith","value","defineProperty","get","bind","configurable","writable","getRxDocumentConstructor","has","ret","createRxDocumentConstructor","set","createNewRxDocument","docData","doc","createRxDocumentWithConstructor","overwritable","deepFreezeWhenDevMode","_runHooksSync","runPluginHooks","entries","methods","k","v"],"sources":["../../src/rx-document-prototype-merge.ts"],"sourcesContent":["/**\n * For the ORM capabilities,\n * we have to merge the document prototype\n * with the ORM functions and the data\n * We do this iterating over the properties and\n * adding them to a new object.\n * In the future we should do this by chaining the __proto__ objects\n */\n\nimport type {\n RxCollection,\n RxDocument,\n RxDocumentData\n} from './types';\nimport {\n createRxDocumentConstructor,\n basePrototype,\n createWithConstructor as createRxDocumentWithConstructor\n} from './rx-document';\nimport {\n runPluginHooks\n} from './hooks';\nimport { overwritable } from './overwritable';\n\nconst constructorForCollection = new WeakMap();\n\nexport function getDocumentPrototype(\n rxCollection: RxCollection\n): any {\n const schemaProto = rxCollection.schema.getDocumentPrototype();\n const ormProto = getDocumentOrmPrototype(rxCollection);\n const baseProto = basePrototype;\n const proto = {};\n [\n schemaProto,\n ormProto,\n baseProto\n ].forEach(obj => {\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(key => {\n const desc: any = Object.getOwnPropertyDescriptor(obj, key);\n\n\n /**\n * When enumerable is true, it will show on console.dir(instance)\n * To not pollute the output, only getters and methods are enumerable\n */\n let enumerable = true;\n if (\n key.startsWith('_') ||\n key.endsWith('_') ||\n key.startsWith('$') ||\n key.endsWith('$')\n ) enumerable = false;\n\n if (typeof desc.value === 'function') {\n // when getting a function, we automatically do a .bind(this)\n Object.defineProperty(proto, key, {\n get() {\n return desc.value.bind(this);\n },\n enumerable,\n configurable: false\n });\n\n } else {\n desc.enumerable = enumerable;\n desc.configurable = false;\n if (desc.writable)\n desc.writable = false;\n Object.defineProperty(proto, key, desc);\n }\n });\n });\n return proto;\n}\n\nexport function getRxDocumentConstructor(\n rxCollection: RxCollection\n) {\n if (!constructorForCollection.has(rxCollection)) {\n const ret = createRxDocumentConstructor(\n getDocumentPrototype(rxCollection)\n );\n constructorForCollection.set(rxCollection, ret);\n }\n return constructorForCollection.get(rxCollection);\n}\n\n/**\n * Create a RxDocument-instance from the jsonData\n * and the prototype merge.\n * You should never call this method directly,\n * instead you should get the document from collection._docCache.getCachedRxDocument().\n */\nexport function createNewRxDocument(\n rxCollection: RxCollection,\n docData: RxDocumentData\n): RxDocument {\n const doc = createRxDocumentWithConstructor(\n getRxDocumentConstructor(rxCollection),\n rxCollection as any,\n overwritable.deepFreezeWhenDevMode(docData as any)\n );\n rxCollection._runHooksSync('post', 'create', docData, doc);\n runPluginHooks('postCreateRxDocument', doc);\n return doc as any;\n}\n\n\n/**\n * returns the prototype-object\n * that contains the orm-methods,\n * used in the proto-merge\n */\nexport function getDocumentOrmPrototype(rxCollection: RxCollection): any {\n const proto: any = {};\n Object\n .entries(rxCollection.methods)\n .forEach(([k, v]) => {\n proto[k] = v;\n });\n return proto;\n}\n"],"mappings":";;;;;;;;;AAcA;AAKA;AAG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,OAAOlC,KAAK;AAChB"} \ No newline at end of file diff --git a/dist/lib/rx-document.js b/dist/lib/rx-document.js index f66f1854061..285af703b91 100644 --- a/dist/lib/rx-document.js +++ b/dist/lib/rx-document.js @@ -5,197 +5,24 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.basePrototype = void 0; +exports.beforeDocumentUpdateWrite = beforeDocumentUpdateWrite; exports.createRxDocumentConstructor = createRxDocumentConstructor; exports.createWithConstructor = createWithConstructor; exports.defineGetterSetter = defineGetterSetter; exports.isRxDocument = isRxDocument; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _objectPath = _interopRequireDefault(require("object-path")); -var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _hooks = require("./hooks"); var _rxChangeEvent = require("./rx-change-event"); var _overwritable = require("./overwritable"); var _rxSchemaHelper = require("./rx-schema-helper"); var _rxStorageHelper = require("./rx-storage-helper"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} +var _incrementalWrite = require("./incremental-write"); var basePrototype = { - /** - * TODO - * instead of appliying the _this-hack - * we should make these accessors functions instead of getters. - */ - get _data() { - var _this = this; - /** - * Might be undefined when vuejs-devtools are used - * @link https://github.com/pubkey/rxdb/issues/1126 - */ - if (!_this.isInstanceOfRxDocument) { - return undefined; - } - return _this._dataSync$.getValue(); - }, get primaryPath() { var _this = this; if (!_this.isInstanceOfRxDocument) { @@ -222,7 +49,7 @@ var basePrototype = { if (!_this.isInstanceOfRxDocument) { return undefined; } - return _this._dataSync$.pipe((0, _operators.map)(function (d) { + return _this.$.pipe((0, _operators.map)(function (d) { return d._deleted; })); }, @@ -233,62 +60,54 @@ var basePrototype = { } return _this._data._deleted; }, + getLatest: function getLatest() { + var latestDocData = this.collection._docCache.getLatestDocumentData(this.primary); + return this.collection._docCache.getCachedRxDocument(latestDocData); + }, /** * returns the observable which emits the plain-data of this document */ get $() { + var _this2 = this; var _this = this; - return _this._dataSync$.asObservable().pipe((0, _operators.map)(function (docData) { - return _overwritable.overwritable.deepFreezeWhenDevMode(docData); - })); - }, - _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) { - return; - } - - // ensure that new _rev is higher then current - var docData = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); - var newRevNr = (0, _util.getHeightOfRevision)(docData._rev); - var currentRevNr = (0, _util.getHeightOfRevision)(this._data._rev); - if (currentRevNr > newRevNr) return; - switch (changeEvent.operation) { - case 'INSERT': - break; - case 'UPDATE': - this._dataSync$.next(changeEvent.documentData); - break; - case 'DELETE': - // remove from docCache to assure new upserted RxDocuments will be a new instance - this.collection._docCache["delete"](this.primary); - this._dataSync$.next(changeEvent.documentData); - break; - } + return _this.collection.$.pipe((0, _operators.filter)(function (changeEvent) { + return !changeEvent.isLocal; + }), (0, _operators.filter)(function (changeEvent) { + return changeEvent.documentId === _this2.primary; + }), (0, _operators.map)(function (changeEvent) { + return (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + }), (0, _operators.startWith)(_this.collection._docCache.getLatestDocumentData(this.primary)), (0, _operators.distinctUntilChanged)(function (prev, curr) { + return prev._rev === curr._rev; + }), (0, _operators.shareReplay)(_utils.RXJS_SHARE_REPLAY_DEFAULTS)); }, /** * returns observable of the value of the given path */ get$: function get$(path) { - if (path.includes('.item.')) { - throw (0, _rxError.newRxError)('DOC1', { - path: path - }); - } - if (path === this.primaryPath) throw (0, _rxError.newRxError)('DOC2'); + if (_overwritable.overwritable.isDevMode()) { + if (path.includes('.item.')) { + throw (0, _rxError.newRxError)('DOC1', { + path: path + }); + } + if (path === this.primaryPath) { + throw (0, _rxError.newRxError)('DOC2'); + } - // final fields cannot be modified and so also not observed - if (this.collection.schema.finalFields.includes(path)) { - throw (0, _rxError.newRxError)('DOC3', { - path: path - }); - } - var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); - if (!schemaObj) { - throw (0, _rxError.newRxError)('DOC4', { - path: path - }); + // final fields cannot be modified and so also not observed + if (this.collection.schema.finalFields.includes(path)) { + throw (0, _rxError.newRxError)('DOC3', { + path: path + }); + } + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); + if (!schemaObj) { + throw (0, _rxError.newRxError)('DOC4', { + path: path + }); + } } - return this._dataSync$.pipe((0, _operators.map)(function (data) { + return this.$.pipe((0, _operators.map)(function (data) { return _objectPath["default"].get(data, path); }), (0, _operators.distinctUntilChanged)()); }, @@ -299,7 +118,7 @@ var basePrototype = { var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); var value = this.get(path); if (!value) { - return _util.PROMISE_RESOLVE_NULL; + return _utils.PROMISE_RESOLVE_NULL; } if (!schemaObj) { throw (0, _rxError.newRxError)('DOC5', { @@ -321,7 +140,7 @@ var basePrototype = { }); } if (schemaObj.type === 'array') { - return refCollection.findByIds(value).then(function (res) { + return refCollection.findByIds(value).exec().then(function (res) { var valuesIterator = res.values(); return Array.from(valuesIterator); }); @@ -345,14 +164,14 @@ var basePrototype = { * TODO find a way to deep-freeze together with defineGetterSetter * so we do not have to do a deep clone here. */ - valueObj = (0, _util.clone)(valueObj); + valueObj = (0, _utils.clone)(valueObj); defineGetterSetter(this.collection.schema, valueObj, objPath, this); return valueObj; }, toJSON: function toJSON() { var withMetaFields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!withMetaFields) { - var data = (0, _util.flatClone)(this._data); + var data = (0, _utils.flatClone)(this._data); delete data._rev; delete data._attachments; delete data._deleted; @@ -364,7 +183,7 @@ var basePrototype = { }, toMutableJSON: function toMutableJSON() { var withMetaFields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return (0, _util.clone)(this.toJSON(withMetaFields)); + return (0, _utils.clone)(this.toJSON(withMetaFields)); }, /** * updates document @@ -372,99 +191,81 @@ var basePrototype = { * @param updateObj mongodb-like syntax */ update: function update(_updateObj) { - throw (0, _util.pluginMissing)('update'); + throw (0, _utils.pluginMissing)('update'); + }, + incrementalUpdate: function incrementalUpdate(_updateObj) { + throw (0, _utils.pluginMissing)('update'); }, updateCRDT: function updateCRDT(_updateObj) { - throw (0, _util.pluginMissing)('crdt'); + throw (0, _utils.pluginMissing)('crdt'); }, putAttachment: function putAttachment() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, getAttachment: function getAttachment() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, allAttachments: function allAttachments() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, get allAttachments$() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, + modify: function () { + var _modify = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(mutationFunction, + // used by some plugins that wrap the method + _context) { + var oldData, newData; + return _regenerator["default"].wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + oldData = this._data; + _context2.next = 3; + return (0, _incrementalWrite.modifierFromPublicToInternal)(mutationFunction)(oldData); + case 3: + newData = _context2.sent; + return _context2.abrupt("return", this._saveData(newData, oldData)); + case 5: + case "end": + return _context2.stop(); + } + }, _callee, this); + })); + function modify(_x, _x2) { + return _modify.apply(this, arguments); + } + return modify; + }(), /** - * runs an atomic update over the document + * runs an incremental update over the document * @param function that takes the document-data and returns a new data-object */ - atomicUpdate: function atomicUpdate(mutationFunction, + incrementalModify: function incrementalModify(mutationFunction, // used by some plugins that wrap the method _context) { - var _this2 = this; - return new Promise(function (res, rej) { - _this2._atomicQueue = _this2._atomicQueue.then(function () { - try { - var _temp5 = function _temp5(_result3) { - if (_exit) return _result3; - res(_this2); - }; - var _exit = false; - var done = false; - // we need a hacky while loop to stay incide the chain-link of _atomicQueue - // while still having the option to run a retry on conflicts - var _temp4 = _for(function () { - return !_exit && !done; - }, void 0, function () { - function _temp3(_result) { - if (_exit) return _result; - var _temp = _catch(function () { - return Promise.resolve(_this2._saveData(newData, oldData)).then(function () { - done = true; - }); - }, function (err) { - var useError = err.parameters && err.parameters.error ? err.parameters.error : err; - /** - * conflicts cannot happen by just using RxDB in one process - * There are two ways they still can appear which is - * replication and multi-tab usage - * Because atomicUpdate has a mutation function, - * we can just re-run the mutation until there is no conflict - */ - var isConflict = (0, _rxError.isBulkWriteConflictError)(useError); - if (isConflict) {} else { - rej(useError); - _exit = true; - } - }); - if (_temp && _temp.then) return _temp.then(function () {}); - } - var oldData = _this2._dataSync$.getValue(); - // always await because mutationFunction might be async - var newData; - var _temp2 = _catch(function () { - return Promise.resolve(mutationFunction((0, _util.clone)(oldData), _this2)).then(function (_mutationFunction) { - newData = _mutationFunction; - if (_this2.collection) { - newData = _this2.collection.schema.fillObjectWithDefaults(newData); - } - }); - }, function (err) { - rej(err); - _exit = true; - }); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }); + var _this3 = this; + return this.collection.incrementalWriteQueue.addWrite(this._data, (0, _incrementalWrite.modifierFromPublicToInternal)(mutationFunction)).then(function (result) { + return _this3.collection._docCache.getCachedRxDocument(result); }); }, + patch: function patch(_patch) { + var oldData = this._data; + var newData = (0, _utils.clone)(oldData); + Object.entries(_patch).forEach(function (_ref) { + var k = _ref[0], + v = _ref[1]; + newData[k] = v; + }); + return this._saveData(newData, oldData); + }, /** * patches the given properties */ - atomicPatch: function atomicPatch(patch) { - return this.atomicUpdate(function (docData) { - Object.entries(patch).forEach(function (_ref) { - var k = _ref[0], - v = _ref[1]; + incrementalPatch: function incrementalPatch(patch) { + return this.incrementalModify(function (docData) { + Object.entries(patch).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; docData[k] = v; }); return docData; @@ -474,49 +275,55 @@ var basePrototype = { * saves the new document-data * and handles the events */ - _saveData: function _saveData(newData, oldData) { - try { - var _this3 = this; - newData = (0, _util.flatClone)(newData); + _saveData: function () { + var _saveData2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(newData, oldData) { + var writeResult, isError; + return _regenerator["default"].wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + newData = (0, _utils.flatClone)(newData); - // deleted documents cannot be changed - if (_this3._data._deleted) { - throw (0, _rxError.newRxError)('DOC11', { - id: _this3.primary, - document: _this3 - }); - } - - /** - * Meta values must always be merged - * instead of overwritten. - * This ensures that different plugins do not overwrite - * each others meta properties. - */ - newData._meta = Object.assign({}, oldData._meta, newData._meta); - - // ensure modifications are ok - if (_overwritable.overwritable.isDevMode()) { - _this3.collection.schema.validateChange(oldData, newData); - } - return Promise.resolve(_this3.collection._runHooks('pre', 'save', newData, _this3)).then(function () { - return Promise.resolve(_this3.collection.storageInstance.bulkWrite([{ - previous: oldData, - document: newData - }], 'rx-document-save-data')).then(function (writeResult) { - var isError = writeResult.error[_this3.primary]; - (0, _rxStorageHelper.throwIfIsStorageWriteError)(_this3.collection, _this3.primary, newData, isError); - return _this3.collection._runHooks('post', 'save', newData, _this3); - }); - }); - } catch (e) { - return Promise.reject(e); + // deleted documents cannot be changed + if (!this._data._deleted) { + _context3.next = 3; + break; + } + throw (0, _rxError.newRxError)('DOC11', { + id: this.primary, + document: this + }); + case 3: + _context3.next = 5; + return beforeDocumentUpdateWrite(this.collection, newData, oldData); + case 5: + _context3.next = 7; + return this.collection.storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }], 'rx-document-save-data'); + case 7: + writeResult = _context3.sent; + isError = writeResult.error[this.primary]; + (0, _rxStorageHelper.throwIfIsStorageWriteError)(this.collection, this.primary, newData, isError); + _context3.next = 12; + return this.collection._runHooks('post', 'save', newData, this); + case 12: + return _context3.abrupt("return", this.collection._docCache.getCachedRxDocument((0, _utils.getFromObjectOrThrow)(writeResult.success, this.primary))); + case 13: + case "end": + return _context3.stop(); + } + }, _callee2, this); + })); + function _saveData(_x3, _x4) { + return _saveData2.apply(this, arguments); } - }, + return _saveData; + }(), /** - * remove the document, - * this not not equal to a pouchdb.remove(), - * instead we keep the values and only set _deleted: true + * Remove the document. + * Notice that there is no hard delete, + * instead deleted documents get flagged with _deleted=true. */ remove: function remove() { var _this4 = this; @@ -527,27 +334,77 @@ var basePrototype = { id: this.primary })); } - var deletedData = (0, _util.flatClone)(this._data); - return collection._runHooks('pre', 'remove', deletedData, this).then(function () { - try { - deletedData._deleted = true; - return Promise.resolve(collection.storageInstance.bulkWrite([{ - previous: _this4._data, - document: deletedData - }], 'rx-document-remove')).then(function (writeResult) { - var isError = writeResult.error[_this4.primary]; - (0, _rxStorageHelper.throwIfIsStorageWriteError)(collection, _this4.primary, deletedData, isError); - return (0, _util.ensureNotFalsy)(writeResult.success[_this4.primary]); - }); - } catch (e) { - return Promise.reject(e); - } - }).then(function () { + var deletedData = (0, _utils.flatClone)(this._data); + var removedDocData; + return collection._runHooks('pre', 'remove', deletedData, this).then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var writeResult, isError; + return _regenerator["default"].wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + deletedData._deleted = true; + _context4.next = 3; + return collection.storageInstance.bulkWrite([{ + previous: _this4._data, + document: deletedData + }], 'rx-document-remove'); + case 3: + writeResult = _context4.sent; + isError = writeResult.error[_this4.primary]; + (0, _rxStorageHelper.throwIfIsStorageWriteError)(collection, _this4.primary, deletedData, isError); + return _context4.abrupt("return", (0, _utils.getFromObjectOrThrow)(writeResult.success, _this4.primary)); + case 7: + case "end": + return _context4.stop(); + } + }, _callee3); + }))).then(function (removed) { + removedDocData = removed; return _this4.collection._runHooks('post', 'remove', deletedData, _this4); }).then(function () { - return _this4; + return _this4.collection._docCache.getCachedRxDocument(removedDocData); }); }, + incrementalRemove: function incrementalRemove() { + var _this5 = this; + return this.incrementalModify( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(docData) { + return _regenerator["default"].wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5.collection._runHooks('pre', 'remove', docData, _this5); + case 2: + docData._deleted = true; + return _context5.abrupt("return", docData); + case 4: + case "end": + return _context5.stop(); + } + }, _callee4); + })); + return function (_x5) { + return _ref4.apply(this, arguments); + }; + }()).then( /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(newDoc) { + return _regenerator["default"].wrap(function _callee5$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return _this5.collection._runHooks('post', 'remove', newDoc._data, newDoc); + case 2: + return _context6.abrupt("return", newDoc); + case 3: + case "end": + return _context6.stop(); + } + }, _callee5); + })); + return function (_x6) { + return _ref5.apply(this, arguments); + }; + }()); + }, destroy: function destroy() { throw (0, _rxError.newRxError)('DOC14'); } @@ -555,12 +412,11 @@ var basePrototype = { exports.basePrototype = basePrototype; function createRxDocumentConstructor() { var proto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : basePrototype; - var constructor = function RxDocumentConstructor(collection, jsonData) { + var constructor = function RxDocumentConstructor(collection, docData) { this.collection = collection; // assume that this is always equal to the doc-data in the database - this._dataSync$ = new _rxjs.BehaviorSubject(jsonData); - this._atomicQueue = _util.PROMISE_RESOLVE_VOID; + this._data = docData; /** * because of the prototype-merge, @@ -579,7 +435,7 @@ function defineGetterSetter(schema, valueObj) { if (typeof pathProperties === 'undefined') return; if (pathProperties.properties) pathProperties = pathProperties.properties; Object.keys(pathProperties).forEach(function (key) { - var fullPath = (0, _util.trimDots)(objPath + '.' + key); + var fullPath = (0, _utils.trimDots)(objPath + '.' + key); // getter - value valueObj.__defineGetter__(key, function () { @@ -621,10 +477,6 @@ function defineGetterSetter(schema, valueObj) { }); } function createWithConstructor(constructor, collection, jsonData) { - var primary = jsonData[collection.schema.primaryPath]; - if (primary && primary.startsWith('_design')) { - return null; - } var doc = new constructor(collection, jsonData); (0, _hooks.runPluginHooks)('createRxDocument', doc); return doc; @@ -633,4 +485,19 @@ function isRxDocument(obj) { if (typeof obj === 'undefined') return false; return !!obj.isInstanceOfRxDocument; } +function beforeDocumentUpdateWrite(collection, newData, oldData) { + /** + * Meta values must always be merged + * instead of overwritten. + * This ensures that different plugins do not overwrite + * each others meta properties. + */ + newData._meta = Object.assign({}, oldData._meta, newData._meta); + + // ensure modifications are ok + if (_overwritable.overwritable.isDevMode()) { + collection.schema.validateChange(oldData, newData); + } + return collection._runHooks('pre', 'save', newData); +} //# sourceMappingURL=rx-document.js.map \ No newline at end of file diff --git a/dist/lib/rx-document.js.map b/dist/lib/rx-document.js.map index 814b06c5b92..2d4e549cf06 100644 --- a/dist/lib/rx-document.js.map +++ b/dist/lib/rx-document.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-document.js","names":["body","recover","result","e","then","pact","state","value","s","v","o","bind","observer","prototype","onFulfilled","onRejected","callback","_this","thenable","test","update","stage","shouldContinue","updateValue","reject","_resumeAfterTest","_resumeAfterBody","_resumeAfterUpdate","basePrototype","_data","isInstanceOfRxDocument","undefined","_dataSync$","getValue","primaryPath","collection","schema","primary","revision","_rev","deleted$","pipe","map","d","_deleted","deleted","$","asObservable","docData","overwritable","deepFreezeWhenDevMode","_handleChangeEvent","changeEvent","documentId","getDocumentDataOfRxChangeEvent","newRevNr","getHeightOfRevision","currentRevNr","operation","next","documentData","_docCache","get$","path","includes","newRxError","finalFields","schemaObj","getSchemaByObjectPath","jsonSchema","data","objectPath","get","distinctUntilChanged","populate","PROMISE_RESOLVE_NULL","ref","refCollection","database","collections","type","findByIds","res","valuesIterator","values","Array","from","findOne","exec","objPath","valueObj","isArray","clone","defineGetterSetter","toJSON","withMetaFields","flatClone","_attachments","_meta","toMutableJSON","_updateObj","pluginMissing","updateCRDT","putAttachment","getAttachment","allAttachments","allAttachments$","atomicUpdate","mutationFunction","_context","Promise","rej","_atomicQueue","done","_saveData","newData","oldData","err","useError","parameters","error","isConflict","isBulkWriteConflictError","fillObjectWithDefaults","atomicPatch","patch","Object","entries","forEach","k","id","document","assign","isDevMode","validateChange","_runHooks","storageInstance","bulkWrite","previous","writeResult","isError","throwIfIsStorageWriteError","remove","deletedData","ensureNotFalsy","success","destroy","createRxDocumentConstructor","proto","constructor","RxDocumentConstructor","jsonData","BehaviorSubject","PROMISE_RESOLVE_VOID","thisObj","pathProperties","properties","keys","key","fullPath","trimDots","__defineGetter__","ret","defineProperty","enumerable","configurable","__defineSetter__","val","set","createWithConstructor","startsWith","doc","runPluginHooks","isRxDocument","obj"],"sources":["../../src/rx-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport {\n Observable,\n BehaviorSubject\n} from 'rxjs';\nimport {\n distinctUntilChanged,\n map\n} from 'rxjs/operators';\nimport {\n clone,\n trimDots,\n getHeightOfRevision,\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_NULL,\n PROMISE_RESOLVE_VOID,\n ensureNotFalsy\n} from './util';\nimport {\n newRxError,\n isBulkWriteConflictError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\n\nimport type {\n RxDocument,\n RxCollection,\n RxDocumentData,\n RxDocumentWriteData,\n RxChangeEvent,\n UpdateQuery,\n CRDTEntry\n} from './types';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\nimport { overwritable } from './overwritable';\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport { throwIfIsStorageWriteError } from './rx-storage-helper';\n\nexport const basePrototype = {\n\n /**\n * TODO\n * instead of appliying the _this-hack\n * we should make these accessors functions instead of getters.\n */\n get _data() {\n const _this: RxDocument = this as any;\n /**\n * Might be undefined when vuejs-devtools are used\n * @link https://github.com/pubkey/rxdb/issues/1126\n */\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n\n return _this._dataSync$.getValue();\n },\n get primaryPath() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this.collection.schema.primaryPath;\n },\n get primary() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return (_this._data as any)[_this.primaryPath];\n },\n get revision() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._rev;\n },\n get deleted$() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._dataSync$.pipe(\n map((d: any) => d._deleted)\n );\n },\n get deleted() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._deleted;\n },\n\n /**\n * returns the observable which emits the plain-data of this document\n */\n get $(): Observable {\n const _this: RxDocument = this as any;\n return _this._dataSync$.asObservable().pipe(\n map(docData => overwritable.deepFreezeWhenDevMode(docData))\n );\n },\n\n _handleChangeEvent(this: RxDocument, changeEvent: RxChangeEvent) {\n if (changeEvent.documentId !== this.primary) {\n return;\n }\n\n // ensure that new _rev is higher then current\n const docData = getDocumentDataOfRxChangeEvent(changeEvent);\n const newRevNr = getHeightOfRevision(docData._rev);\n const currentRevNr = getHeightOfRevision(this._data._rev);\n if (currentRevNr > newRevNr) return;\n\n switch (changeEvent.operation) {\n case 'INSERT':\n break;\n case 'UPDATE':\n this._dataSync$.next(changeEvent.documentData);\n break;\n case 'DELETE':\n // remove from docCache to assure new upserted RxDocuments will be a new instance\n this.collection._docCache.delete(this.primary);\n this._dataSync$.next(changeEvent.documentData);\n break;\n }\n },\n\n /**\n * returns observable of the value of the given path\n */\n get$(this: RxDocument, path: string): Observable {\n if (path.includes('.item.')) {\n throw newRxError('DOC1', {\n path\n });\n }\n\n if (path === this.primaryPath)\n throw newRxError('DOC2');\n\n // final fields cannot be modified and so also not observed\n if (this.collection.schema.finalFields.includes(path)) {\n throw newRxError('DOC3', {\n path\n });\n }\n\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n if (!schemaObj) {\n throw newRxError('DOC4', {\n path\n });\n }\n\n return this._dataSync$\n .pipe(\n map(data => objectPath.get(data, path)),\n distinctUntilChanged()\n );\n },\n\n /**\n * populate the given path\n */\n populate(this: RxDocument, path: string): Promise {\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n const value = this.get(path);\n if (!value) {\n return PROMISE_RESOLVE_NULL;\n }\n if (!schemaObj) {\n throw newRxError('DOC5', {\n path\n });\n }\n if (!schemaObj.ref) {\n throw newRxError('DOC6', {\n path,\n schemaObj\n });\n }\n\n const refCollection: RxCollection = this.collection.database.collections[schemaObj.ref];\n if (!refCollection) {\n throw newRxError('DOC7', {\n ref: schemaObj.ref,\n path,\n schemaObj\n });\n }\n\n if (schemaObj.type === 'array') {\n return refCollection.findByIds(value).then(res => {\n const valuesIterator = res.values();\n return Array.from(valuesIterator) as any;\n });\n } else {\n return refCollection.findOne(value).exec();\n }\n },\n\n /**\n * get data by objectPath\n */\n get(this: RxDocument, objPath: string): any | null {\n if (!this._data) return undefined;\n let valueObj = objectPath.get(this._data, objPath);\n\n // direct return if array or non-object\n if (\n typeof valueObj !== 'object' ||\n Array.isArray(valueObj)\n ) {\n return overwritable.deepFreezeWhenDevMode(valueObj);\n }\n\n /**\n * TODO find a way to deep-freeze together with defineGetterSetter\n * so we do not have to do a deep clone here.\n */\n valueObj = clone(valueObj);\n defineGetterSetter(\n this.collection.schema,\n valueObj,\n objPath,\n this as any\n );\n return valueObj;\n },\n\n toJSON(this: RxDocument, withMetaFields = false) {\n if (!withMetaFields) {\n const data = flatClone(this._data);\n delete (data as any)._rev;\n delete (data as any)._attachments;\n delete (data as any)._deleted;\n delete (data as any)._meta;\n return overwritable.deepFreezeWhenDevMode(data);\n } else {\n return overwritable.deepFreezeWhenDevMode(this._data);\n }\n },\n toMutableJSON(this: RxDocument, withMetaFields = false) {\n return clone(this.toJSON(withMetaFields as any));\n },\n\n /**\n * updates document\n * @overwritten by plugin (optional)\n * @param updateObj mongodb-like syntax\n */\n update(_updateObj: UpdateQuery) {\n throw pluginMissing('update');\n },\n updateCRDT(_updateObj: CRDTEntry | CRDTEntry[]) {\n throw pluginMissing('crdt');\n },\n putAttachment() {\n throw pluginMissing('attachments');\n },\n getAttachment() {\n throw pluginMissing('attachments');\n },\n allAttachments() {\n throw pluginMissing('attachments');\n },\n get allAttachments$() {\n throw pluginMissing('attachments');\n },\n\n\n /**\n * runs an atomic update over the document\n * @param function that takes the document-data and returns a new data-object\n */\n atomicUpdate(\n this: RxDocument,\n mutationFunction: Function,\n // used by some plugins that wrap the method\n _context?: string\n ): Promise {\n return new Promise((res, rej) => {\n this._atomicQueue = this\n ._atomicQueue\n .then(async () => {\n let done = false;\n // we need a hacky while loop to stay incide the chain-link of _atomicQueue\n // while still having the option to run a retry on conflicts\n while (!done) {\n const oldData = this._dataSync$.getValue();\n // always await because mutationFunction might be async\n let newData;\n\n try {\n newData = await mutationFunction(\n clone(oldData),\n this\n );\n if (this.collection) {\n newData = this.collection.schema.fillObjectWithDefaults(newData);\n }\n } catch (err) {\n rej(err);\n return;\n }\n\n try {\n await this._saveData(newData, oldData);\n done = true;\n } catch (err: any) {\n const useError = err.parameters && err.parameters.error ? err.parameters.error : err;\n /**\n * conflicts cannot happen by just using RxDB in one process\n * There are two ways they still can appear which is\n * replication and multi-tab usage\n * Because atomicUpdate has a mutation function,\n * we can just re-run the mutation until there is no conflict\n */\n const isConflict = isBulkWriteConflictError(useError as any);\n if (isConflict) {\n // conflict error -> retrying\n } else {\n rej(useError);\n return;\n }\n }\n }\n res(this);\n });\n });\n },\n\n\n /**\n * patches the given properties\n */\n atomicPatch(\n this: RxDocument,\n patch: Partial\n ): Promise> {\n return this.atomicUpdate((docData: RxDocumentType) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n (docData as any)[k] = v;\n });\n return docData;\n });\n },\n\n /**\n * saves the new document-data\n * and handles the events\n */\n async _saveData(\n this: RxDocument,\n newData: RxDocumentWriteData,\n oldData: RxDocumentData\n ): Promise {\n newData = flatClone(newData);\n\n // deleted documents cannot be changed\n if (this._data._deleted) {\n throw newRxError('DOC11', {\n id: this.primary,\n document: this\n });\n }\n\n /**\n * Meta values must always be merged\n * instead of overwritten.\n * This ensures that different plugins do not overwrite\n * each others meta properties.\n */\n newData._meta = Object.assign(\n {},\n oldData._meta,\n newData._meta\n );\n\n // ensure modifications are ok\n if (overwritable.isDevMode()) {\n this.collection.schema.validateChange(oldData, newData);\n }\n\n await this.collection._runHooks('pre', 'save', newData, this);\n\n const writeResult = await this.collection.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'rx-document-save-data');\n\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(this.collection, this.primary, newData, isError);\n\n return this.collection._runHooks('post', 'save', newData, this);\n },\n\n /**\n * remove the document,\n * this not not equal to a pouchdb.remove(),\n * instead we keep the values and only set _deleted: true\n */\n remove(this: RxDocument): Promise {\n const collection = this.collection;\n if (this.deleted) {\n return Promise.reject(newRxError('DOC13', {\n document: this,\n id: this.primary\n }));\n }\n\n const deletedData = flatClone(this._data);\n return collection._runHooks('pre', 'remove', deletedData, this)\n .then(async () => {\n deletedData._deleted = true;\n\n const writeResult = await collection.storageInstance.bulkWrite([{\n previous: this._data,\n document: deletedData\n }], 'rx-document-remove');\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(collection, this.primary, deletedData, isError);\n return ensureNotFalsy(writeResult.success[this.primary]);\n })\n .then(() => {\n return this.collection._runHooks('post', 'remove', deletedData, this);\n })\n .then(() => this);\n },\n destroy() {\n throw newRxError('DOC14');\n }\n};\n\nexport function createRxDocumentConstructor(proto = basePrototype) {\n const constructor = function RxDocumentConstructor(\n this: RxDocument,\n collection: RxCollection,\n jsonData: any\n ) {\n this.collection = collection;\n\n // assume that this is always equal to the doc-data in the database\n this._dataSync$ = new BehaviorSubject(jsonData);\n\n this._atomicQueue = PROMISE_RESOLVE_VOID;\n\n /**\n * because of the prototype-merge,\n * we can not use the native instanceof operator\n */\n this.isInstanceOfRxDocument = true;\n };\n constructor.prototype = proto;\n return constructor;\n}\n\nexport function defineGetterSetter(\n schema: any,\n valueObj: any,\n objPath = '',\n thisObj = false\n) {\n if (valueObj === null) return;\n\n\n let pathProperties = getSchemaByObjectPath(\n schema.jsonSchema,\n objPath\n );\n\n if (typeof pathProperties === 'undefined') return;\n if (pathProperties.properties) pathProperties = pathProperties.properties;\n\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = trimDots(objPath + '.' + key);\n\n // getter - value\n valueObj.__defineGetter__(\n key,\n function (this: RxDocument) {\n const _this: RxDocument = thisObj ? thisObj : (this as any);\n if (!_this.get || typeof _this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = _this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(valueObj, key + '$', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(valueObj, key + '_', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // setter - value\n valueObj.__defineSetter__(key, function (\n this: RxDocument,\n val: any\n ) {\n const _this: any = thisObj ? thisObj : this;\n return _this.set(fullPath, val);\n });\n });\n}\n\nexport function createWithConstructor(\n constructor: any,\n collection: RxCollection,\n jsonData: RxDocumentData\n): RxDocument | null {\n const primary: string = jsonData[collection.schema.primaryPath] as any;\n if (\n primary &&\n primary.startsWith('_design')\n ) {\n return null;\n }\n\n const doc = new constructor(collection, jsonData);\n runPluginHooks('createRxDocument', doc);\n return doc;\n}\n\nexport function isRxDocument(obj: any): boolean {\n if (typeof obj === 'undefined') return false;\n return !!obj.isInstanceOfRxDocument;\n}\n"],"mappings":";;;;;;;;;;;AAAA;AACA;AAIA;AAIA;AAUA;AAIA;AAaA;AACA;AACA;AACA;AA2gBO,gBAAgBA,IAAI,EAAEC,OAAO,EAAE;EACrC,IAAI;IACH,IAAIC,MAAM,GAAGF,IAAI,EAAE;EACpB,CAAC,CAAC,OAAMG,CAAC,EAAE;IACV,OAAOF,OAAO,CAACE,CAAC,CAAC;EAClB;EACA,IAAID,MAAM,IAAIA,MAAM,CAACE,IAAI,EAAE;IAC1B,OAAOF,MAAM,CAACE,IAAI,CAAC,KAAK,CAAC,EAAEH,OAAO,CAAC;EACpC;EACA,OAAOC,MAAM;AACd;AArhBO,iBAAiBG,IAAI,EAAEC,KAAK,EAAEC,KAAK,EAAE;EAC3C,IAAI,CAACF,IAAI,CAACG,CAAC,EAAE;IACZ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ACjCpB,WAAgB,EAChBlH,UAAmC,EACnCoH,QAAmC,EACP;EAC5B,IAAMlH,OAAe,GAAGkH,QAAQ,CAACpH,UAAU,CAACC,MAAM,CAACF,WAAW,CAAQ;EACtE,IACIG,OAAO,IACPA,OAAO,CAACqI,UAAU,CAAC,SAAS,CAAC,EAC/B;IACE,OAAO,IAAI;EACf;EAEA,IAAMC,GAAG,GAAG,IAAItB,WAAW,CAAClH,UAAU,EAAEoH,QAAQ,CAAC;EACjD,IAAAqB,qBAAc,EAAC,kBAAkB,EAAED,GAAG,CAAC;EACvC,OAAOA,GAAG;AACd;AAEO,SAASE,YAAY,CAACC,GAAQ,EAAW;EAC5C,IAAI,OAAOA,GAAG,KAAK,WAAW,EAAE,OAAO,KAAK;EAC5C,OAAO,CAAC,CAACA,GAAG,CAAChJ,sBAAsB;AACvC"} \ No newline at end of file +{"version":3,"file":"rx-document.js","names":["basePrototype","primaryPath","_this","isInstanceOfRxDocument","undefined","collection","schema","primary","_data","revision","_rev","deleted$","$","pipe","map","d","_deleted","deleted","getLatest","latestDocData","_docCache","getLatestDocumentData","getCachedRxDocument","filter","changeEvent","isLocal","documentId","getDocumentDataOfRxChangeEvent","startWith","distinctUntilChanged","prev","curr","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","get$","path","overwritable","isDevMode","includes","newRxError","finalFields","schemaObj","getSchemaByObjectPath","jsonSchema","data","objectPath","get","populate","value","PROMISE_RESOLVE_NULL","ref","refCollection","database","collections","type","findByIds","exec","then","res","valuesIterator","values","Array","from","findOne","objPath","valueObj","isArray","deepFreezeWhenDevMode","clone","defineGetterSetter","toJSON","withMetaFields","flatClone","_attachments","_meta","toMutableJSON","update","_updateObj","pluginMissing","incrementalUpdate","updateCRDT","putAttachment","getAttachment","allAttachments","allAttachments$","modify","mutationFunction","_context","oldData","modifierFromPublicToInternal","newData","_saveData","incrementalModify","incrementalWriteQueue","addWrite","result","patch","Object","entries","forEach","k","v","incrementalPatch","docData","id","document","beforeDocumentUpdateWrite","storageInstance","bulkWrite","previous","writeResult","isError","error","throwIfIsStorageWriteError","_runHooks","getFromObjectOrThrow","success","remove","Promise","reject","deletedData","removedDocData","removed","incrementalRemove","newDoc","destroy","createRxDocumentConstructor","proto","constructor","RxDocumentConstructor","prototype","thisObj","pathProperties","properties","keys","key","fullPath","trimDots","__defineGetter__","ret","defineProperty","enumerable","configurable","__defineSetter__","val","set","createWithConstructor","jsonData","doc","runPluginHooks","isRxDocument","obj","assign","validateChange"],"sources":["../../src/rx-document.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport {\n Observable\n} from 'rxjs';\nimport {\n distinctUntilChanged,\n filter,\n map,\n shareReplay,\n startWith\n} from 'rxjs/operators';\nimport {\n clone,\n trimDots,\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_NULL,\n RXJS_SHARE_REPLAY_DEFAULTS,\n getFromObjectOrThrow\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\n\nimport type {\n RxDocument,\n RxCollection,\n RxDocumentData,\n RxDocumentWriteData,\n UpdateQuery,\n CRDTEntry,\n ModifyFunction\n} from './types';\nimport { getDocumentDataOfRxChangeEvent } from './rx-change-event';\nimport { overwritable } from './overwritable';\nimport { getSchemaByObjectPath } from './rx-schema-helper';\nimport { throwIfIsStorageWriteError } from './rx-storage-helper';\nimport { modifierFromPublicToInternal } from './incremental-write';\n\nexport const basePrototype = {\n get primaryPath() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this.collection.schema.primaryPath;\n },\n get primary() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return (_this._data as any)[_this.primaryPath];\n },\n get revision() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._rev;\n },\n get deleted$() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this.$.pipe(\n map((d: any) => d._deleted)\n );\n },\n get deleted() {\n const _this: RxDocument = this as any;\n if (!_this.isInstanceOfRxDocument) {\n return undefined;\n }\n return _this._data._deleted;\n },\n\n getLatest(this: RxDocument): RxDocument {\n const latestDocData = this.collection._docCache.getLatestDocumentData(this.primary);\n return this.collection._docCache.getCachedRxDocument(latestDocData);\n },\n\n /**\n * returns the observable which emits the plain-data of this document\n */\n get $(): Observable> {\n const _this: RxDocument = this as any;\n return _this.collection.$.pipe(\n filter(changeEvent => !changeEvent.isLocal),\n filter(changeEvent => changeEvent.documentId === this.primary),\n map(changeEvent => getDocumentDataOfRxChangeEvent(changeEvent)),\n startWith(_this.collection._docCache.getLatestDocumentData(this.primary)),\n distinctUntilChanged((prev, curr) => prev._rev === curr._rev),\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n },\n\n /**\n * returns observable of the value of the given path\n */\n get$(this: RxDocument, path: string): Observable {\n if (overwritable.isDevMode()) {\n if (path.includes('.item.')) {\n throw newRxError('DOC1', {\n path\n });\n }\n\n if (path === this.primaryPath) {\n throw newRxError('DOC2');\n }\n\n // final fields cannot be modified and so also not observed\n if (this.collection.schema.finalFields.includes(path)) {\n throw newRxError('DOC3', {\n path\n });\n }\n\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n if (!schemaObj) {\n throw newRxError('DOC4', {\n path\n });\n }\n }\n\n return this.$\n .pipe(\n map(data => objectPath.get(data, path)),\n distinctUntilChanged()\n );\n },\n\n /**\n * populate the given path\n */\n populate(this: RxDocument, path: string): Promise {\n const schemaObj = getSchemaByObjectPath(\n this.collection.schema.jsonSchema,\n path\n );\n const value = this.get(path);\n if (!value) {\n return PROMISE_RESOLVE_NULL;\n }\n if (!schemaObj) {\n throw newRxError('DOC5', {\n path\n });\n }\n if (!schemaObj.ref) {\n throw newRxError('DOC6', {\n path,\n schemaObj\n });\n }\n\n const refCollection: RxCollection = this.collection.database.collections[schemaObj.ref];\n if (!refCollection) {\n throw newRxError('DOC7', {\n ref: schemaObj.ref,\n path,\n schemaObj\n });\n }\n\n if (schemaObj.type === 'array') {\n return refCollection.findByIds(value).exec().then(res => {\n const valuesIterator = res.values();\n return Array.from(valuesIterator) as any;\n });\n } else {\n return refCollection.findOne(value).exec();\n }\n },\n\n /**\n * get data by objectPath\n */\n get(this: RxDocument, objPath: string): any | null {\n if (!this._data) return undefined;\n let valueObj = objectPath.get(this._data, objPath);\n\n // direct return if array or non-object\n if (\n typeof valueObj !== 'object' ||\n Array.isArray(valueObj)\n ) {\n return overwritable.deepFreezeWhenDevMode(valueObj);\n }\n\n /**\n * TODO find a way to deep-freeze together with defineGetterSetter\n * so we do not have to do a deep clone here.\n */\n valueObj = clone(valueObj);\n defineGetterSetter(\n this.collection.schema,\n valueObj,\n objPath,\n this as any\n );\n return valueObj;\n },\n\n toJSON(this: RxDocument, withMetaFields = false) {\n if (!withMetaFields) {\n const data = flatClone(this._data);\n delete (data as any)._rev;\n delete (data as any)._attachments;\n delete (data as any)._deleted;\n delete (data as any)._meta;\n return overwritable.deepFreezeWhenDevMode(data);\n } else {\n return overwritable.deepFreezeWhenDevMode(this._data);\n }\n },\n toMutableJSON(this: RxDocument, withMetaFields = false) {\n return clone(this.toJSON(withMetaFields as any));\n },\n\n /**\n * updates document\n * @overwritten by plugin (optional)\n * @param updateObj mongodb-like syntax\n */\n update(_updateObj: UpdateQuery) {\n throw pluginMissing('update');\n },\n incrementalUpdate(_updateObj: UpdateQuery) {\n throw pluginMissing('update');\n },\n updateCRDT(_updateObj: CRDTEntry | CRDTEntry[]) {\n throw pluginMissing('crdt');\n },\n putAttachment() {\n throw pluginMissing('attachments');\n },\n getAttachment() {\n throw pluginMissing('attachments');\n },\n allAttachments() {\n throw pluginMissing('attachments');\n },\n get allAttachments$() {\n throw pluginMissing('attachments');\n },\n\n async modify(\n this: RxDocument,\n mutationFunction: ModifyFunction,\n // used by some plugins that wrap the method\n _context?: string\n ): Promise {\n const oldData = this._data;\n const newData: RxDocumentData = await modifierFromPublicToInternal(mutationFunction)(oldData) as any;\n return this._saveData(newData, oldData) as any;\n },\n\n /**\n * runs an incremental update over the document\n * @param function that takes the document-data and returns a new data-object\n */\n incrementalModify(\n this: RxDocument,\n mutationFunction: ModifyFunction,\n // used by some plugins that wrap the method\n _context?: string\n ): Promise {\n return this.collection.incrementalWriteQueue.addWrite(\n this._data,\n modifierFromPublicToInternal(mutationFunction)\n ).then(result => this.collection._docCache.getCachedRxDocument(result));\n },\n\n patch(\n this: RxDocument,\n patch: Partial\n ) {\n const oldData = this._data;\n const newData = clone(oldData);\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n (newData as any)[k] = v;\n });\n return this._saveData(newData, oldData);\n },\n\n /**\n * patches the given properties\n */\n incrementalPatch(\n this: RxDocument,\n patch: Partial\n ): Promise> {\n return this.incrementalModify((docData) => {\n Object\n .entries(patch)\n .forEach(([k, v]) => {\n (docData as any)[k] = v;\n });\n return docData;\n });\n },\n\n /**\n * saves the new document-data\n * and handles the events\n */\n async _saveData(\n this: RxDocument,\n newData: RxDocumentWriteData,\n oldData: RxDocumentData\n ): Promise> {\n newData = flatClone(newData);\n\n // deleted documents cannot be changed\n if (this._data._deleted) {\n throw newRxError('DOC11', {\n id: this.primary,\n document: this\n });\n }\n await beforeDocumentUpdateWrite(this.collection, newData, oldData);\n const writeResult = await this.collection.storageInstance.bulkWrite([{\n previous: oldData,\n document: newData\n }], 'rx-document-save-data');\n\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(this.collection, this.primary, newData, isError);\n\n await this.collection._runHooks('post', 'save', newData, this);\n return this.collection._docCache.getCachedRxDocument(\n getFromObjectOrThrow(writeResult.success, this.primary)\n );\n },\n\n /**\n * Remove the document.\n * Notice that there is no hard delete,\n * instead deleted documents get flagged with _deleted=true.\n */\n remove(this: RxDocument): Promise {\n const collection = this.collection;\n if (this.deleted) {\n return Promise.reject(newRxError('DOC13', {\n document: this,\n id: this.primary\n }));\n }\n\n const deletedData = flatClone(this._data);\n let removedDocData: RxDocumentData;\n return collection._runHooks('pre', 'remove', deletedData, this)\n .then(async () => {\n deletedData._deleted = true;\n const writeResult = await collection.storageInstance.bulkWrite([{\n previous: this._data,\n document: deletedData\n }], 'rx-document-remove');\n const isError = writeResult.error[this.primary];\n throwIfIsStorageWriteError(collection, this.primary, deletedData, isError);\n return getFromObjectOrThrow(writeResult.success, this.primary);\n })\n .then((removed) => {\n removedDocData = removed;\n return this.collection._runHooks('post', 'remove', deletedData, this);\n })\n .then(() => {\n return this.collection._docCache.getCachedRxDocument(removedDocData);\n });\n },\n incrementalRemove(this: RxDocument): Promise {\n return this.incrementalModify(async (docData) => {\n await this.collection._runHooks('pre', 'remove', docData, this);\n docData._deleted = true;\n return docData;\n }).then(async (newDoc) => {\n await this.collection._runHooks('post', 'remove', newDoc._data, newDoc);\n return newDoc;\n });\n },\n destroy() {\n throw newRxError('DOC14');\n }\n};\n\nexport function createRxDocumentConstructor(proto = basePrototype) {\n const constructor = function RxDocumentConstructor(\n this: RxDocument,\n collection: RxCollection,\n docData: RxDocumentData\n ) {\n this.collection = collection;\n\n // assume that this is always equal to the doc-data in the database\n this._data = docData;\n\n /**\n * because of the prototype-merge,\n * we can not use the native instanceof operator\n */\n this.isInstanceOfRxDocument = true;\n };\n constructor.prototype = proto;\n return constructor;\n}\n\nexport function defineGetterSetter(\n schema: any,\n valueObj: any,\n objPath = '',\n thisObj = false\n) {\n if (valueObj === null) return;\n\n\n let pathProperties = getSchemaByObjectPath(\n schema.jsonSchema,\n objPath\n );\n\n if (typeof pathProperties === 'undefined') return;\n if (pathProperties.properties) pathProperties = pathProperties.properties;\n\n Object.keys(pathProperties)\n .forEach(key => {\n const fullPath = trimDots(objPath + '.' + key);\n\n // getter - value\n valueObj.__defineGetter__(\n key,\n function (this: RxDocument) {\n const _this: RxDocument = thisObj ? thisObj : (this as any);\n if (!_this.get || typeof _this.get !== 'function') {\n /**\n * When an object gets added to the state of a vuejs-component,\n * it happens that this getter is called with another scope.\n * To prevent errors, we have to return undefined in this case\n */\n return undefined;\n }\n const ret = _this.get(fullPath);\n return ret;\n }\n );\n // getter - observable$\n Object.defineProperty(valueObj, key + '$', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.get$(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // getter - populate_\n Object.defineProperty(valueObj, key + '_', {\n get: function () {\n const _this = thisObj ? thisObj : this;\n return _this.populate(fullPath);\n },\n enumerable: false,\n configurable: false\n });\n // setter - value\n valueObj.__defineSetter__(key, function (\n this: RxDocument,\n val: any\n ) {\n const _this: any = thisObj ? thisObj : this;\n return _this.set(fullPath, val);\n });\n });\n}\n\nexport function createWithConstructor(\n constructor: any,\n collection: RxCollection,\n jsonData: RxDocumentData\n): RxDocument | null {\n const doc = new constructor(collection, jsonData);\n runPluginHooks('createRxDocument', doc);\n return doc;\n}\n\nexport function isRxDocument(obj: any): boolean {\n if (typeof obj === 'undefined') return false;\n return !!obj.isInstanceOfRxDocument;\n}\n\n\nexport function beforeDocumentUpdateWrite(\n collection: RxCollection,\n newData: RxDocumentWriteData,\n oldData: RxDocumentData\n): Promise {\n /**\n * Meta values must always be merged\n * instead of overwritten.\n * This ensures that different plugins do not overwrite\n * each others meta properties.\n */\n newData._meta = Object.assign(\n {},\n oldData._meta,\n newData._meta\n );\n\n // ensure modifications are ok\n if (overwritable.isDevMode()) {\n collection.schema.validateChange(oldData, newData);\n }\n return collection._runHooks('pre', 'save', newData);\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAIA;AAOA;AASA;AAGA;AAaA;AACA;AACA;AACA;AACA;AAEO,IAAMA,aAAa,GAAG;EACzB,IAAIC,WAAW,GAAG;IACd,IAAMC,KAAiB,GAAG,IAAW;IACrC,IAAI,CAACA,KAAK,CAACC,sBAAsB,EAAE;MAC/B,OAAOC,SAAS;IACpB;IACA,OAAOF,KAAK,CAACG,UAAU,CAACC,MAAM,CAACL,WAAW;EAC9C,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,GAAQ,EACV;MACE,IAAM9I,KAAU,GAAGiI,OAAO,GAAGA,OAAO,GAAG,IAAI;MAC3C,OAAOjI,KAAK,CAAC+I,GAAG,CAACT,QAAQ,EAAEQ,GAAG,CAAC;IACnC,CAAC,CAAC;EACN,CAAC,CAAC;AACV;AAEO,SAASE,qBAAqB,CACjClB,WAAgB,EAChB3H,UAAmC,EACnC8I,QAAmC,EACP;EAC5B,IAAMC,GAAG,GAAG,IAAIpB,WAAW,CAAC3H,UAAU,EAAE8I,QAAQ,CAAC;EACjD,IAAAE,qBAAc,EAAC,kBAAkB,EAAED,GAAG,CAAC;EACvC,OAAOA,GAAG;AACd;AAEO,SAASE,YAAY,CAACC,GAAQ,EAAW;EAC5C,IAAI,OAAOA,GAAG,KAAK,WAAW,EAAE,OAAO,KAAK;EAC5C,OAAO,CAAC,CAACA,GAAG,CAACpJ,sBAAsB;AACvC;AAGO,SAASuG,yBAAyB,CACrCrG,UAAmC,EACnCqF,OAAuC,EACvCF,OAAkC,EACtB;EACZ;AACJ;AACA;AACA;AACA;AACA;EACIE,OAAO,CAAChB,KAAK,GAAGuB,MAAM,CAACuD,MAAM,CACzB,CAAC,CAAC,EACFhE,OAAO,CAACd,KAAK,EACbgB,OAAO,CAAChB,KAAK,CAChB;;EAED;EACA,IAAItC,0BAAY,CAACC,SAAS,EAAE,EAAE;IAC1BhC,UAAU,CAACC,MAAM,CAACmJ,cAAc,CAACjE,OAAO,EAAEE,OAAO,CAAC;EACtD;EACA,OAAOrF,UAAU,CAAC6G,SAAS,CAAC,KAAK,EAAE,MAAM,EAAExB,OAAO,CAAC;AACvD"} \ No newline at end of file diff --git a/dist/lib/rx-error.js b/dist/lib/rx-error.js index a35c7792bd7..282e62ddc4a 100644 --- a/dist/lib/rx-error.js +++ b/dist/lib/rx-error.js @@ -8,6 +8,7 @@ exports.RxTypeError = exports.RxError = void 0; exports.isBulkWriteConflictError = isBulkWriteConflictError; exports.newRxError = newRxError; exports.newRxTypeError = newRxTypeError; +exports.rxStorageWriteErrorToRxError = rxStorageWriteErrorToRxError; var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); @@ -40,6 +41,8 @@ function messageForError(message, code, parameters) { } var RxError = /*#__PURE__*/function (_Error) { (0, _inheritsLoose2["default"])(RxError, _Error); + // always true, use this to detect if its an rxdb-error + function RxError(code, message) { var _this; var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -71,6 +74,8 @@ var RxError = /*#__PURE__*/function (_Error) { exports.RxError = RxError; var RxTypeError = /*#__PURE__*/function (_TypeError) { (0, _inheritsLoose2["default"])(RxTypeError, _TypeError); + // always true, use this to detect if its an rxdb-error + function RxTypeError(code, message) { var _this2; var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -112,10 +117,22 @@ function newRxTypeError(code, parameters) { * return false if it is another error. */ function isBulkWriteConflictError(err) { - if (err.status === 409) { + if (err && err.status === 409) { return err; } else { return false; } } +var STORAGE_WRITE_ERROR_CODE_TO_MESSAGE = { + 409: 'document write conflict', + 422: 'schema validation error', + 510: 'attachment data missing' +}; +function rxStorageWriteErrorToRxError(err) { + return newRxError('COL20', { + name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status], + document: err.documentId, + writeError: err + }); +} //# sourceMappingURL=rx-error.js.map \ No newline at end of file diff --git a/dist/lib/rx-error.js.map b/dist/lib/rx-error.js.map index 6f75ad64f78..4679c0ebc7c 100644 --- a/dist/lib/rx-error.js.map +++ b/dist/lib/rx-error.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.js","names":["parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","JSON","stringify","_k","v","undefined","e","join","messageForError","message","code","RxError","mes","rxdb","toString","Error","RxTypeError","TypeError","newRxError","overwritable","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","err","status"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageBulkWriteError\n} from './types';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n paramStr = JSON.stringify(\n parameters[k],\n (_k, v) => v === undefined ? null : v,\n 2\n );\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err: RxStorageBulkWriteError | any\n): RxStorageBulkWriteError | false {\n if (\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAIA;AAJA;AACA;AACA;;AASA;AACA;AACA;AACA,SAASA,kBAAkB,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GAAG,CAAC,UAAAC,CAAC,EAAI;IACN,IAAIC,QAAQ,GAAG,iBAAiB;IAChC,IAAI;MACAA,QAAQ,GAAGC,IAAI,CAACC,SAAS,CACrBT,UAAU,CAACM,CAAC,CAAC,EACb,UAACI,EAAE,EAAEC,CAAC;QAAA,OAAKA,CAAC,KAAKC,SAAS,GAAG,IAAI,GAAGD,CAAC;MAAA,GACrC,CAAC,CACJ;IACL,CAAC,CAAC,OAAOE,CAAC,EAAE,CAAE;IACd,OAAOP,CAAC,GAAG,GAAG,GAAGC,QAAQ;EAC7B,CAAC,CAAC,CACDO,IAAI,CAAC,IAAI,CAAC;EACfb,GAAG,IAAI,GAAG;EACV,OAAOA,GAAG;AACd;AAEA,SAASc,eAAe,CACpBC,OAAe,EACfC,IAAY,EACZjB,UAAe,EACT;EACN,OAAO,WAAW,GAAGiB,IAAI,GAAG,IAAI,GAAG,IAAI,GACnCD,OAAO,GAAG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;IAC5C;EAAC;IAAA;IAAA,KAID,eAAyB;MACrB,OAAO,IAAI;IACf;EAAC;EAAA;AAAA,kDAzB4BO,SAAS;AAAA;AA4BnC,SAASC,UAAU,CACtBR,IAAgB,EAChBjB,UAA8B,EACvB;EACP,OAAO,IAAIkB,OAAO,CACdD,IAAI,EACJS,0BAAY,CAACC,kBAAkB,CAACV,IAAI,CAAC,EACrCjB,UAAU,CACb;AACL;AAEO,SAAS4B,cAAc,CAC1BX,IAAgB,EAChBjB,UAA8B,EACnB;EACX,OAAO,IAAIuB,WAAW,CAClBN,IAAI,EACJS,0BAAY,CAACC,kBAAkB,CAACV,IAAI,CAAC,EACrCjB,UAAU,CACb;AACL;;AAGA;AACA;AACA;AACA;AACO,SAAS6B,wBAAwB,CACpCC,GAA6C,EACH;EAC1C,IACIA,GAAG,CAACC,MAAM,KAAK,GAAG,EACpB;IACE,OAAOD,GAAG;EACd,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file +{"version":3,"file":"rx-error.js","names":["parametersToString","parameters","ret","Object","keys","length","map","k","paramStr","JSON","stringify","_k","v","undefined","e","join","messageForError","message","code","RxError","mes","rxdb","toString","Error","RxTypeError","TypeError","newRxError","overwritable","tunnelErrorMessage","newRxTypeError","isBulkWriteConflictError","err","status","STORAGE_WRITE_ERROR_CODE_TO_MESSAGE","rxStorageWriteErrorToRxError","name","document","documentId","writeError"],"sources":["../../src/rx-error.ts"],"sourcesContent":["/**\n * here we use custom errors with the additional field 'parameters'\n */\n\nimport { overwritable } from './overwritable';\nimport type {\n RxErrorParameters,\n RxErrorKey,\n RxStorageWriteError,\n RxStorageWriteErrorConflict\n} from './types';\n\n/**\n * transform an object of parameters to a presentable string\n */\nfunction parametersToString(parameters: any): string {\n let ret = '';\n if (Object.keys(parameters).length === 0)\n return ret;\n ret += 'Given parameters: {\\n';\n ret += Object.keys(parameters)\n .map(k => {\n let paramStr = '[object Object]';\n try {\n paramStr = JSON.stringify(\n parameters[k],\n (_k, v) => v === undefined ? null : v,\n 2\n );\n } catch (e) { }\n return k + ':' + paramStr;\n })\n .join('\\n');\n ret += '}';\n return ret;\n}\n\nfunction messageForError(\n message: string,\n code: string,\n parameters: any\n): string {\n return 'RxError (' + code + '):' + '\\n' +\n message + '\\n' +\n parametersToString(parameters);\n}\n\nexport class RxError extends Error {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return false;\n }\n}\n\nexport class RxTypeError extends TypeError {\n public code: RxErrorKey;\n public message: string;\n public parameters: RxErrorParameters;\n // always true, use this to detect if its an rxdb-error\n public rxdb: true;\n constructor(\n code: RxErrorKey,\n message: string,\n parameters: RxErrorParameters = {}\n ) {\n const mes = messageForError(message, code, parameters);\n super(mes);\n this.code = code;\n this.message = mes;\n this.parameters = parameters;\n this.rxdb = true; // tag them as internal\n }\n get name(): string {\n return 'RxTypeError (' + this.code + ')';\n }\n toString(): string {\n return this.message;\n }\n get typeError(): boolean {\n return true;\n }\n}\n\nexport function newRxError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxError {\n return new RxError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\nexport function newRxTypeError(\n code: RxErrorKey,\n parameters?: RxErrorParameters\n): RxTypeError {\n return new RxTypeError(\n code,\n overwritable.tunnelErrorMessage(code),\n parameters\n );\n}\n\n\n/**\n * Returns the error if it is a 409 conflict,\n * return false if it is another error.\n */\nexport function isBulkWriteConflictError(\n err?: RxStorageWriteError | any\n): RxStorageWriteErrorConflict | false {\n if (\n err &&\n err.status === 409\n ) {\n return err;\n } else {\n return false;\n }\n}\n\n\nconst STORAGE_WRITE_ERROR_CODE_TO_MESSAGE: { [k: number]: string; } = {\n 409: 'document write conflict',\n 422: 'schema validation error',\n 510: 'attachment data missing'\n};\n\nexport function rxStorageWriteErrorToRxError(err: RxStorageWriteError): RxError {\n return newRxError('COL20', {\n name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status],\n document: err.documentId,\n writeError: err\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA;AAJA;AACA;AACA;;AAUA;AACA;AACA;AACA,SAASA,kBAAkB,CAACC,UAAe,EAAU;EACjD,IAAIC,GAAG,GAAG,EAAE;EACZ,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CAACI,MAAM,KAAK,CAAC,EACpC,OAAOH,GAAG;EACdA,GAAG,IAAI,uBAAuB;EAC9BA,GAAG,IAAIC,MAAM,CAACC,IAAI,CAACH,UAAU,CAAC,CACzBK,GAAG,CAAC,UAAAC,CAAC,EAAI;IACN,IAAIC,QAAQ,GAAG,iBAAiB;IAChC,IAAI;MACAA,QAAQ,GAAGC,IAAI,CAACC,SAAS,CACrBT,UAAU,CAACM,CAAC,CAAC,EACb,UAACI,EAAE,EAAEC,CAAC;QAAA,OAAKA,CAAC,KAAKC,SAAS,GAAG,IAAI,GAAGD,CAAC;MAAA,GACrC,CAAC,CACJ;IACL,CAAC,CAAC,OAAOE,CAAC,EAAE,CAAE;IACd,OAAOP,CAAC,GAAG,GAAG,GAAGC,QAAQ;EAC7B,CAAC,CAAC,CACDO,IAAI,CAAC,IAAI,CAAC;EACfb,GAAG,IAAI,GAAG;EACV,OAAOA,GAAG;AACd;AAEA,SAASc,eAAe,CACpBC,OAAe,EACfC,IAAY,EACZjB,UAAe,EACT;EACN,OAAO,WAAW,GAAGiB,IAAI,GAAG,IAAI,GAAG,IAAI,GACnCD,OAAO,GAAG,IAAI,GACdjB,kBAAkB,CAACC,UAAU,CAAC;AACtC;AAAC,IAEYkB,OAAO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AAI;IACf;EAAC;EAAA;AAAA,kDA1B4BO,SAAS;AAAA;AA6BnC,SAASC,UAAU,CACtBR,IAAgB,EAChBjB,UAA8B,EACvB;EACP,OAAO,IAAIkB,OAAO,CACdD,IAAI,EACJS,0BAAY,CAACC,kBAAkB,CAACV,IAAI,CAAC,EACrCjB,UAAU,CACb;AACL;AAEO,SAAS4B,cAAc,CAC1BX,IAAgB,EAChBjB,UAA8B,EACnB;EACX,OAAO,IAAIuB,WAAW,CAClBN,IAAI,EACJS,0BAAY,CAACC,kBAAkB,CAACV,IAAI,CAAC,EACrCjB,UAAU,CACb;AACL;;AAGA;AACA;AACA;AACA;AACO,SAAS6B,wBAAwB,CACpCC,GAA0C,EACI;EAC9C,IACIA,GAAG,IACHA,GAAG,CAACC,MAAM,KAAK,GAAG,EACpB;IACE,OAAOD,GAAG;EACd,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ;AAGA,IAAME,mCAA6D,GAAG;EAClE,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE,yBAAyB;EAC9B,GAAG,EAAE;AACT,CAAC;AAEM,SAASC,4BAA4B,CAACH,GAA6B,EAAW;EACjF,OAAOL,UAAU,CAAC,OAAO,EAAE;IACvBS,IAAI,EAAEF,mCAAmC,CAACF,GAAG,CAACC,MAAM,CAAC;IACrDI,QAAQ,EAAEL,GAAG,CAACM,UAAU;IACxBC,UAAU,EAAEP;EAChB,CAAC,CAAC;AACN"} \ No newline at end of file diff --git a/dist/lib/rx-query-helper.js b/dist/lib/rx-query-helper.js index 90dcca70d2f..ebc4ecac986 100644 --- a/dist/lib/rx-query-helper.js +++ b/dist/lib/rx-query-helper.js @@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", { exports.normalizeMangoQuery = normalizeMangoQuery; var _queryPlanner = require("./query-planner"); var _rxSchemaHelper = require("./rx-schema-helper"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * Normalize the query to ensure we have all fields set * and queries that represent the same query logic are detected as equal by the caching. */ function normalizeMangoQuery(schema, mangoQuery) { var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var normalizedMangoQuery = (0, _util.clone)(mangoQuery); + var normalizedMangoQuery = (0, _utils.clone)(mangoQuery); if (typeof normalizedMangoQuery.skip !== 'number') { normalizedMangoQuery.skip = 0; } @@ -52,7 +52,7 @@ function normalizeMangoQuery(schema, mangoQuery) { * the primaryKey is inside of it. */ if (normalizedMangoQuery.index) { - var indexAr = Array.isArray(normalizedMangoQuery.index) ? normalizedMangoQuery.index.slice(0) : [normalizedMangoQuery.index]; + var indexAr = (0, _utils.toArray)(normalizedMangoQuery.index); if (!indexAr.includes(primaryKey)) { indexAr.push(primaryKey); } @@ -105,7 +105,7 @@ function normalizeMangoQuery(schema, mangoQuery) { var currentFieldsAmount = -1; var currentBestIndexForSort; schema.indexes.forEach(function (index) { - var useIndex = (0, _util.isMaybeReadonlyArray)(index) ? index : [index]; + var useIndex = (0, _utils.isMaybeReadonlyArray)(index) ? index : [index]; var firstWrongIndex = useIndex.findIndex(function (indexField) { return !fieldsWithLogicalOperator.has(indexField); }); @@ -133,7 +133,7 @@ function normalizeMangoQuery(schema, mangoQuery) { } } else { var isPrimaryInSort = normalizedMangoQuery.sort.find(function (p) { - return (0, _util.firstPropertyNameOfObject)(p) === primaryKey; + return (0, _utils.firstPropertyNameOfObject)(p) === primaryKey; }); if (!isPrimaryInSort) { var _normalizedMangoQuery; diff --git a/dist/lib/rx-query-helper.js.map b/dist/lib/rx-query-helper.js.map index fb23255e239..ddd4fac9bf5 100644 --- a/dist/lib/rx-query-helper.js.map +++ b/dist/lib/rx-query-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query-helper.js","names":["normalizeMangoQuery","schema","mangoQuery","primaryKey","getPrimaryFieldOfPrimaryKey","normalizedMangoQuery","clone","skip","selector","Object","entries","forEach","field","matcher","$eq","index","indexAr","Array","isArray","slice","includes","push","sort","map","indexes","fieldsWithLogicalOperator","Set","hasLogical","keys","find","operator","LOGICAL_OPERATORS","has","add","currentFieldsAmount","currentBestIndexForSort","useIndex","isMaybeReadonlyArray","firstWrongIndex","findIndex","indexField","isPrimaryInSort","p","firstPropertyNameOfObject"],"sources":["../../src/rx-query-helper.ts"],"sourcesContent":["import { LOGICAL_OPERATORS } from './query-planner';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n clone,\n firstPropertyNameOfObject,\n isMaybeReadonlyArray\n} from './util';\n\n/**\n * Normalize the query to ensure we have all fields set\n * and queries that represent the same query logic are detected as equal by the caching.\n */\nexport function normalizeMangoQuery(\n schema: RxJsonSchema>,\n mangoQuery: MangoQuery\n): FilledMangoQuery {\n const primaryKey: string = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const normalizedMangoQuery: FilledMangoQuery = clone(mangoQuery) as any;\n\n if (typeof normalizedMangoQuery.skip !== 'number') {\n normalizedMangoQuery.skip = 0;\n }\n\n if (!normalizedMangoQuery.selector) {\n normalizedMangoQuery.selector = {};\n } else {\n normalizedMangoQuery.selector = normalizedMangoQuery.selector;\n /**\n * In mango query, it is possible to have an\n * equals comparison by directly assigning a value\n * to a property, without the '$eq' operator.\n * Like:\n * selector: {\n * foo: 'bar'\n * }\n * For normalization, we have to normalize this\n * so our checks can perform properly.\n *\n *\n * TODO this must work recursive with nested queries that\n * contain multiple selectors via $and or $or etc.\n */\n Object\n .entries(normalizedMangoQuery.selector)\n .forEach(([field, matcher]) => {\n if (typeof matcher !== 'object' || matcher === null) {\n normalizedMangoQuery.selector[field] = {\n $eq: matcher\n };\n }\n });\n }\n\n /**\n * Ensure that if an index is specified,\n * the primaryKey is inside of it.\n */\n if (normalizedMangoQuery.index) {\n const indexAr = Array.isArray(normalizedMangoQuery.index) ? normalizedMangoQuery.index.slice(0) : [normalizedMangoQuery.index];\n if (!indexAr.includes(primaryKey)) {\n indexAr.push(primaryKey);\n }\n normalizedMangoQuery.index = indexAr;\n }\n\n /**\n * To ensure a deterministic sorting,\n * we have to ensure the primary key is always part\n * of the sort query.\n * Primary sorting is added as last sort parameter,\n * similar to how we add the primary key to indexes that do not have it.\n *\n */\n if (!normalizedMangoQuery.sort) {\n /**\n * If no sort is given at all,\n * we can assume that the user does not care about sort order at al.\n *\n * we cannot just use the primary key as sort parameter\n * because it would likely cause the query to run over the primary key index\n * which has a bad performance in most cases.\n */\n if (normalizedMangoQuery.index) {\n normalizedMangoQuery.sort = normalizedMangoQuery.index.map((field: string) => ({ [field as any]: 'asc' } as any));\n } else {\n /**\n * Find the index that best matches the fields with the logical operators\n */\n if (schema.indexes) {\n const fieldsWithLogicalOperator: Set = new Set();\n Object.entries(normalizedMangoQuery.selector).forEach(([field, matcher]) => {\n let hasLogical = false;\n if (typeof matcher === 'object' && matcher !== null) {\n hasLogical = !!Object.keys(matcher).find(operator => LOGICAL_OPERATORS.has(operator));\n } else {\n hasLogical = true;\n }\n if (hasLogical) {\n fieldsWithLogicalOperator.add(field);\n }\n });\n\n\n let currentFieldsAmount = -1;\n let currentBestIndexForSort: string[] | readonly string[] | undefined;\n schema.indexes.forEach(index => {\n const useIndex = isMaybeReadonlyArray(index) ? index : [index];\n const firstWrongIndex = useIndex.findIndex(indexField => !fieldsWithLogicalOperator.has(indexField));\n if (\n firstWrongIndex > 0 &&\n firstWrongIndex > currentFieldsAmount\n ) {\n currentFieldsAmount = firstWrongIndex;\n currentBestIndexForSort = useIndex;\n }\n });\n if (currentBestIndexForSort) {\n normalizedMangoQuery.sort = currentBestIndexForSort.map((field: string) => ({ [field as any]: 'asc' } as any));\n }\n\n }\n\n /**\n * Fall back to the primary key as sort order\n * if no better one has been found\n */\n if (!normalizedMangoQuery.sort) {\n normalizedMangoQuery.sort = [{ [primaryKey]: 'asc' }] as any;\n }\n }\n } else {\n const isPrimaryInSort = normalizedMangoQuery.sort\n .find(p => firstPropertyNameOfObject(p) === primaryKey);\n if (!isPrimaryInSort) {\n normalizedMangoQuery.sort = normalizedMangoQuery.sort.slice(0);\n normalizedMangoQuery.sort.push({ [primaryKey]: 'asc' } as any);\n }\n }\n\n return normalizedMangoQuery;\n}\n"],"mappings":";;;;;;AAAA;AACA;AAOA;AAMA;AACA;AACA;AACA;AACO,SAASA,mBAAmB,CAC/BC,MAA+C,EAC/CC,UAAiC,EACN;EAC3B,IAAMC,UAAkB,GAAG,IAAAC,2CAA2B,EAACH,MAAM,CAACE,UAAU,CAAC;EACzE,IAAME,oBAAiD,GAAG,IAAAC,WAAK,EAACJ,UAAU,CAAQ;EAElF,IAAI,OAAOG,oBAAoB,CAACE,IAAI,KAAK,QAAQ,EAAE;IAC/CF,oBAAoB,CAACE,IAAI,GAAG,CAAC;EACjC;EAEA,IAAI,CAACF,oBAAoB,CAACG,QAAQ,EAAE;IAChCH,oBAAoB,CAACG,QAAQ,GAAG,CAAC,CAAC;EACtC,CAAC,MAAM;IACHH,oBAAoB,CAACG,QAAQ,GAAGH,oBAAoB,CAACG,QAAQ;IAC7D;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;IACQC,MAAM,CACDC,OAAO,CAACL,oBAAoB,CAACG,QAAQ,CAAC,CACtCG,OAAO,CAAC,gBAAsB;MAAA,IAApBC,KAAK;QAAEC,OAAO;MACrB,IAAI,OAAOA,OAAO,KAAK,QAAQ,IAAIA,OAAO,KAAK,IAAI,EAAE;QACjDR,oBAAoB,CAACG,QAAQ,CAACI,KAAK,CAAC,GAAG;UACnCE,GAAG,EAAED;QACT,CAAC;MACL;IACJ,CAAC,CAAC;EACV;;EAEA;AACJ;AACA;AACA;EACI,IAAIR,oBAAoB,CAACU,KAAK,EAAE;IAC5B,IAAMC,OAAO,GAAGC,KAAK,CAACC,OAAO,CAACb,oBAAoB,CAACU,KAAK,CAAC,GAAGV,oBAAoB,CAACU,KAAK,CAACI,KAAK,CAAC,CAAC,CAAC,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names":["normalizeMangoQuery","schema","mangoQuery","primaryKey","getPrimaryFieldOfPrimaryKey","normalizedMangoQuery","clone","skip","selector","Object","entries","forEach","field","matcher","$eq","index","indexAr","toArray","includes","push","sort","map","indexes","fieldsWithLogicalOperator","Set","hasLogical","keys","find","operator","LOGICAL_OPERATORS","has","add","currentFieldsAmount","currentBestIndexForSort","useIndex","isMaybeReadonlyArray","firstWrongIndex","findIndex","indexField","isPrimaryInSort","p","firstPropertyNameOfObject","slice"],"sources":["../../src/rx-query-helper.ts"],"sourcesContent":["import { LOGICAL_OPERATORS } from './query-planner';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper';\nimport type {\n FilledMangoQuery,\n MangoQuery,\n RxDocumentData,\n RxJsonSchema\n} from './types';\nimport {\n clone,\n firstPropertyNameOfObject,\n toArray,\n isMaybeReadonlyArray\n} from './plugins/utils';\n\n/**\n * Normalize the query to ensure we have all fields set\n * and queries that represent the same query logic are detected as equal by the caching.\n */\nexport function normalizeMangoQuery(\n schema: RxJsonSchema>,\n mangoQuery: MangoQuery\n): FilledMangoQuery {\n const primaryKey: string = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const normalizedMangoQuery: FilledMangoQuery = clone(mangoQuery) as any;\n\n if (typeof normalizedMangoQuery.skip !== 'number') {\n normalizedMangoQuery.skip = 0;\n }\n\n if (!normalizedMangoQuery.selector) {\n normalizedMangoQuery.selector = {};\n } else {\n normalizedMangoQuery.selector = normalizedMangoQuery.selector;\n /**\n * In mango query, it is possible to have an\n * equals comparison by directly assigning a value\n * to a property, without the '$eq' operator.\n * Like:\n * selector: {\n * foo: 'bar'\n * }\n * For normalization, we have to normalize this\n * so our checks can perform properly.\n *\n *\n * TODO this must work recursive with nested queries that\n * contain multiple selectors via $and or $or etc.\n */\n Object\n .entries(normalizedMangoQuery.selector)\n .forEach(([field, matcher]) => {\n if (typeof matcher !== 'object' || matcher === null) {\n (normalizedMangoQuery as any).selector[field] = {\n $eq: matcher\n };\n }\n });\n }\n\n /**\n * Ensure that if an index is specified,\n * the primaryKey is inside of it.\n */\n if (normalizedMangoQuery.index) {\n const indexAr = toArray(normalizedMangoQuery.index);\n if (!indexAr.includes(primaryKey)) {\n indexAr.push(primaryKey);\n }\n normalizedMangoQuery.index = indexAr;\n }\n\n /**\n * To ensure a deterministic sorting,\n * we have to ensure the primary key is always part\n * of the sort query.\n * Primary sorting is added as last sort parameter,\n * similar to how we add the primary key to indexes that do not have it.\n *\n */\n if (!normalizedMangoQuery.sort) {\n /**\n * If no sort is given at all,\n * we can assume that the user does not care about sort order at al.\n *\n * we cannot just use the primary key as sort parameter\n * because it would likely cause the query to run over the primary key index\n * which has a bad performance in most cases.\n */\n if (normalizedMangoQuery.index) {\n normalizedMangoQuery.sort = normalizedMangoQuery.index.map((field: string) => ({ [field as any]: 'asc' } as any));\n } else {\n /**\n * Find the index that best matches the fields with the logical operators\n */\n if (schema.indexes) {\n const fieldsWithLogicalOperator: Set = new Set();\n Object.entries(normalizedMangoQuery.selector).forEach(([field, matcher]) => {\n let hasLogical = false;\n if (typeof matcher === 'object' && matcher !== null) {\n hasLogical = !!Object.keys(matcher).find(operator => LOGICAL_OPERATORS.has(operator));\n } else {\n hasLogical = true;\n }\n if (hasLogical) {\n fieldsWithLogicalOperator.add(field);\n }\n });\n\n\n let currentFieldsAmount = -1;\n let currentBestIndexForSort: string[] | readonly string[] | undefined;\n schema.indexes.forEach(index => {\n const useIndex = isMaybeReadonlyArray(index) ? index : [index];\n const firstWrongIndex = useIndex.findIndex(indexField => !fieldsWithLogicalOperator.has(indexField));\n if (\n firstWrongIndex > 0 &&\n firstWrongIndex > currentFieldsAmount\n ) {\n currentFieldsAmount = firstWrongIndex;\n currentBestIndexForSort = useIndex;\n }\n });\n if (currentBestIndexForSort) {\n normalizedMangoQuery.sort = currentBestIndexForSort.map((field: string) => ({ [field as any]: 'asc' } as any));\n }\n\n }\n\n /**\n * Fall back to the primary key as sort order\n * if no better one has been found\n */\n if (!normalizedMangoQuery.sort) {\n normalizedMangoQuery.sort = [{ [primaryKey]: 'asc' }] as any;\n }\n }\n } else {\n const isPrimaryInSort = normalizedMangoQuery.sort\n .find(p => firstPropertyNameOfObject(p) === primaryKey);\n if (!isPrimaryInSort) {\n normalizedMangoQuery.sort = normalizedMangoQuery.sort.slice(0);\n normalizedMangoQuery.sort.push({ [primaryKey]: 'asc' } as any);\n }\n }\n\n return normalizedMangoQuery;\n}\n"],"mappings":";;;;;;AAAA;AACA;AAOA;AAOA;AACA;AACA;AACA;AACO,SAASA,mBAAmB,CAC/BC,MAA+C,EAC/CC,UAAiC,EACN;EAC3B,IAAMC,UAAkB,GAAG,IAAAC,2CAA2B,EAACH,MAAM,CAACE,UAAU,CAAC;EACzE,IAAME,oBAAiD,GAAG,IAAAC,YAAK,EAACJ,UAAU,CAAQ;EAElF,IAAI,OAAOG,oBAAoB,CAACE,IAAI,KAAK,QAAQ,EAAE;IAC/CF,oBAAoB,CAACE,IAAI,GAAG,CAAC;EACjC;EAEA,IAAI,CAACF,oBAAoB,CAACG,QAAQ,EAAE;IAChCH,oBAAoB,CAACG,QAAQ,GAAG,CAAC,CAAC;EACtC,CAAC,MAAM;IACHH,oBAAoB,CAACG,QAAQ,GAAGH,oBAAoB,CAACG,QAAQ;IAC7D;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;IACQC,MAAM,CACDC,OAAO,CAACL,oBAAoB,CAACG,QAAQ,CAAC,CACtCG,OAAO,CAAC,gBAAsB;MAAA,IAApBC,KAAK;QAAEC,OAAO;MACrB,IAAI,OAAOA,OAAO,KAAK,QAAQ,IAAIA,OAAO,KAAK,IAAI,EAAE;QAChDR,oBAAoB,CAASG,QAAQ,CAACI,KAAK,CAAC,GAAG;UAC5CE,GAAG,EAAED;QACT,CAAC;MACL;IACJ,CAAC,CAAC;EACV;;EAEA;AACJ;AACA;AACA;EACI,IAAIR,oBAAoB,CAACU,KAAK,EAAE;IAC5B,IAAMC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-mingo.js b/dist/lib/rx-query-mingo.js index 207979eb880..487321a55f2 100644 --- a/dist/lib/rx-query-mingo.js +++ b/dist/lib/rx-query-mingo.js @@ -6,7 +6,8 @@ Object.defineProperty(exports, "__esModule", { exports.getMingoQuery = getMingoQuery; var _core = require("mingo/core"); var _query = require("mingo/query"); -var _pipeline = require("mingo/operators/pipeline"); +var _sort = require("mingo/operators/pipeline/sort"); +var _project = require("mingo/operators/pipeline/project"); var _query2 = require("mingo/operators/query"); var mingoInitDone = false; @@ -20,8 +21,8 @@ var mingoInitDone = false; function getMingoQuery(selector) { if (!mingoInitDone) { (0, _core.useOperators)(_core.OperatorType.PIPELINE, { - $sort: _pipeline.$sort, - $project: _pipeline.$project + $sort: _sort.$sort, + $project: _project.$project }); (0, _core.useOperators)(_core.OperatorType.QUERY, { $and: _query2.$and, diff --git a/dist/lib/rx-query-mingo.js.map b/dist/lib/rx-query-mingo.js.map index eb97a3d2754..23decc13035 100644 --- a/dist/lib/rx-query-mingo.js.map +++ b/dist/lib/rx-query-mingo.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query-mingo.js","names":["mingoInitDone","getMingoQuery","selector","useOperators","OperatorType","PIPELINE","$sort","$project","QUERY","$and","$eq","$elemMatch","$exists","$gt","$gte","$in","$lt","$lte","$ne","$nin","$mod","$nor","$not","$or","$regex","$size","$type","Query"],"sources":["../../src/rx-query-mingo.ts"],"sourcesContent":["import { useOperators, OperatorType } from 'mingo/core';\nimport { Query } from 'mingo/query';\nimport type { MangoQuerySelector } from './types';\n\nimport { $sort, $project } from 'mingo/operators/pipeline';\nimport {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n} from 'mingo/operators/query';\n\nlet mingoInitDone = false;\n\n\n/**\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport function getMingoQuery(\n selector?: MangoQuerySelector\n) {\n if (!mingoInitDone) {\n\n useOperators(OperatorType.PIPELINE, {\n $sort,\n $project\n } as any);\n useOperators(OperatorType.QUERY, {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n } as any);\n mingoInitDone = true;\n }\n return new Query(selector as any);\n}\n"],"mappings":";;;;;;AAAA;AACA;AAGA;AACA;AAqBA,IAAIA,aAAa,GAAG,KAAK;;AAGzB;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,aAAa,CACzBC,QAAwC,EAC1C;EACE,IAAI,CAACF,aAAa,EAAE;IAEhB,IAAAG,kBAAY,EAACC,kBAAY,CAACC,QAAQ,EAAE;MAChCC,KAAK,EAALA,eAAK;MACLC,QAAQ,EAARA;IACJ,CAAC,CAAQ;IACT,IAAAJ,kBAAY,EAACC,kBAAY,CAACI,KAAK,EAAE;MAC7BC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,UAAU,EAAVA,kBAAU;MACVC,OAAO,EAAPA,eAAO;MACPC,GAAG,EAAHA,WAAG;MACHC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,GAAG,EAAHA,WAAG;MACHC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,IAAI,EAAJA,YAAI;MACJC,IAAI,EAAJA,YAAI;MACJC,IAAI,EAAJA,YAAI;MACJC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,MAAM,EAANA,cAAM;MACNC,KAAK,EAALA,aAAK;MACLC,KAAK,EAALA;IACJ,CAAC,CAAQ;IACT1B,aAAa,GAAG,IAAI;EACxB;EACA,OAAO,IAAI2B,YAAK,CAACzB,QAAQ,CAAQ;AACrC"} \ No newline at end of file +{"version":3,"file":"rx-query-mingo.js","names":["mingoInitDone","getMingoQuery","selector","useOperators","OperatorType","PIPELINE","$sort","$project","QUERY","$and","$eq","$elemMatch","$exists","$gt","$gte","$in","$lt","$lte","$ne","$nin","$mod","$nor","$not","$or","$regex","$size","$type","Query"],"sources":["../../src/rx-query-mingo.ts"],"sourcesContent":["import { useOperators, OperatorType } from 'mingo/core';\nimport { Query } from 'mingo/query';\nimport type { MangoQuerySelector } from './types';\n\nimport { $sort } from 'mingo/operators/pipeline/sort';\nimport { $project } from 'mingo/operators/pipeline/project';\nimport {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n} from 'mingo/operators/query';\n\nlet mingoInitDone = false;\n\n\n/**\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport function getMingoQuery(\n selector?: MangoQuerySelector\n) {\n if (!mingoInitDone) {\n\n useOperators(OperatorType.PIPELINE, {\n $sort,\n $project\n } as any);\n useOperators(OperatorType.QUERY, {\n $and,\n $eq,\n $elemMatch,\n $exists,\n $gt,\n $gte,\n $in,\n $lt,\n $lte,\n $ne,\n $nin,\n $mod,\n $nor,\n $not,\n $or,\n $regex,\n $size,\n $type,\n } as any);\n mingoInitDone = true;\n }\n return new Query(selector as any);\n}\n"],"mappings":";;;;;;AAAA;AACA;AAGA;AACA;AACA;AAqBA,IAAIA,aAAa,GAAG,KAAK;;AAGzB;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,aAAa,CACzBC,QAAwC,EAC1C;EACE,IAAI,CAACF,aAAa,EAAE;IAEhB,IAAAG,kBAAY,EAACC,kBAAY,CAACC,QAAQ,EAAE;MAChCC,KAAK,EAALA,WAAK;MACLC,QAAQ,EAARA;IACJ,CAAC,CAAQ;IACT,IAAAJ,kBAAY,EAACC,kBAAY,CAACI,KAAK,EAAE;MAC7BC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,UAAU,EAAVA,kBAAU;MACVC,OAAO,EAAPA,eAAO;MACPC,GAAG,EAAHA,WAAG;MACHC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,GAAG,EAAHA,WAAG;MACHC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,IAAI,EAAJA,YAAI;MACJC,IAAI,EAAJA,YAAI;MACJC,IAAI,EAAJA,YAAI;MACJC,IAAI,EAAJA,YAAI;MACJC,GAAG,EAAHA,WAAG;MACHC,MAAM,EAANA,cAAM;MACNC,KAAK,EAALA,aAAK;MACLC,KAAK,EAALA;IACJ,CAAC,CAAQ;IACT1B,aAAa,GAAG,IAAI;EACxB;EACA,OAAO,IAAI2B,YAAK,CAACzB,QAAQ,CAAQ;AACrC"} \ No newline at end of file diff --git a/dist/lib/rx-query.js b/dist/lib/rx-query.js index 6e4bf7b8324..f4d492d89cf 100644 --- a/dist/lib/rx-query.js +++ b/dist/lib/rx-query.js @@ -9,67 +9,19 @@ exports._getDefaultQuery = _getDefaultQuery; exports.createRxQuery = createRxQuery; exports.isFindOneByIdQuery = isFindOneByIdQuery; exports.isInstanceOf = isInstanceOf; -exports.queryCollection = void 0; +exports.queryCollection = queryCollection; exports.tunnelQueryCache = tunnelQueryCache; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _hooks = require("./hooks"); -var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); var _eventReduce = require("./event-reduce"); var _queryCache = require("./query-cache"); var _rxQueryHelper = require("./rx-query-helper"); -/** - * Runs the query over the storage instance - * of the collection. - * Does some optimizations to ensuer findById is used - * when specific queries are used. - */ -var queryCollection = function queryCollection(rxQuery) { - try { - var docs = []; - var _collection = rxQuery.collection; - - /** - * Optimizations shortcut. - * If query is find-one-document-by-id, - * then we do not have to use the slow query() method - * but instead can use findDocumentsById() - */ - var _temp = function () { - if (rxQuery.isFindOneByIdQuery) { - var docId = rxQuery.isFindOneByIdQuery; - return Promise.resolve(_collection.storageInstance.findDocumentsById([docId], false)).then(function (docsMap) { - var docData = docsMap[docId]; - if (docData) { - docs.push(docData); - } - }); - } else { - var preparedQuery = rxQuery.getPreparedQuery(); - return Promise.resolve(_collection.storageInstance.query(preparedQuery)).then(function (queryResult) { - docs = queryResult.documents; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return docs; - }) : docs); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Returns true if the given query - * selects exactly one document by its id. - * Used to optimize performance because these kind of - * queries do not have to run over an index and can use get-by-id instead. - * Returns false if no query of that kind. - * Returns the document id otherwise. - */ -exports.queryCollection = queryCollection; var _queryCount = 0; var newQueryID = function newQueryID() { return ++_queryCount; @@ -93,7 +45,7 @@ var RxQueryBase = /*#__PURE__*/function () { function RxQueryBase(op, mangoQuery, collection) { this.id = newQueryID(); this._execOverDatabaseCount = 0; - this._creationTime = (0, _util.now)(); + this._creationTime = (0, _utils.now)(); this._lastEnsureEqual = 0; this.other = {}; this.uncached = false; @@ -102,7 +54,7 @@ var RxQueryBase = /*#__PURE__*/function () { this._latestChangeEvent = -1; this._lastExecStart = 0; this._lastExecEnd = 0; - this._ensureEqualQueue = _util.PROMISE_RESOLVE_FALSE; + this._ensureEqualQueue = _utils.PROMISE_RESOLVE_FALSE; this.op = op; this.mangoQuery = mangoQuery; this.collection = collection; @@ -114,40 +66,46 @@ var RxQueryBase = /*#__PURE__*/function () { var _proto = RxQueryBase.prototype; /** * set the new result-data as result-docs of the query - * @param newResultData json-docs that were received from pouchdb + * @param newResultData json-docs that were received from the storage */ _proto._setResultData = function _setResultData(newResultData) { + var _this = this; if (typeof newResultData === 'number') { this._result = { docsData: [], + docsMap: new Map(), docsDataMap: new Map(), count: newResultData, docs: [], - time: (0, _util.now)() + time: (0, _utils.now)() }; return; + } else if (newResultData instanceof Map) { + newResultData = Array.from(newResultData.values()); } - var docs = (0, _rxDocumentPrototypeMerge.createRxDocuments)(this.collection, newResultData); + var docsDataMap = new Map(); + var docsMap = new Map(); + var docs = newResultData.map(function (docData) { + return _this.collection._docCache.getCachedRxDocument(docData); + }); /** * Instead of using the newResultData in the result cache, * we directly use the objects that are stored in the RxDocument * to ensure we do not store the same data twice and fill up the memory. */ - var primPath = this.collection.schema.primaryPath; - var docsDataMap = new Map(); var docsData = docs.map(function (doc) { - var docData = doc._dataSync$.getValue(); - var id = docData[primPath]; - docsDataMap.set(id, docData); - return docData; + docsDataMap.set(doc.primary, doc._data); + docsMap.set(doc.primary, doc); + return doc._data; }); this._result = { docsData: docsData, + docsMap: docsMap, docsDataMap: docsDataMap, count: docsData.length, docs: docs, - time: (0, _util.now)() + time: (0, _utils.now)() }; } @@ -155,37 +113,95 @@ var RxQueryBase = /*#__PURE__*/function () { * executes the query on the database * @return results-array with document-data */; - _proto._execOverDatabase = function _execOverDatabase() { - var _this = this; - this._execOverDatabaseCount = this._execOverDatabaseCount + 1; - this._lastExecStart = (0, _util.now)(); - if (this.op === 'count') { - var preparedQuery = this.getPreparedQuery(); - return this.collection.storageInstance.count(preparedQuery).then(function (result) { - if (result.mode === 'slow' && !_this.collection.database.allowSlowCount) { - throw (0, _rxError.newRxError)('QU14', { - collection: _this.collection, - queryObj: _this.mangoQuery - }); - } else { - return result.count; + _proto._execOverDatabase = + /*#__PURE__*/ + function () { + var _execOverDatabase2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _this2 = this; + var preparedQuery, result, ids, ret, mustBeQueried, docs, docsPromise; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + this._execOverDatabaseCount = this._execOverDatabaseCount + 1; + this._lastExecStart = (0, _utils.now)(); + if (!(this.op === 'count')) { + _context.next = 12; + break; + } + preparedQuery = this.getPreparedQuery(); + _context.next = 6; + return this.collection.storageInstance.count(preparedQuery); + case 6: + result = _context.sent; + if (!(result.mode === 'slow' && !this.collection.database.allowSlowCount)) { + _context.next = 11; + break; + } + throw (0, _rxError.newRxError)('QU14', { + collection: this.collection, + queryObj: this.mangoQuery + }); + case 11: + return _context.abrupt("return", result.count); + case 12: + if (!(this.op === 'findByIds')) { + _context.next = 23; + break; + } + ids = (0, _utils.ensureNotFalsy)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in; + ret = new Map(); + mustBeQueried = []; // first try to fill from docCache + ids.forEach(function (id) { + var docData = _this2.collection._docCache.getLatestDocumentDataIfExists(id); + if (docData) { + if (!docData._deleted) { + var doc = _this2.collection._docCache.getCachedRxDocument(docData); + ret.set(id, doc); + } + } else { + mustBeQueried.push(id); + } + }); + // everything which was not in docCache must be fetched from the storage + if (!(mustBeQueried.length > 0)) { + _context.next = 22; + break; + } + _context.next = 20; + return this.collection.storageInstance.findDocumentsById(mustBeQueried, false); + case 20: + docs = _context.sent; + Object.values(docs).forEach(function (docData) { + var doc = _this2.collection._docCache.getCachedRxDocument(docData); + ret.set(doc.primary, doc); + }); + case 22: + return _context.abrupt("return", ret); + case 23: + docsPromise = queryCollection(this); + return _context.abrupt("return", docsPromise.then(function (docs) { + _this2._lastExecEnd = (0, _utils.now)(); + return docs; + })); + case 25: + case "end": + return _context.stop(); } - }); + }, _callee, this); + })); + function _execOverDatabase() { + return _execOverDatabase2.apply(this, arguments); } - var docsPromise = queryCollection(this); - return docsPromise.then(function (docs) { - _this._lastExecEnd = (0, _util.now)(); - return docs; - }); - } - + return _execOverDatabase; + }() /** * Execute the query * To have an easier implementations, * just subscribe and use the first result - */; + */ + ; _proto.exec = function exec(throwIfMissing) { - var _this2 = this; + var _this3 = this; if (throwIfMissing && this.op !== 'findOne') { throw (0, _rxError.newRxError)('QU9', { collection: this.collection.name, @@ -200,13 +216,13 @@ var RxQueryBase = /*#__PURE__*/function () { * will be thrown at this execution context and not in the background. */ return _ensureEqual(this).then(function () { - return (0, _rxjs.firstValueFrom)(_this2.$); + return (0, _rxjs.firstValueFrom)(_this3.$); }).then(function (result) { if (!result && throwIfMissing) { throw (0, _rxError.newRxError)('QU10', { - collection: _this2.collection.name, - query: _this2.mangoQuery, - op: _this2.op + collection: _this3.collection.name, + query: _this3.mangoQuery, + op: _this3.op }); } else { return result; @@ -223,12 +239,12 @@ var RxQueryBase = /*#__PURE__*/function () { * @overwrites itself with the actual value */ _proto.toString = function toString() { - var stringObj = (0, _util.sortObject)({ + var stringObj = (0, _utils.sortObject)({ op: this.op, query: this.mangoQuery, other: this.other }, true); - var value = JSON.stringify(stringObj, _util.stringifyFilter); + var value = JSON.stringify(stringObj, _utils.stringifyFilter); this.toString = function () { return value; }; @@ -244,7 +260,7 @@ var RxQueryBase = /*#__PURE__*/function () { var hookInput = { rxQuery: this, // can be mutated by the hooks so we have to deep clone first. - mangoQuery: (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _util.clone)(this.mangoQuery)) + mangoQuery: (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _utils.clone)(this.mangoQuery)) }; (0, _hooks.runPluginHooks)('prePrepareQuery', hookInput); var value = this.collection.database.storage.statics.prepareQuery(this.collection.schema.jsonSchema, hookInput.mangoQuery); @@ -271,9 +287,7 @@ var RxQueryBase = /*#__PURE__*/function () { * @return promise with deleted documents */; _proto.remove = function remove() { - var ret; return this.exec().then(function (docs) { - ret = docs; if (Array.isArray(docs)) { // TODO use a bulk operation instead of running .remove() on each document return Promise.all(docs.map(function (doc) { @@ -282,8 +296,6 @@ var RxQueryBase = /*#__PURE__*/function () { } else { return docs.remove(); } - }).then(function () { - return ret; }); } @@ -295,28 +307,28 @@ var RxQueryBase = /*#__PURE__*/function () { * @overwritten by plugin (optional) */ _proto.update = function update(_updateObj) { - throw (0, _util.pluginMissing)('update'); + throw (0, _utils.pluginMissing)('update'); } // we only set some methods of query-builder here // because the others depend on these ones ; _proto.where = function where(_queryObj) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; _proto.sort = function sort(_params) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; _proto.skip = function skip(_amount) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; _proto.limit = function limit(_amount) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; (0, _createClass2["default"])(RxQueryBase, [{ key: "$", get: function get() { - var _this3 = this; + var _this4 = this; if (!this._$) { var results$ = this.collection.$.pipe( /** @@ -333,17 +345,17 @@ var RxQueryBase = /*#__PURE__*/function () { (0, _operators.startWith)(null), // ensure query results are up to date. (0, _operators.mergeMap)(function () { - return _ensureEqual(_this3); + return _ensureEqual(_this4); }), // use the current result set, written by _ensureEqual(). (0, _operators.map)(function () { - return _this3._result; + return _this4._result; }), // do not run stuff above for each new subscriber, only once. - (0, _operators.shareReplay)(_util.RXJS_SHARE_REPLAY_DEFAULTS), + (0, _operators.shareReplay)(_utils.RXJS_SHARE_REPLAY_DEFAULTS), // do not proceed if result set has not changed. (0, _operators.distinctUntilChanged)(function (prev, curr) { - if (prev && prev.time === (0, _util.ensureNotFalsy)(curr).time) { + if (prev && prev.time === (0, _utils.ensureNotFalsy)(curr).time) { return true; } else { return false; @@ -356,12 +368,14 @@ var RxQueryBase = /*#__PURE__*/function () { * depending on query type */ (0, _operators.map)(function (result) { - var useResult = (0, _util.ensureNotFalsy)(result); - if (_this3.op === 'count') { + var useResult = (0, _utils.ensureNotFalsy)(result); + if (_this4.op === 'count') { return useResult.count; - } else if (_this3.op === 'findOne') { + } else if (_this4.op === 'findOne') { // findOne()-queries emit RxDocument or null return useResult.docs.length === 0 ? null : useResult.docs[0]; + } else if (_this4.op === 'findByIds') { + return useResult.docsMap; } else { // find()-queries emit RxDocument[] // Flat copy the array so it won't matter if the user modifies it. @@ -392,8 +406,8 @@ var RxQueryBase = /*#__PURE__*/function () { * so that it does not contain modifications from the hooks * like the key compression. */ - var usePreparedQuery = this.collection.database.storage.statics.prepareQuery(schema, (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _util.clone)(this.mangoQuery))); - return (0, _util.overwriteGetterForCaching)(this, 'queryMatcher', this.collection.database.storage.statics.getQueryMatcher(schema, usePreparedQuery)); + var usePreparedQuery = this.collection.database.storage.statics.prepareQuery(schema, (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _utils.clone)(this.mangoQuery))); + return (0, _utils.overwriteGetterForCaching)(this, 'queryMatcher', this.collection.database.storage.statics.getQueryMatcher(schema, usePreparedQuery)); } }, { key: "asRxQuery", @@ -452,7 +466,7 @@ function _isResultsInSync(rxQuery) { function _ensureEqual(rxQuery) { // Optimisation shortcut if (rxQuery.collection.database.destroyed || _isResultsInSync(rxQuery)) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue.then(function () { return __ensureEqual(rxQuery); @@ -465,7 +479,7 @@ function _ensureEqual(rxQuery) { * @return true if results have changed */ function __ensureEqual(rxQuery) { - rxQuery._lastEnsureEqual = (0, _util.now)(); + rxQuery._lastEnsureEqual = (0, _utils.now)(); /** * Optimisation shortcuts @@ -475,7 +489,7 @@ function __ensureEqual(rxQuery) { rxQuery.collection.database.destroyed || // nothing happened since last run _isResultsInSync(rxQuery)) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } var ret = false; var mustReExec = false; // if this becomes true, a whole execution over the database is made @@ -497,7 +511,7 @@ function __ensureEqual(rxQuery) { var runChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(missedChangeEvents); if (rxQuery.op === 'count') { // 'count' query - var previousCount = (0, _util.ensureNotFalsy)(rxQuery._result).count; + var previousCount = (0, _utils.ensureNotFalsy)(rxQuery._result).count; var newCount = previousCount; runChangeEvents.forEach(function (cE) { var didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData); @@ -543,7 +557,7 @@ function __ensureEqual(rxQuery) { } return ret; } - if (!rxQuery._result || !(0, _util.areRxDocumentArraysEqual)(rxQuery.collection.schema.primaryPath, newResultData, rxQuery._result.docsData)) { + if (!rxQuery._result || !(0, _utils.areRxDocumentArraysEqual)(rxQuery.collection.schema.primaryPath, newResultData, rxQuery._result.docsData)) { ret = true; // true because results changed rxQuery._setResultData(newResultData); } @@ -553,12 +567,82 @@ function __ensureEqual(rxQuery) { return Promise.resolve(ret); // true if results have changed } +/** + * Runs the query over the storage instance + * of the collection. + * Does some optimizations to ensuer findById is used + * when specific queries are used. + */ +function queryCollection(_x) { + return _queryCollection.apply(this, arguments); +} +/** + * Returns true if the given query + * selects exactly one document by its id. + * Used to optimize performance because these kind of + * queries do not have to run over an index and can use get-by-id instead. + * Returns false if no query of that kind. + * Returns the document id otherwise. + */ +function _queryCollection() { + _queryCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxQuery) { + var docs, collection, docId, docData, docsMap, preparedQuery, queryResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + docs = []; + collection = rxQuery.collection; + /** + * Optimizations shortcut. + * If query is find-one-document-by-id, + * then we do not have to use the slow query() method + * but instead can use findDocumentsById() + */ + if (!rxQuery.isFindOneByIdQuery) { + _context2.next = 13; + break; + } + docId = rxQuery.isFindOneByIdQuery; // first try to fill from docCache + docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId); + if (docData) { + _context2.next = 10; + break; + } + _context2.next = 8; + return collection.storageInstance.findDocumentsById([docId], false); + case 8: + docsMap = _context2.sent; + docData = docsMap[docId]; + case 10: + if (docData) { + docs.push(docData); + } + _context2.next = 18; + break; + case 13: + preparedQuery = rxQuery.getPreparedQuery(); + _context2.next = 16; + return collection.storageInstance.query(preparedQuery); + case 16: + queryResult = _context2.sent; + docs = queryResult.documents; + case 18: + return _context2.abrupt("return", docs); + case 19: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _queryCollection.apply(this, arguments); +} function isFindOneByIdQuery(primaryPath, query) { if (!query.skip && query.selector && Object.keys(query.selector).length === 1 && query.selector[primaryPath]) { - if (typeof query.selector[primaryPath] === 'string') { - return query.selector[primaryPath]; - } else if (Object.keys(query.selector[primaryPath]).length === 1 && typeof query.selector[primaryPath].$eq === 'string') { - return query.selector[primaryPath].$eq; + var value = query.selector[primaryPath]; + if (typeof value === 'string') { + return value; + } else if (Object.keys(value).length === 1 && typeof value.$eq === 'string') { + return value.$eq; } } return false; diff --git a/dist/lib/rx-query.js.map b/dist/lib/rx-query.js.map index 3b851258335..690c460d0f4 100644 --- a/dist/lib/rx-query.js.map +++ b/dist/lib/rx-query.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.js","names":["queryCollection","rxQuery","docs","collection","isFindOneByIdQuery","docId","storageInstance","findDocumentsById","docsMap","docData","push","preparedQuery","getPreparedQuery","query","queryResult","documents","_queryCount","newQueryID","RxQueryBase","op","mangoQuery","id","_execOverDatabaseCount","_creationTime","now","_lastEnsureEqual","other","uncached","refCount$","BehaviorSubject","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","PROMISE_RESOLVE_FALSE","_getDefaultQuery","schema","primaryPath","_setResultData","newResultData","docsData","docsDataMap","Map","count","time","createRxDocuments","primPath","map","doc","_dataSync$","getValue","set","length","_execOverDatabase","then","result","mode","database","allowSlowCount","newRxError","queryObj","docsPromise","exec","throwIfMissing","name","_ensureEqual","firstValueFrom","$","toString","stringObj","sortObject","value","JSON","stringify","stringifyFilter","hookInput","normalizeMangoQuery","jsonSchema","clone","runPluginHooks","storage","statics","prepareQuery","doesDocumentDataMatch","_deleted","queryMatcher","remove","ret","Array","isArray","Promise","all","update","_updateObj","pluginMissing","where","_queryObj","sort","_params","skip","_amount","limit","_$","results$","pipe","filter","changeEvent","isLocal","startWith","mergeMap","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","distinctUntilChanged","prev","curr","ensureNotFalsy","useResult","slice","merge","usePreparedQuery","overwriteGetterForCaching","getQueryMatcher","selector","tunnelQueryCache","_queryCache","getByQuery","createRxQuery","triggerCacheReplacement","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","forEach","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","calculateNewResults","runFullQueryAgain","changed","newResults","latestAfter","areRxDocumentArraysEqual","resolve","Object","keys","$eq","isInstanceOf","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n stringifyFilter,\n pluginMissing,\n clone,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './util';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData\n} from './types';\n\nimport {\n createRxDocuments\n} from './rx-document-prototype-merge';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport type { QueryMatcher } from 'event-reduce-js';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n // used by some plugins\n public other: any = {};\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string;\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docs: RxDocument[];\n count: number;\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n time: number;\n } | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly,\n public collection: RxCollection\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.docs.length === 0 ? null : useResult.docs[0];\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.docs.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from pouchdb\n */\n _setResultData(newResultData: RxDocumentData | number): void {\n\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n }\n\n const docs = createRxDocuments(\n this.collection,\n newResultData\n );\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n */\n const primPath = this.collection.schema.primaryPath;\n const docsDataMap = new Map();\n const docsData = docs.map(doc => {\n const docData: RxDocumentData = doc._dataSync$.getValue() as any;\n const id: string = docData[primPath] as any;\n docsDataMap.set(id, docData);\n return docData;\n });\n\n this._result = {\n docsData,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n return this.collection.storageInstance.count(preparedQuery).then(result => {\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n\n });\n }\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n\n\n /**\n * Instead of calling this.getPreparedQuery(),\n * we have to prepare the query for the query matcher\n * so that it does not contain modifications from the hooks\n * like the key compression.\n */\n const usePreparedQuery = this.collection.database.storage.statics.prepareQuery(\n schema,\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n );\n\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n this.collection.database.storage.statics.getQueryMatcher(\n schema,\n usePreparedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj, stringifyFilter);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n };\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n let ret: any;\n return this\n .exec()\n .then(docs => {\n ret = docs;\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n })\n .then(() => ret);\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection\n });\n\n let ret = new RxQueryBase(op, queryObj, collection);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensuer findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n const docId = rxQuery.isFindOneByIdQuery;\n const docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n const docData = docsMap[docId];\n if (docData) {\n docs.push(docData);\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string {\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n if (typeof query.selector[primaryPath] === 'string') {\n return query.selector[primaryPath];\n } else if (\n Object.keys(query.selector[primaryPath]).length === 1 &&\n typeof query.selector[primaryPath].$eq === 'string'\n ) {\n return query.selector[primaryPath].$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAMA;AAQA;AAYA;AAGA;AAiBA;AAGA;AACA;AAEA;AAglBA;AACA;AACA;AACA;AACA;AACA;AALA,IAMsBA,eAAe,YAAfA,eAAe,CACjCC,OAAoD;EAAA,IAChB;IACpC,IAAIC,IAAiC,GAAG,EAAE;IAC1C,IAAMC,WAAU,GAAGF,OAAO,CAACE,UAAU;;IAErC;AACJ;AACA;AACA;AACA;AACA;IALI;MAAA,IAMIF,OAAO,CAACG,kBAAkB;QAC1B,IAAMC,KAAK,GAAGJ,OAAO,CAACG,kBAAkB;QAAC,uBACnBD,WAAU,CAACG,eAAe,CAACC,iBAAiB,CAAC,CAACF,KAAK,CAAC,EAAE,KAAK,CAAC,iBAA5EG,OAAO;UACb,IAAMC,OAAO,GAAGD,OAAO,CAACH,KAAK,CAAC;UAAC,IAC3BI,OAAO;YACPP,IAAI,CAACQ,IAAI,CAACD,OAAO,CAAC;UAAC;QAAA;MAAA;QAGvB,IAAME,aAAa,GAAGV,OAAO,CAACW,gBAAgB,EAAE;QAAC,uBACvBT,WAAU,CAACG,eAAe,CAACO,KAAK,CAACF,aAAa,CAAC,iBAAnEG,WAAW;UACjBZ,IAAI,GAAGY,WAAW,CAACC,SAAS;QAAC;MAAA;IAAA;IAAA;MAEjC,OAAOb,IAAI;IAAC,KAALA,IAAI;EAEf,CAAC;IAAA;EAAA;AAAA;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAPA;AAhnBA,IAAIc,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAbA,UAAU,GAAuB;EACnC,OAAO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,CAAC6B,OAAO,CAACW,QAAQ,CAC3B,EACH;QACE+C,GAAG,GAAG,IAAI,CAAC,CAAC;QACZvF,OAAO,CAACsC,cAAc,CAACC,aAAa,CAAQ;MAChD;MACA,OAAOgD,GAAG;IACd,CAAC,CAAC;EACV;EACA,OAAOG,OAAO,CAACiE,OAAO,CAACpE,GAAG,CAAC,CAAC,CAAC;AACjC;;AA4CO,SAASpF,kBAAkB,CAC9BkC,WAAmB,EACnBzB,KAAsB,EACR;EACd,IACI,CAACA,KAAK,CAACuF,IAAI,IACXvF,KAAK,CAAC8G,QAAQ,IACdkC,MAAM,CAACC,IAAI,CAACjJ,KAAK,CAAC8G,QAAQ,CAAC,CAACtE,MAAM,KAAK,CAAC,IACxCxC,KAAK,CAAC8G,QAAQ,CAACrF,WAAW,CAAC,EAC7B;IACE,IAAI,OAAOzB,KAAK,CAAC8G,QAAQ,CAACrF,WAAW,CAAC,KAAK,QAAQ,EAAE;MACjD,OAAOzB,KAAK,CAAC8G,QAAQ,CAACrF,WAAW,CAAC;IACtC,CAAC,MAAM,IACHuH,MAAM,CAACC,IAAI,CAACjJ,KAAK,CAAC8G,QAAQ,CAACrF,WAAW,CAAC,CAAC,CAACe,MAAM,KAAK,CAAC,IACrD,OAAOxC,KAAK,CAAC8G,QAAQ,CAACrF,WAAW,CAAC,CAACyH,GAAG,KAAK,QAAQ,EACrD;MACE,OAAOlJ,KAAK,CAAC8G,QAAQ,CAACrF,WAAW,CAAC,CAACyH,GAAG;IAC1C;EACJ;EACA,OAAO,KAAK;AAChB;AAIO,SAASC,YAAY,CAACC,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAY/I,WAAW;AACrC"} \ No newline at end of file +{"version":3,"file":"rx-query.js","names":["_queryCount","newQueryID","RxQueryBase","op","mangoQuery","collection","id","_execOverDatabaseCount","_creationTime","now","_lastEnsureEqual","other","uncached","refCount$","BehaviorSubject","_result","_latestChangeEvent","_lastExecStart","_lastExecEnd","_ensureEqualQueue","PROMISE_RESOLVE_FALSE","_getDefaultQuery","isFindOneByIdQuery","schema","primaryPath","_setResultData","newResultData","docsData","docsMap","Map","docsDataMap","count","docs","time","Array","from","values","map","docData","_docCache","getCachedRxDocument","doc","set","primary","_data","length","_execOverDatabase","preparedQuery","getPreparedQuery","storageInstance","result","mode","database","allowSlowCount","newRxError","queryObj","ids","ensureNotFalsy","selector","$in","ret","mustBeQueried","forEach","getLatestDocumentDataIfExists","_deleted","push","findDocumentsById","Object","docsPromise","queryCollection","then","exec","throwIfMissing","name","query","_ensureEqual","firstValueFrom","$","toString","stringObj","sortObject","value","JSON","stringify","stringifyFilter","hookInput","rxQuery","normalizeMangoQuery","jsonSchema","clone","runPluginHooks","storage","statics","prepareQuery","doesDocumentDataMatch","queryMatcher","remove","isArray","Promise","all","update","_updateObj","pluginMissing","where","_queryObj","sort","_params","skip","_amount","limit","_$","results$","pipe","filter","changeEvent","isLocal","startWith","mergeMap","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","distinctUntilChanged","prev","curr","useResult","slice","merge","usePreparedQuery","overwriteGetterForCaching","getQueryMatcher","tunnelQueryCache","_queryCache","getByQuery","createRxQuery","triggerCacheReplacement","_isResultsInSync","currentLatestEventNumber","asRxQuery","_changeEventBuffer","counter","destroyed","__ensureEqual","mustReExec","missedChangeEvents","getFrom","runChangeEvents","reduceByLastOfDoc","previousCount","newCount","cE","didMatchBefore","previousDocumentData","doesMatchNow","documentData","eventReduceResult","calculateNewResults","runFullQueryAgain","changed","newResults","latestAfter","areRxDocumentArraysEqual","resolve","docId","queryResult","documents","keys","$eq","isInstanceOf","obj"],"sources":["../../src/rx-query.ts"],"sourcesContent":["import {\n BehaviorSubject,\n firstValueFrom,\n Observable,\n merge\n} from 'rxjs';\nimport {\n mergeMap,\n filter,\n map,\n startWith,\n distinctUntilChanged,\n shareReplay\n} from 'rxjs/operators';\nimport {\n sortObject,\n stringifyFilter,\n pluginMissing,\n clone,\n overwriteGetterForCaching,\n now,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS,\n ensureNotFalsy,\n areRxDocumentArraysEqual\n} from './plugins/utils';\nimport {\n newRxError\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport type {\n RxCollection,\n RxDocument,\n RxQueryOP,\n RxQuery,\n MangoQuery,\n MangoQuerySortPart,\n MangoQuerySelector,\n PreparedQuery,\n RxChangeEvent,\n RxDocumentWriteData,\n RxDocumentData\n} from './types';\nimport { calculateNewResults } from './event-reduce';\nimport { triggerCacheReplacement } from './query-cache';\nimport type { QueryMatcher } from 'event-reduce-js';\nimport { normalizeMangoQuery } from './rx-query-helper';\n\nlet _queryCount = 0;\nconst newQueryID = function (): number {\n return ++_queryCount;\n};\n\nexport class RxQueryBase<\n RxDocType,\n // TODO also pass DocMethods here\n RxQueryResult = RxDocument[] | RxDocument\n> {\n\n public id: number = newQueryID();\n\n /**\n * Some stats then are used for debugging and cache replacement policies\n */\n public _execOverDatabaseCount: number = 0;\n public _creationTime = now();\n\n // used in the query-cache to determine if the RxQuery can be cleaned up.\n public _lastEnsureEqual = 0;\n\n // used by some plugins\n public other: any = {};\n\n public uncached = false;\n\n // used to count the subscribers to the query\n public refCount$ = new BehaviorSubject(null);\n\n public isFindOneByIdQuery: false | string;\n\n\n /**\n * Contains the current result state\n * or null if query has not run yet.\n */\n public _result: {\n docsData: RxDocumentData[];\n // A key->document map, used in the event reduce optimization.\n docsDataMap: Map;\n docsMap: Map>;\n docs: RxDocument[];\n count: number;\n /**\n * Time at which the current _result state was created.\n * Used to determine if the result set has changed since X\n * so that we do not emit the same result multiple times on subscription.\n */\n time: number;\n } | null = null;\n\n\n constructor(\n public op: RxQueryOP,\n public mangoQuery: Readonly>,\n public collection: RxCollection\n ) {\n if (!mangoQuery) {\n this.mangoQuery = _getDefaultQuery();\n }\n\n this.isFindOneByIdQuery = isFindOneByIdQuery(\n this.collection.schema.primaryPath as string,\n mangoQuery\n );\n }\n get $(): BehaviorSubject {\n if (!this._$) {\n\n const results$ = this.collection.$.pipe(\n /**\n * Performance shortcut.\n * Changes to local documents are not relevant for the query.\n */\n filter(changeEvent => !changeEvent.isLocal),\n /**\n * Start once to ensure the querying also starts\n * when there where no changes.\n */\n startWith(null),\n // ensure query results are up to date.\n mergeMap(() => _ensureEqual(this as any)),\n // use the current result set, written by _ensureEqual().\n map(() => this._result),\n // do not run stuff above for each new subscriber, only once.\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS),\n // do not proceed if result set has not changed.\n distinctUntilChanged((prev, curr) => {\n if (prev && prev.time === ensureNotFalsy(curr).time) {\n return true;\n } else {\n return false;\n }\n }),\n filter(result => !!result),\n /**\n * Map the result set to a single RxDocument or an array,\n * depending on query type\n */\n map((result) => {\n const useResult = ensureNotFalsy(result);\n if (this.op === 'count') {\n return useResult.count;\n } else if (this.op === 'findOne') {\n // findOne()-queries emit RxDocument or null\n return useResult.docs.length === 0 ? null : useResult.docs[0];\n } else if (this.op === 'findByIds') {\n return useResult.docsMap;\n } else {\n // find()-queries emit RxDocument[]\n // Flat copy the array so it won't matter if the user modifies it.\n return useResult.docs.slice(0);\n }\n })\n );\n\n this._$ = merge(\n results$,\n /**\n * Also add the refCount$ to the query observable\n * to allow us to count the amount of subscribers.\n */\n this.refCount$.pipe(\n filter(() => false)\n )\n );\n }\n return this._$ as any;\n }\n\n\n // stores the changeEvent-number of the last handled change-event\n public _latestChangeEvent: -1 | number = -1;\n\n // time stamps on when the last full exec over the database has run\n // used to properly handle events that happen while the find-query is running\n public _lastExecStart: number = 0;\n public _lastExecEnd: number = 0;\n\n /**\n * ensures that the exec-runs\n * are not run in parallel\n */\n public _ensureEqualQueue: Promise = PROMISE_RESOLVE_FALSE;\n\n /**\n * Returns an observable that emits the results\n * This should behave like an rxjs-BehaviorSubject which means:\n * - Emit the current result-set on subscribe\n * - Emit the new result-set when an RxChangeEvent comes in\n * - Do not emit anything before the first result-set was created (no null)\n */\n public _$?: Observable;\n\n /**\n * set the new result-data as result-docs of the query\n * @param newResultData json-docs that were received from the storage\n */\n _setResultData(newResultData: RxDocumentData[] | number | Map>): void {\n\n if (typeof newResultData === 'number') {\n this._result = {\n docsData: [],\n docsMap: new Map(),\n docsDataMap: new Map(),\n count: newResultData,\n docs: [],\n time: now()\n };\n return;\n } else if (newResultData instanceof Map) {\n newResultData = Array.from((newResultData as Map>).values());\n }\n\n const docsDataMap = new Map();\n const docsMap = new Map();\n const docs = newResultData.map(docData => this.collection._docCache.getCachedRxDocument(docData));\n\n /**\n * Instead of using the newResultData in the result cache,\n * we directly use the objects that are stored in the RxDocument\n * to ensure we do not store the same data twice and fill up the memory.\n */\n const docsData = docs.map(doc => {\n docsDataMap.set(doc.primary, doc._data);\n docsMap.set(doc.primary, doc);\n return doc._data;\n });\n\n this._result = {\n docsData,\n docsMap,\n docsDataMap,\n count: docsData.length,\n docs,\n time: now()\n };\n }\n\n /**\n * executes the query on the database\n * @return results-array with document-data\n */\n async _execOverDatabase(): Promise[] | number> {\n this._execOverDatabaseCount = this._execOverDatabaseCount + 1;\n this._lastExecStart = now();\n\n\n if (this.op === 'count') {\n const preparedQuery = this.getPreparedQuery();\n const result = await this.collection.storageInstance.count(preparedQuery);\n if (result.mode === 'slow' && !this.collection.database.allowSlowCount) {\n throw newRxError('QU14', {\n collection: this.collection,\n queryObj: this.mangoQuery\n });\n } else {\n return result.count;\n }\n }\n\n if (this.op === 'findByIds') {\n const ids: string[] = ensureNotFalsy(this.mangoQuery.selector as any)[this.collection.schema.primaryPath].$in;\n const ret = new Map>();\n const mustBeQueried: string[] = [];\n // first try to fill from docCache\n ids.forEach(id => {\n const docData = this.collection._docCache.getLatestDocumentDataIfExists(id);\n if (docData) {\n if (!docData._deleted) {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(id, doc);\n }\n } else {\n mustBeQueried.push(id);\n }\n });\n // everything which was not in docCache must be fetched from the storage\n if (mustBeQueried.length > 0) {\n const docs = await this.collection.storageInstance.findDocumentsById(mustBeQueried, false);\n Object.values(docs).forEach(docData => {\n const doc = this.collection._docCache.getCachedRxDocument(docData);\n ret.set(doc.primary, doc);\n });\n }\n return ret as any;\n }\n\n\n const docsPromise = queryCollection(this as any);\n return docsPromise.then(docs => {\n this._lastExecEnd = now();\n return docs;\n });\n }\n\n /**\n * Execute the query\n * To have an easier implementations,\n * just subscribe and use the first result\n */\n public exec(throwIfMissing: true): Promise>;\n public exec(): Promise;\n public exec(throwIfMissing?: boolean): Promise {\n if (throwIfMissing && this.op !== 'findOne') {\n throw newRxError('QU9', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n }\n\n\n /**\n * run _ensureEqual() here,\n * this will make sure that errors in the query which throw inside of the RxStorage,\n * will be thrown at this execution context and not in the background.\n */\n return _ensureEqual(this)\n .then(() => firstValueFrom(this.$))\n .then(result => {\n if (!result && throwIfMissing) {\n throw newRxError('QU10', {\n collection: this.collection.name,\n query: this.mangoQuery,\n op: this.op\n });\n } else {\n return result;\n }\n });\n }\n\n\n\n /**\n * cached call to get the queryMatcher\n * @overwrites itself with the actual value\n */\n get queryMatcher(): QueryMatcher> {\n const schema = this.collection.schema.jsonSchema;\n\n\n /**\n * Instead of calling this.getPreparedQuery(),\n * we have to prepare the query for the query matcher\n * so that it does not contain modifications from the hooks\n * like the key compression.\n */\n const usePreparedQuery = this.collection.database.storage.statics.prepareQuery(\n schema,\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n );\n\n return overwriteGetterForCaching(\n this,\n 'queryMatcher',\n this.collection.database.storage.statics.getQueryMatcher(\n schema,\n usePreparedQuery\n ) as any\n );\n }\n\n /**\n * returns a string that is used for equal-comparisons\n * @overwrites itself with the actual value\n */\n toString(): string {\n const stringObj = sortObject({\n op: this.op,\n query: this.mangoQuery,\n other: this.other\n }, true);\n const value = JSON.stringify(stringObj, stringifyFilter);\n this.toString = () => value;\n return value;\n }\n\n /**\n * returns the prepared query\n * which can be send to the storage instance to query for documents.\n * @overwrites itself with the actual value.\n */\n getPreparedQuery(): PreparedQuery {\n const hookInput = {\n rxQuery: this,\n // can be mutated by the hooks so we have to deep clone first.\n mangoQuery: normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n clone(this.mangoQuery)\n )\n };\n runPluginHooks('prePrepareQuery', hookInput);\n\n const value = this.collection.database.storage.statics.prepareQuery(\n this.collection.schema.jsonSchema,\n hookInput.mangoQuery\n );\n\n this.getPreparedQuery = () => value;\n return value;\n }\n\n /**\n * returns true if the document matches the query,\n * does not use the 'skip' and 'limit'\n */\n doesDocumentDataMatch(docData: RxDocType | any): boolean {\n // if doc is deleted, it cannot match\n if (docData._deleted) {\n return false;\n }\n\n return this.queryMatcher(docData);\n }\n\n /**\n * deletes all found documents\n * @return promise with deleted documents\n */\n remove(): Promise {\n return this\n .exec()\n .then(docs => {\n if (Array.isArray(docs)) {\n // TODO use a bulk operation instead of running .remove() on each document\n return Promise.all(docs.map(doc => doc.remove()));\n } else {\n return (docs as any).remove();\n }\n });\n }\n\n\n /**\n * helper function to transform RxQueryBase to RxQuery type\n */\n get asRxQuery(): RxQuery {\n return this as any;\n }\n\n /**\n * updates all found documents\n * @overwritten by plugin (optional)\n */\n update(_updateObj: any): Promise {\n throw pluginMissing('update');\n }\n\n\n // we only set some methods of query-builder here\n // because the others depend on these ones\n where(_queryObj: MangoQuerySelector | keyof RxDocType | string): RxQuery {\n throw pluginMissing('query-builder');\n }\n sort(_params: string | MangoQuerySortPart): RxQuery {\n throw pluginMissing('query-builder');\n }\n skip(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n limit(_amount: number | null): RxQuery {\n throw pluginMissing('query-builder');\n }\n}\n\nexport function _getDefaultQuery(): MangoQuery {\n return {\n selector: {}\n };\n}\n\n/**\n * run this query through the QueryCache\n */\nexport function tunnelQueryCache(\n rxQuery: RxQueryBase\n): RxQuery {\n return rxQuery.collection._queryCache.getByQuery(rxQuery as any);\n}\n\nexport function createRxQuery(\n op: RxQueryOP,\n queryObj: MangoQuery,\n collection: RxCollection\n) {\n runPluginHooks('preCreateRxQuery', {\n op,\n queryObj,\n collection\n });\n\n let ret = new RxQueryBase(op, queryObj, collection);\n\n // ensure when created with same params, only one is created\n ret = tunnelQueryCache(ret);\n triggerCacheReplacement(collection);\n\n return ret;\n}\n\n/**\n * Check if the current results-state is in sync with the database\n * which means that no write event happened since the last run.\n * @return false if not which means it should re-execute\n */\nfunction _isResultsInSync(rxQuery: RxQueryBase): boolean {\n const currentLatestEventNumber = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n if (rxQuery._latestChangeEvent >= currentLatestEventNumber) {\n return true;\n } else {\n return false;\n }\n}\n\n\n/**\n * wraps __ensureEqual()\n * to ensure it does not run in parallel\n * @return true if has changed, false if not\n */\nfunction _ensureEqual(rxQuery: RxQueryBase): Promise {\n // Optimisation shortcut\n if (\n rxQuery.collection.database.destroyed ||\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue\n .then(() => __ensureEqual(rxQuery));\n return rxQuery._ensureEqualQueue;\n}\n\n/**\n * ensures that the results of this query is equal to the results which a query over the database would give\n * @return true if results have changed\n */\nfunction __ensureEqual(rxQuery: RxQueryBase): Promise {\n rxQuery._lastEnsureEqual = now();\n\n /**\n * Optimisation shortcuts\n */\n if (\n // db is closed\n rxQuery.collection.database.destroyed ||\n // nothing happened since last run\n _isResultsInSync(rxQuery)\n ) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n let ret = false;\n let mustReExec = false; // if this becomes true, a whole execution over the database is made\n if (rxQuery._latestChangeEvent === -1) {\n // have not executed yet -> must run\n mustReExec = true;\n }\n\n /**\n * try to use EventReduce to calculate the new results\n */\n if (!mustReExec) {\n const missedChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.getFrom(rxQuery._latestChangeEvent + 1);\n if (missedChangeEvents === null) {\n // changeEventBuffer is of bounds -> we must re-execute over the database\n mustReExec = true;\n } else {\n rxQuery._latestChangeEvent = rxQuery.asRxQuery.collection._changeEventBuffer.counter;\n\n const runChangeEvents: RxChangeEvent[] = rxQuery.asRxQuery.collection\n ._changeEventBuffer\n .reduceByLastOfDoc(missedChangeEvents);\n\n if (rxQuery.op === 'count') {\n // 'count' query\n const previousCount = ensureNotFalsy(rxQuery._result).count;\n let newCount = previousCount;\n runChangeEvents.forEach(cE => {\n const didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData);\n const doesMatchNow = rxQuery.doesDocumentDataMatch(cE.documentData);\n\n if (!didMatchBefore && doesMatchNow) {\n newCount++;\n }\n if (didMatchBefore && !doesMatchNow) {\n newCount--;\n }\n });\n if (newCount !== previousCount) {\n ret = true; // true because results changed\n rxQuery._setResultData(newCount as any);\n }\n } else {\n // 'find' or 'findOne' query\n const eventReduceResult = calculateNewResults(\n rxQuery as any,\n runChangeEvents\n );\n if (eventReduceResult.runFullQueryAgain) {\n // could not calculate the new results, execute must be done\n mustReExec = true;\n } else if (eventReduceResult.changed) {\n // we got the new results, we do not have to re-execute, mustReExec stays false\n ret = true; // true because results changed\n rxQuery._setResultData(eventReduceResult.newResults as any);\n }\n }\n }\n }\n\n\n\n // oh no we have to re-execute the whole query over the database\n if (mustReExec) {\n // counter can change while _execOverDatabase() is running so we save it here\n const latestAfter: number = (rxQuery as any).collection._changeEventBuffer.counter;\n return rxQuery._execOverDatabase()\n .then(newResultData => {\n rxQuery._latestChangeEvent = latestAfter;\n\n // A count query needs a different has-changed check.\n if (typeof newResultData === 'number') {\n if (\n !rxQuery._result ||\n newResultData !== rxQuery._result.count\n ) {\n ret = true;\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n }\n if (\n !rxQuery._result ||\n !areRxDocumentArraysEqual(\n rxQuery.collection.schema.primaryPath,\n newResultData,\n rxQuery._result.docsData\n )\n ) {\n ret = true; // true because results changed\n rxQuery._setResultData(newResultData as any);\n }\n return ret;\n });\n }\n return Promise.resolve(ret); // true if results have changed\n}\n\n/**\n * Runs the query over the storage instance\n * of the collection.\n * Does some optimizations to ensuer findById is used\n * when specific queries are used.\n */\nexport async function queryCollection(\n rxQuery: RxQuery | RxQueryBase\n): Promise[]> {\n let docs: RxDocumentData[] = [];\n const collection = rxQuery.collection;\n\n /**\n * Optimizations shortcut.\n * If query is find-one-document-by-id,\n * then we do not have to use the slow query() method\n * but instead can use findDocumentsById()\n */\n if (rxQuery.isFindOneByIdQuery) {\n const docId = rxQuery.isFindOneByIdQuery;\n\n // first try to fill from docCache\n let docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId);\n if (!docData) {\n // otherwise get from storage\n const docsMap = await collection.storageInstance.findDocumentsById([docId], false);\n docData = docsMap[docId];\n }\n if (docData) {\n docs.push(docData);\n }\n } else {\n const preparedQuery = rxQuery.getPreparedQuery();\n const queryResult = await collection.storageInstance.query(preparedQuery);\n docs = queryResult.documents;\n }\n return docs;\n\n}\n\n/**\n * Returns true if the given query\n * selects exactly one document by its id.\n * Used to optimize performance because these kind of\n * queries do not have to run over an index and can use get-by-id instead.\n * Returns false if no query of that kind.\n * Returns the document id otherwise.\n */\nexport function isFindOneByIdQuery(\n primaryPath: string,\n query: MangoQuery\n): false | string {\n if (\n !query.skip &&\n query.selector &&\n Object.keys(query.selector).length === 1 &&\n query.selector[primaryPath]\n ) {\n const value: any = query.selector[primaryPath];\n if (typeof value === 'string') {\n return value;\n } else if (\n Object.keys(value).length === 1 &&\n typeof value.$eq === 'string'\n ) {\n return value.$eq;\n }\n }\n return false;\n}\n\n\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxQueryBase;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAMA;AAQA;AAYA;AAGA;AAgBA;AACA;AAEA;AAEA,IAAIA,WAAW,GAAG,CAAC;AACnB,IAAMC,UAAU,GAAG,SAAbA,UAAU,GAAuB;EACnC,OAAO,EAAED,WAAW;AACxB,CAAC;AAAC,IAEWE,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,OAAO,CAAC;UACtB;UAAC;UAAA;QAAA;UAEKS,aAAa,GAAGuC,OAAO,CAACtC,gBAAgB,EAAE;UAAA;UAAA,OACtB3C,UAAU,CAAC4C,eAAe,CAACyB,KAAK,CAAC3B,aAAa,CAAC;QAAA;UAAnEmH,WAAW;UACjBlI,IAAI,GAAGkI,WAAW,CAACC,SAAS;QAAC;UAAA,kCAE1BnI,IAAI;QAAA;QAAA;UAAA;MAAA;IAAA;EAAA,CAEd;EAAA;AAAA;AAUM,SAASV,kBAAkB,CAC9BE,WAAmB,EACnBkD,KAAsB,EACR;EACd,IACI,CAACA,KAAK,CAACiC,IAAI,IACXjC,KAAK,CAAChB,QAAQ,IACdS,MAAM,CAACiG,IAAI,CAAC1F,KAAK,CAAChB,QAAQ,CAAC,CAACb,MAAM,KAAK,CAAC,IACxC6B,KAAK,CAAChB,QAAQ,CAAClC,WAAW,CAAC,EAC7B;IACE,IAAMyD,KAAU,GAAGP,KAAK,CAAChB,QAAQ,CAAClC,WAAW,CAAC;IAC9C,IAAI,OAAOyD,KAAK,KAAK,QAAQ,EAAE;MAC3B,OAAOA,KAAK;IAChB,CAAC,MAAM,IACHd,MAAM,CAACiG,IAAI,CAACnF,KAAK,CAAC,CAACpC,MAAM,KAAK,CAAC,IAC/B,OAAOoC,KAAK,CAACoF,GAAG,KAAK,QAAQ,EAC/B;MACE,OAAOpF,KAAK,CAACoF,GAAG;IACpB;EACJ;EACA,OAAO,KAAK;AAChB;AAIO,SAASC,YAAY,CAACC,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAYrK,WAAW;AACrC"} \ No newline at end of file diff --git a/dist/lib/rx-schema-helper.js b/dist/lib/rx-schema-helper.js index a978528fa42..99bbc7798aa 100644 --- a/dist/lib/rx-schema-helper.js +++ b/dist/lib/rx-schema-helper.js @@ -15,7 +15,7 @@ exports.getSchemaByObjectPath = getSchemaByObjectPath; exports.normalizeRxJsonSchema = normalizeRxJsonSchema; var _objectPath = _interopRequireDefault(require("object-path")); var _rxError = require("./rx-error"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * Helper function to create a valid RxJsonSchema * with a given version. @@ -42,12 +42,12 @@ function getSchemaByObjectPath(rxJsonSchema, path) { var usePath = path; usePath = usePath.replace(/\./g, '.properties.'); usePath = 'properties.' + usePath; - usePath = (0, _util.trimDots)(usePath); + usePath = (0, _utils.trimDots)(usePath); var ret = _objectPath["default"].get(rxJsonSchema, usePath); return ret; } function fillPrimaryKey(primaryPath, jsonSchema, documentData) { - var cloned = (0, _util.flatClone)(documentData); + var cloned = (0, _utils.flatClone)(documentData); var newPrimary = getComposedPrimaryKeyOfDocumentData(jsonSchema, documentData); var existingPrimary = documentData[primaryPath]; if (existingPrimary && existingPrimary !== newPrimary) { @@ -106,18 +106,7 @@ function getComposedPrimaryKeyOfDocumentData(jsonSchema, documentData) { * @return RxJsonSchema - ordered and filled */ function normalizeRxJsonSchema(jsonSchema) { - // TODO do we need the deep clone() here? - var normalizedSchema = (0, _util.sortObject)((0, _util.clone)(jsonSchema)); - - // indexes must NOT be sorted because sort order is important here. - if (jsonSchema.indexes) { - normalizedSchema.indexes = Array.from(jsonSchema.indexes); - } - - // primaryKey.fields must NOT be sorted because sort order is important here. - if (typeof normalizedSchema.primaryKey === 'object' && typeof jsonSchema.primaryKey === 'object') { - normalizedSchema.primaryKey.fields = jsonSchema.primaryKey.fields; - } + var normalizedSchema = (0, _utils.sortObject)(jsonSchema, true); return normalizedSchema; } @@ -126,9 +115,9 @@ function normalizeRxJsonSchema(jsonSchema) { * @return cloned schemaObj */ function fillWithDefaultSettings(schemaObj) { - schemaObj = (0, _util.flatClone)(schemaObj); + schemaObj = (0, _utils.flatClone)(schemaObj); var primaryPath = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey); - schemaObj.properties = (0, _util.flatClone)(schemaObj.properties); + schemaObj.properties = (0, _utils.flatClone)(schemaObj.properties); // additionalProperties is always false schemaObj.additionalProperties = false; @@ -196,7 +185,7 @@ function fillWithDefaultSettings(schemaObj) { */ if (schemaObj.indexes) { schemaObj.indexes = schemaObj.indexes.map(function (index) { - var arIndex = (0, _util.isMaybeReadonlyArray)(index) ? index.slice(0) : [index]; + var arIndex = (0, _utils.isMaybeReadonlyArray)(index) ? index.slice(0) : [index]; if (!arIndex.includes(primaryPath)) { var modifiedIndex = arIndex.slice(0); modifiedIndex.push(primaryPath); @@ -219,7 +208,7 @@ var RX_META_SCHEMA = { /** * We use 1 as minimum so that the value is never falsy. */ - minimum: _util.RX_META_LWT_MINIMUM, + minimum: _utils.RX_META_LWT_MINIMUM, maximum: 1000000000000000, multipleOf: 0.01 } diff --git a/dist/lib/rx-schema-helper.js.map b/dist/lib/rx-schema-helper.js.map index f77512fb056..a7507d449e6 100644 --- a/dist/lib/rx-schema-helper.js.map +++ b/dist/lib/rx-schema-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema-helper.js","names":["getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","trimDots","ret","objectPath","get","fillPrimaryKey","primaryPath","jsonSchema","documentData","cloned","flatClone","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","newRxError","args","schema","getPrimaryFieldOfPrimaryKey","key","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","sortObject","clone","indexes","Array","from","schemaObj","additionalProperties","hasOwnProperty","keyCompression","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","concat","filter","includes","elem","pos","arr","indexOf","index","arIndex","isMaybeReadonlyArray","modifiedIndex","lwt","minimum","RX_META_LWT_MINIMUM","maximum","multipleOf","Object","keys","forEach","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { newRxError } from './rx-error';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types';\nimport { clone, flatClone, isMaybeReadonlyArray, RX_META_LWT_MINIMUM, sortObject, trimDots } from './util';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(/\\./g, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = objectPath.get(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n const cloned = flatClone(documentData);\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (cloned as any)[primaryPath] = newPrimary;\n return cloned;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = objectPath.get(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n // TODO do we need the deep clone() here?\n const normalizedSchema: RxJsonSchema = sortObject(clone(jsonSchema));\n\n // indexes must NOT be sorted because sort order is important here.\n if (jsonSchema.indexes) {\n normalizedSchema.indexes = Array.from(jsonSchema.indexes);\n }\n\n // primaryKey.fields must NOT be sorted because sort order is important here.\n if (\n typeof normalizedSchema.primaryKey === 'object' &&\n typeof jsonSchema.primaryKey === 'object'\n ) {\n normalizedSchema.primaryKey.fields = jsonSchema.primaryKey.fields;\n }\n\n\n\n return normalizedSchema;\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!schemaObj.hasOwnProperty('keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n /**\n * TODO we should not need to add the internal fields to the schema.\n * Better remove the fields before validation.\n */\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n schemaObj.required = schemaObj.required\n .concat(finalFields as any)\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (schemaObj.indexes) {\n schemaObj.indexes = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n if (!arIndex.includes(primaryPath)) {\n const modifiedIndex = arIndex.slice(0);\n modifiedIndex.push(primaryPath);\n return modifiedIndex;\n }\n return arIndex;\n });\n }\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AAWA;AAEA;AACA;AACA;AACA;AACO,SAASA,yBAAyB,CACrCC,OAAe,EACfC,UAAyB,EACM;EAAA;EAC/B,IAAMC,YAA6C,GAAGC,uBAAuB,CAAC;IAC1EH,OAAO,EAAPA,OAAO;IACPI,IAAI,EAAE,QAAQ;IACdH,UAAU,EAAEA,UAAiB;IAC7BI,UAAU,iCACLJ,UAAU,IAAG;MACVG,IAAI,EAAE,QAAQ;MACdE,SAAS,EAAE;IACf,CAAC,cACG;IACRC,QAAQ,EAAE,CAACN,UAAU;EACzB,CAAC,CAAC;EACF,OAAOC,YAAY;AACvB;;AAEA;AACA;AACA;AACO,SAASM,qBAAqB,CACjCC,YAA6B,EAC7BC,IAAsB,EACZ;EACV,IAAIC,OAAe,GAAGD,IAAc;EACpCC,OAAO,GAAGA,OAAO,CAACC,OAAO,CAAC,KAAK,EAAE,cAAc,CAAC;EAChDD,OAAO,GAAG,aAAa,GAAGA,OAAO;EACjCA,OAAO,GAAG,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ACJ;AACA;AACA;EACI7B,oBAAoB,EAAE,IAAW;EACjCvC,QAAQ,EAAE,CACN,KAAK;AAEb,CAAC;;AAGD;AACA;AACA;AACA;AAHA;AAIO,SAASoD,cAAc,CAC1BxC,UAA2B,EACnB;EACR,IAAML,GAAG,GAAG8D,MAAM,CAACC,IAAI,CAAC1D,UAAU,CAACd,UAAU,CAAC,CACzCwD,MAAM,CAAC,UAAA/B,GAAG;IAAA,OAAKX,UAAU,CAASd,UAAU,CAACyB,GAAG,CAAC,SAAM;EAAA,EAAC;;EAE7D;EACA,IAAMZ,WAAW,GAAGW,2BAA2B,CAACV,UAAU,CAAClB,UAAU,CAAC;EACtEa,GAAG,CAAC2C,IAAI,CAACvC,WAAW,CAAC;;EAErB;EACA,IAAI,OAAOC,UAAU,CAAClB,UAAU,KAAK,QAAQ,EAAE;IAC1CkB,UAAU,CAAClB,UAAU,CAA4B+B,MAAM,CACnD8C,OAAO,CAAC,UAAA5C,KAAK;MAAA,OAAIpB,GAAG,CAAC2C,IAAI,CAACvB,KAAK,CAAW;IAAA,EAAC;EACpD;EAEA,OAAOpB,GAAG;AACd;AAGO,IAAMiE,yBAA+E,GAAG;EAC3F3E,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACR2E,EAAE,EAAE;MACA5E,IAAI,EAAE;IACV,CAAC;IACDmE,GAAG,EAAE;MACDnE,IAAI,EAAE;IACV;EACJ,CAAC;EACDG,QAAQ,EAAE,CACN,IAAI,EACJ,KAAK,CACR;EACDuC,oBAAoB,EAAE;AAC1B,CAAU;AAAC"} \ No newline at end of file +{"version":3,"file":"rx-schema-helper.js","names":["getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","trimDots","ret","objectPath","get","fillPrimaryKey","primaryPath","jsonSchema","documentData","cloned","flatClone","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","newRxError","args","schema","getPrimaryFieldOfPrimaryKey","key","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","sortObject","schemaObj","additionalProperties","hasOwnProperty","keyCompression","indexes","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","concat","filter","includes","elem","pos","arr","indexOf","index","arIndex","isMaybeReadonlyArray","modifiedIndex","lwt","minimum","RX_META_LWT_MINIMUM","maximum","multipleOf","Object","keys","forEach","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import objectPath from 'object-path';\nimport { newRxError } from './rx-error';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types';\nimport {\n flatClone,\n isMaybeReadonlyArray,\n RX_META_LWT_MINIMUM,\n sortObject,\n trimDots\n} from './plugins/utils';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(/\\./g, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = objectPath.get(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n const cloned = flatClone(documentData);\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (cloned as any)[primaryPath] = newPrimary;\n return cloned;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = objectPath.get(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n const normalizedSchema: RxJsonSchema = sortObject(jsonSchema, true);\n return normalizedSchema;\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!schemaObj.hasOwnProperty('keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n /**\n * TODO we should not need to add the internal fields to the schema.\n * Better remove the fields before validation.\n */\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n schemaObj.required = schemaObj.required\n .concat(finalFields as any)\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (schemaObj.indexes) {\n schemaObj.indexes = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n if (!arIndex.includes(primaryPath)) {\n const modifiedIndex = arIndex.slice(0);\n modifiedIndex.push(primaryPath);\n return modifiedIndex;\n }\n return arIndex;\n });\n }\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AACA;AAWA;AAQA;AACA;AACA;AACA;AACO,SAASA,yBAAyB,CACrCC,OAAe,EACfC,UAAyB,EACM;EAAA;EAC/B,IAAMC,YAA6C,GAAGC,uBAAuB,CAAC;IAC1EH,OAAO,EAAPA,OAAO;IACPI,IAAI,EAAE,QAAQ;IACdH,UAAU,EAAEA,UAAiB;IAC7BI,UAAU,iCACLJ,UAAU,IAAG;MACVG,IAAI,EAAE,QAAQ;MACdE,SAAS,EAAE;IACf,CAAC,cACG;IACRC,QAAQ,EAAE,CAACN,UAAU;EACzB,CAAC,CAAC;EACF,OAAOC,YAAY;AACvB;;AAEA;AACA;AACA;AACO,SAASM,qBAAqB,CACjCC,Y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G,GAAG2D,MAAM,CAACC,IAAI,CAACvD,UAAU,CAACd,UAAU,CAAC,CACzCqD,MAAM,CAAC,UAAA5B,GAAG;IAAA,OAAKX,UAAU,CAASd,UAAU,CAACyB,GAAG,CAAC,SAAM;EAAA,EAAC;;EAE7D;EACA,IAAMZ,WAAW,GAAGW,2BAA2B,CAACV,UAAU,CAAClB,UAAU,CAAC;EACtEa,GAAG,CAACwC,IAAI,CAACpC,WAAW,CAAC;;EAErB;EACA,IAAI,OAAOC,UAAU,CAAClB,UAAU,KAAK,QAAQ,EAAE;IAC1CkB,UAAU,CAAClB,UAAU,CAA4B+B,MAAM,CACnD2C,OAAO,CAAC,UAAAzC,KAAK;MAAA,OAAIpB,GAAG,CAACwC,IAAI,CAACpB,KAAK,CAAW;IAAA,EAAC;EACpD;EAEA,OAAOpB,GAAG;AACd;AAGO,IAAM8D,yBAA+E,GAAG;EAC3FxE,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRwE,EAAE,EAAE;MACAzE,IAAI,EAAE;IACV,CAAC;IACDgE,GAAG,EAAE;MACDhE,IAAI,EAAE;IACV;EACJ,CAAC;EACDG,QAAQ,EAAE,CACN,IAAI,EACJ,KAAK,CACR;EACDmC,oBAAoB,EAAE;AAC1B,CAAU;AAAC"} \ No newline at end of file diff --git a/dist/lib/rx-schema.js b/dist/lib/rx-schema.js index 5910412a1a7..2fd0c887724 100644 --- a/dist/lib/rx-schema.js +++ b/dist/lib/rx-schema.js @@ -12,7 +12,7 @@ exports.isInstanceOf = isInstanceOf; exports.toTypedRxJsonSchema = toTypedRxJsonSchema; var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _hooks = require("./hooks"); var _rxDocument = require("./rx-document"); @@ -52,7 +52,7 @@ var RxSchema = /*#__PURE__*/function () { * fills all unset fields with default-values if set */; _proto.fillObjectWithDefaults = function fillObjectWithDefaults(obj) { - obj = (0, _util.flatClone)(obj); + obj = (0, _utils.flatClone)(obj); Object.entries(this.defaultValues).filter(function (_ref) { var k = _ref[0]; return !obj.hasOwnProperty(k) || typeof obj[k] === 'undefined'; @@ -71,7 +71,7 @@ var RxSchema = /*#__PURE__*/function () { _proto.getDocumentPrototype = function getDocumentPrototype() { var proto = {}; (0, _rxDocument.defineGetterSetter)(this, proto, ''); - (0, _util.overwriteGetterForCaching)(this, 'getDocumentPrototype', function () { + (0, _utils.overwriteGetterForCaching)(this, 'getDocumentPrototype', function () { return proto; }); return proto; @@ -96,7 +96,7 @@ var RxSchema = /*#__PURE__*/function () { v = _ref4[1]; return values[k] = v["default"]; }); - return (0, _util.overwriteGetterForCaching)(this, 'defaultValues', values); + return (0, _utils.overwriteGetterForCaching)(this, 'defaultValues', values); } /** @@ -105,7 +105,7 @@ var RxSchema = /*#__PURE__*/function () { }, { key: "hash", get: function get() { - return (0, _util.overwriteGetterForCaching)(this, 'hash', (0, _util.fastUnsecureHash)(JSON.stringify(this.jsonSchema))); + return (0, _utils.overwriteGetterForCaching)(this, 'hash', (0, _utils.fastUnsecureHash)(JSON.stringify(this.jsonSchema))); } }]); return RxSchema; @@ -113,7 +113,7 @@ var RxSchema = /*#__PURE__*/function () { exports.RxSchema = RxSchema; function getIndexes(jsonSchema) { return (jsonSchema.indexes || []).map(function (index) { - return (0, _util.isMaybeReadonlyArray)(index) ? index : [index]; + return (0, _utils.isMaybeReadonlyArray)(index) ? index : [index]; }); } diff --git a/dist/lib/rx-schema.js.map b/dist/lib/rx-schema.js.map index 0538e4fa31c..c833886dc6f 100644 --- a/dist/lib/rx-schema.js.map +++ b/dist/lib/rx-schema.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema.js","names":["RxSchema","jsonSchema","indexes","getIndexes","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","finalFields","getFinalFields","validateChange","dataBefore","dataAfter","forEach","fieldName","deepEqual","newRxError","schema","fillObjectWithDefaults","obj","flatClone","Object","entries","defaultValues","filter","k","hasOwnProperty","v","getDocumentPrototype","proto","defineGetterSetter","overwriteGetterForCaching","getPrimaryOfDocumentData","documentData","getComposedPrimaryKeyOfDocumentData","version","values","properties","fastUnsecureHash","JSON","stringify","map","index","isMaybeReadonlyArray","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","runPluginHooks","useJsonSchema","fillWithDefaultSettings","normalizeRxJsonSchema","overwritable","deepFreezeWhenDevMode","isInstanceOf","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\n\nimport {\n overwriteGetterForCaching,\n flatClone,\n isMaybeReadonlyArray,\n fastUnsecureHash\n} from './util';\nimport {\n newRxError,\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport {\n defineGetterSetter\n} from './rx-document';\n\nimport type {\n DeepMutable,\n DeepReadonly, MaybeReadonly,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n normalizeRxJsonSchema\n} from './rx-schema-helper';\nimport { overwritable } from './overwritable';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => (v as any).hasOwnProperty('default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n */\n public get hash(): string {\n return overwriteGetterForCaching(\n this,\n 'hash',\n fastUnsecureHash(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * fills all unset fields with default-values if set\n */\n fillObjectWithDefaults(obj: any): any {\n obj = flatClone(obj);\n Object\n .entries(this.defaultValues)\n .filter(([k]) => !obj.hasOwnProperty(k) || typeof obj[k] === 'undefined')\n .forEach(([k, v]) => obj[k] = v);\n return obj;\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto = {};\n defineGetterSetter(this, proto, '');\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA;AAEA;AAMA;AAGA;AAGA;AAWA;AAOA;AAA8C,IAEjCA,QAAQ;EAKjB,kBACoBC,UAAmD,EACrE;IAAA,KADkBA,UAAmD,GAAnDA,UAAmD;IAEnE,IAAI,CAACC,OAAO,GAAGC,UAAU,CAAC,IAAI,CAACF,UAAU,CAAC;;IAE1C;IACA,IAAI,CAACG,WAAW,GAAG,IAAAC,2CAA2B,EAAC,IAAI,CAACJ,UAAU,CAACK,UAAU,CAAC;IAE1E,IAAI,CAACC,WAAW,GAAG,IAAAC,8BAAc,EAAC,IAAI,CAACP,UAAU,CAAC;EACtD;EAAC;EA8BD;AACJ;AACA;AACA;AACA;AACA;EALI,OAMAQ,cAAc,GAAd,wBAAeC,UAAe,EAAEC,SAAc,EAAQ;IAAA;IAClD,IAAI,CAACJ,WAAW,CAACK,OAAO,CAAC,UAAAC,SAAS,EAAI;MAClC,IAAI,CAAC,IAAAC,yBAAS,EAACJ,UAAU,CAACG,SAAS,CAAC,EAAEF,SAAS,CAACE,SAAS,CAAC,CAAC,EAAE;QACzD,MAAM,IAAAE,mBAAU,EAAC,MAAM,EAAE;UACrBL,UAAU,EAAVA,UAAU;UACVC,SAAS,EAATA,SAAS;UACTE,SAAS,EAATA,SAAS;UACTG,MAAM,EAAE,KAAI,CAACf;QACjB,CAAC,CAAC;MACN;IACJ,CAAC,CAAC;EACN;;EAEA;AACJ;AACA,KAFI;EAAA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AEjD,IAAMlC,MAAM,GAAG,IAAIhB,QAAQ,CAACkD,aAAa,CAAC;EAC1C,IAAAD,qBAAc,EAAC,gBAAgB,EAAEjC,MAAM,CAAC;EACxC,OAAOA,MAAM;AACjB;AAEO,SAASuC,YAAY,CAACrC,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAYlB,QAAQ;AAClC;;AAEA;AACA;AACA;AACA;AACO,SAASwD,mBAAmB,CAA4CxC,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB"} \ No newline at end of file +{"version":3,"file":"rx-schema.js","names":["RxSchema","jsonSchema","indexes","getIndexes","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","finalFields","getFinalFields","validateChange","dataBefore","dataAfter","forEach","fieldName","deepEqual","newRxError","schema","fillObjectWithDefaults","obj","flatClone","Object","entries","defaultValues","filter","k","hasOwnProperty","v","getDocumentPrototype","proto","defineGetterSetter","overwriteGetterForCaching","getPrimaryOfDocumentData","documentData","getComposedPrimaryKeyOfDocumentData","version","values","properties","fastUnsecureHash","JSON","stringify","map","index","isMaybeReadonlyArray","getPreviousVersions","c","Array","fill","createRxSchema","runPreCreateHooks","runPluginHooks","useJsonSchema","fillWithDefaultSettings","normalizeRxJsonSchema","overwritable","deepFreezeWhenDevMode","isInstanceOf","toTypedRxJsonSchema"],"sources":["../../src/rx-schema.ts"],"sourcesContent":["import deepEqual from 'fast-deep-equal';\n\nimport {\n overwriteGetterForCaching,\n flatClone,\n isMaybeReadonlyArray,\n fastUnsecureHash\n} from './plugins/utils';\nimport {\n newRxError,\n} from './rx-error';\nimport {\n runPluginHooks\n} from './hooks';\nimport {\n defineGetterSetter\n} from './rx-document';\n\nimport type {\n DeepMutable,\n DeepReadonly, MaybeReadonly,\n RxDocumentData,\n RxJsonSchema,\n StringKeys\n} from './types';\nimport {\n fillWithDefaultSettings,\n getComposedPrimaryKeyOfDocumentData,\n getFinalFields,\n getPrimaryFieldOfPrimaryKey,\n normalizeRxJsonSchema\n} from './rx-schema-helper';\nimport { overwritable } from './overwritable';\n\nexport class RxSchema {\n public indexes: MaybeReadonly[];\n public readonly primaryPath: StringKeys>;\n public finalFields: string[];\n\n constructor(\n public readonly jsonSchema: RxJsonSchema>\n ) {\n this.indexes = getIndexes(this.jsonSchema);\n\n // primary is always required\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.jsonSchema.primaryKey);\n\n this.finalFields = getFinalFields(this.jsonSchema);\n }\n\n public get version(): number {\n return this.jsonSchema.version;\n }\n\n public get defaultValues(): { [P in keyof RxDocType]: RxDocType[P] } {\n const values = {} as { [P in keyof RxDocType]: RxDocType[P] };\n Object\n .entries(this.jsonSchema.properties)\n .filter(([, v]) => (v as any).hasOwnProperty('default'))\n .forEach(([k, v]) => (values as any)[k] = (v as any).default);\n return overwriteGetterForCaching(\n this,\n 'defaultValues',\n values\n );\n }\n\n /**\n * @overrides itself on the first call\n */\n public get hash(): string {\n return overwriteGetterForCaching(\n this,\n 'hash',\n fastUnsecureHash(JSON.stringify(this.jsonSchema))\n );\n }\n\n /**\n * checks if a given change on a document is allowed\n * Ensures that:\n * - final fields are not modified\n * @throws {Error} if not valid\n */\n validateChange(dataBefore: any, dataAfter: any): void {\n this.finalFields.forEach(fieldName => {\n if (!deepEqual(dataBefore[fieldName], dataAfter[fieldName])) {\n throw newRxError('DOC9', {\n dataBefore,\n dataAfter,\n fieldName,\n schema: this.jsonSchema\n });\n }\n });\n }\n\n /**\n * fills all unset fields with default-values if set\n */\n fillObjectWithDefaults(obj: any): any {\n obj = flatClone(obj);\n Object\n .entries(this.defaultValues)\n .filter(([k]) => !obj.hasOwnProperty(k) || typeof obj[k] === 'undefined')\n .forEach(([k, v]) => obj[k] = v);\n return obj;\n }\n\n /**\n * creates the schema-based document-prototype,\n * see RxCollection.getDocumentPrototype()\n */\n public getDocumentPrototype(): any {\n const proto = {};\n defineGetterSetter(this, proto, '');\n overwriteGetterForCaching(\n this,\n 'getDocumentPrototype',\n () => proto\n );\n return proto;\n }\n\n\n getPrimaryOfDocumentData(\n documentData: Partial\n ): string {\n return getComposedPrimaryKeyOfDocumentData(\n this.jsonSchema,\n documentData\n );\n }\n}\n\nexport function getIndexes(\n jsonSchema: RxJsonSchema\n): MaybeReadonly[] {\n return (jsonSchema.indexes || []).map(index => isMaybeReadonlyArray(index) ? index : [index]);\n}\n\n/**\n * array with previous version-numbers\n */\nexport function getPreviousVersions(schema: RxJsonSchema): number[] {\n const version = schema.version ? schema.version : 0;\n let c = 0;\n return new Array(version)\n .fill(0)\n .map(() => c++);\n}\n\nexport function createRxSchema(\n jsonSchema: RxJsonSchema,\n runPreCreateHooks = true\n): RxSchema {\n if (runPreCreateHooks) {\n runPluginHooks('preCreateRxSchema', jsonSchema);\n }\n\n let useJsonSchema = fillWithDefaultSettings(jsonSchema);\n useJsonSchema = normalizeRxJsonSchema(useJsonSchema);\n overwritable.deepFreezeWhenDevMode(useJsonSchema);\n\n const schema = new RxSchema(useJsonSchema);\n runPluginHooks('createRxSchema', schema);\n return schema;\n}\n\nexport function isInstanceOf(obj: any): boolean {\n return obj instanceof RxSchema;\n}\n\n/**\n * Used as helper function the generate the document type out of the schema via typescript.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport function toTypedRxJsonSchema>>(schema: T): DeepMutable {\n return schema as any;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA;AAEA;AAMA;AAGA;AAGA;AAWA;AAOA;AAA8C,IAEjCA,QAAQ;EAKjB,kBACoBC,UAAmD,EACrE;IAAA,KADkBA,UAAmD,GAAnDA,UAAmD;IAEnE,IAAI,CAACC,OAAO,GAAGC,UAAU,CAAC,IAAI,CAACF,UAAU,CAAC;;IAE1C;IACA,IAAI,CAACG,WAAW,GAAG,IAAAC,2CAA2B,EAAC,IAAI,CAACJ,UAAU,CAACK,UAAU,CAAC;IAE1E,IAAI,CAACC,WAAW,GAAG,IAAAC,8BAAc,EAAC,IAAI,CAACP,UAAU,CAAC;EACtD;EAAC;EA8BD;AACJ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AC,GAAG,CAAC;EACT,OAAO,IAAIC,KAAK,CAACX,OAAO,CAAC,CACpBY,IAAI,CAAC,CAAC,CAAC,CACPN,GAAG,CAAC;IAAA,OAAMI,CAAC,EAAE;EAAA,EAAC;AACvB;AAEO,SAASG,cAAc,CAC1B9C,UAA2B,EAEhB;EAAA,IADX+C,iBAAiB,uEAAG,IAAI;EAExB,IAAIA,iBAAiB,EAAE;IACnB,IAAAC,qBAAc,EAAC,mBAAmB,EAAEhD,UAAU,CAAC;EACnD;EAEA,IAAIiD,aAAa,GAAG,IAAAC,uCAAuB,EAAClD,UAAU,CAAC;EACvDiD,aAAa,GAAG,IAAAE,qCAAqB,EAACF,aAAa,CAAC;EACpDG,0BAAY,CAACC,qBAAqB,CAACJ,aAAa,CAAC;EAEjD,IAAMlC,MAAM,GAAG,IAAIhB,QAAQ,CAACkD,aAAa,CAAC;EAC1C,IAAAD,qBAAc,EAAC,gBAAgB,EAAEjC,MAAM,CAAC;EACxC,OAAOA,MAAM;AACjB;AAEO,SAASuC,YAAY,CAACrC,GAAQ,EAAW;EAC5C,OAAOA,GAAG,YAAYlB,QAAQ;AAClC;;AAEA;AACA;AACA;AACA;AACO,SAASwD,mBAAmB,CAA4CxC,MAAS,EAAkB;EACtG,OAAOA,MAAM;AACjB"} \ No newline at end of file diff --git a/dist/lib/rx-storage-helper.js b/dist/lib/rx-storage-helper.js index 7ce0a2c7657..ddb841c3e27 100644 --- a/dist/lib/rx-storage-helper.js +++ b/dist/lib/rx-storage-helper.js @@ -1,5 +1,6 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -10,7 +11,7 @@ exports.ensureRxStorageInstanceParamsAreCorrect = ensureRxStorageInstanceParamsA exports.flatCloneDocWithMeta = flatCloneDocWithMeta; exports.getAttachmentSize = getAttachmentSize; exports.getNewestOfDocumentStates = getNewestOfDocumentStates; -exports.getSingleDocument = void 0; +exports.getSingleDocument = getSingleDocument; exports.getUniqueDeterministicEventKey = getUniqueDeterministicEventKey; exports.getWrappedStorageInstance = getWrappedStorageInstance; exports.hasEncryption = hasEncryption; @@ -19,59 +20,90 @@ exports.storageChangeEventToRxChangeEvent = storageChangeEventToRxChangeEvent; exports.stripAttachmentsDataFromDocument = stripAttachmentsDataFromDocument; exports.stripAttachmentsDataFromRow = stripAttachmentsDataFromRow; exports.throwIfIsStorageWriteError = throwIfIsStorageWriteError; -exports.writeSingle = void 0; +exports.writeSingle = writeSingle; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _overwritable = require("./overwritable"); var _rxError = require("./rx-error"); var _rxSchemaHelper = require("./rx-schema-helper"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * Helper functions for accessing the RxStorage instances. */ + +var INTERNAL_STORAGE_NAME = '_rxdb_internal'; +exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; +var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; +exports.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = RX_DATABASE_LOCAL_DOCS_STORAGE_NAME; +function getSingleDocument(_x, _x2) { + return _getSingleDocument.apply(this, arguments); +} /** * Writes a single document, * throws RxStorageBulkWriteError on failure */ -var writeSingle = function writeSingle(instance, writeRow, context) { - try { - return Promise.resolve(instance.bulkWrite([writeRow], context)).then(function (writeResult) { - if (Object.keys(writeResult.error).length > 0) { - var error = (0, _util.firstPropertyValueOfObject)(writeResult.error); - throw error; - } else { - var ret = (0, _util.firstPropertyValueOfObject)(writeResult.success); - return ret; +function _getSingleDocument() { + _getSingleDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageInstance, documentId) { + var results, doc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return storageInstance.findDocumentsById([documentId], false); + case 2: + results = _context.sent; + doc = results[documentId]; + if (!doc) { + _context.next = 8; + break; + } + return _context.abrupt("return", doc); + case 8: + return _context.abrupt("return", null); + case 9: + case "end": + return _context.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; + }, _callee); + })); + return _getSingleDocument.apply(this, arguments); +} +function writeSingle(_x3, _x4, _x5) { + return _writeSingle.apply(this, arguments); +} /** * Checkpoints must be stackable over another. * This is required form some RxStorage implementations * like the sharding plugin, where a checkpoint only represents * the document state from some, but not all shards. */ -exports.writeSingle = writeSingle; -var getSingleDocument = function getSingleDocument(storageInstance, documentId) { - try { - return Promise.resolve(storageInstance.findDocumentsById([documentId], false)).then(function (results) { - var doc = results[documentId]; - if (doc) { - return doc; - } else { - return null; +function _writeSingle() { + _writeSingle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(instance, writeRow, context) { + var writeResult, error, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return instance.bulkWrite([writeRow], context); + case 2: + writeResult = _context2.sent; + if (!(Object.keys(writeResult.error).length > 0)) { + _context2.next = 8; + break; + } + error = (0, _utils.firstPropertyValueOfObject)(writeResult.error); + throw error; + case 8: + ret = (0, _utils.firstPropertyValueOfObject)(writeResult.success); + return _context2.abrupt("return", ret); + case 10: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.getSingleDocument = getSingleDocument; -var INTERNAL_STORAGE_NAME = '_rxdb_internal'; -exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; -var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; -exports.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = RX_DATABASE_LOCAL_DOCS_STORAGE_NAME; + }, _callee2); + })); + return _writeSingle.apply(this, arguments); +} function stackCheckpoints(checkpoints) { return Object.assign.apply(Object, [{}].concat(checkpoints)); } @@ -94,10 +126,17 @@ function storageChangeEventToRxChangeEvent(isLocal, rxStorageChangeEvent, rxColl function throwIfIsStorageWriteError(collection, documentId, writeData, error) { if (error) { if (error.status === 409) { - throw (0, _rxError.newRxError)('COL19', { + throw (0, _rxError.newRxError)('CONFLICT', { + collection: collection.name, + id: documentId, + writeError: error, + data: writeData + }); + } else if (error.status === 422) { + throw (0, _rxError.newRxError)('VD2', { collection: collection.name, id: documentId, - error: error, + writeError: error, data: writeData }); } else { @@ -119,7 +158,7 @@ function getNewestOfDocumentStates(primaryPath, docs) { ret = doc; } }); - return (0, _util.ensureNotFalsy)(ret); + return (0, _utils.ensureNotFalsy)(ret); } /** @@ -152,7 +191,7 @@ bulkWriteRows, context) { var errors = {}; var changedDocumentIds = []; var eventBulk = { - id: (0, _util.randomCouchString)(10), + id: (0, _utils.randomCouchString)(10), events: [], checkpoint: null, context: context @@ -160,7 +199,7 @@ bulkWriteRows, context) { var attachmentsAdd = []; var attachmentsRemove = []; var attachmentsUpdate = []; - var startTime = (0, _util.now)(); + var startTime = (0, _utils.now)(); var docsByIdIsMap = typeof docsInDb.get === 'function'; bulkWriteRows.forEach(function (writeRow) { var id = writeRow.document[primaryPath]; @@ -180,7 +219,8 @@ bulkWriteRows, context) { documentId: id, isError: true, status: 510, - writeRow: writeRow + writeRow: writeRow, + attachmentId: attachmentId }; errors[id] = attachmentError; } else { @@ -207,7 +247,7 @@ bulkWriteRows, context) { documentData: hasAttachments ? stripAttachmentsDataFromDocument(writeRow.document) : writeRow.document, previousDocumentData: hasAttachments && writeRow.previous ? stripAttachmentsDataFromDocument(writeRow.previous) : writeRow.previous, startTime: startTime, - endTime: (0, _util.now)() + endTime: (0, _utils.now)() }); } } else { @@ -257,7 +297,8 @@ bulkWriteRows, context) { documentInDb: documentInDb, isError: true, status: 510, - writeRow: writeRow + writeRow: writeRow, + attachmentId: attachmentId }; } return true; @@ -309,7 +350,7 @@ bulkWriteRows, context) { previousEventDocumentData = writeRow.previous; } else if (writeDoc._deleted) { operation = 'DELETE'; - eventDocumentData = (0, _util.ensureNotFalsy)(writeRow.document); + eventDocumentData = (0, _utils.ensureNotFalsy)(writeRow.document); previousEventDocumentData = writeRow.previous; } else { throw (0, _rxError.newRxError)('SNH', { @@ -322,11 +363,11 @@ bulkWriteRows, context) { eventBulk.events.push({ eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath, writeRow), documentId: id, - documentData: (0, _util.ensureNotFalsy)(eventDocumentData), + documentData: (0, _utils.ensureNotFalsy)(eventDocumentData), previousDocumentData: previousEventDocumentData, operation: operation, startTime: startTime, - endTime: (0, _util.now)() + endTime: (0, _utils.now)() }); } }); @@ -360,14 +401,14 @@ function attachmentWriteDataToNormalData(writeData) { return writeData; } var ret = { - digest: (0, _util.defaultHashFunction)(data), + digest: (0, _utils.defaultHashFunction)(data), length: getAttachmentSize(data), type: writeData.type }; return ret; } function stripAttachmentsDataFromDocument(doc) { - var useDoc = (0, _util.flatClone)(doc); + var useDoc = (0, _utils.flatClone)(doc); useDoc._attachments = {}; Object.entries(doc._attachments).forEach(function (_ref4) { var attachmentId = _ref4[0], @@ -384,8 +425,8 @@ function stripAttachmentsDataFromDocument(doc) { * during replication etc. */ function flatCloneDocWithMeta(doc) { - var ret = (0, _util.flatClone)(doc); - ret._meta = (0, _util.flatClone)(doc._meta); + var ret = (0, _utils.flatClone)(doc); + ret._meta = (0, _utils.flatClone)(doc._meta); return ret; } @@ -402,7 +443,6 @@ function getUniqueDeterministicEventKey(storageInstance, primaryPath, writeRow) var eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev; return eventKey; } - /** * Wraps the normal storageInstance of a RxCollection * to ensure that all access is properly using the hooks @@ -418,8 +458,8 @@ rxJsonSchema) { _overwritable.overwritable.deepFreezeWhenDevMode(rxJsonSchema); var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(rxJsonSchema.primaryKey); function transformDocumentDataFromRxDBToRxStorage(writeRow) { - var data = (0, _util.flatClone)(writeRow.document); - data._meta = (0, _util.flatClone)(data._meta); + var data = (0, _utils.flatClone)(writeRow.document); + data._meta = (0, _utils.flatClone)(data._meta); /** * Do some checks in dev-mode @@ -469,20 +509,21 @@ rxJsonSchema) { }); } } - data._meta.lwt = (0, _util.now)(); + data._meta.lwt = (0, _utils.now)(); /** * Yes we really want to set the revision here. * If you make a plugin that relies on having its own revision * stored into the storage, use this.originalStorageInstance.bulkWrite() instead. */ - data._rev = (0, _util.createRevision)(database.hashFunction, data, writeRow.previous); + data._rev = (0, _utils.createRevision)(database.token, writeRow.previous); return { document: data, previous: writeRow.previous }; } var ret = { + originalStorageInstance: storageInstance, schema: storageInstance.schema, internals: storageInstance.internals, collectionName: storageInstance.collectionName, @@ -504,22 +545,22 @@ rxJsonSchema) { * @link https://github.com/pubkey/rxdb/pull/3839 */.then(function (writeResult) { var reInsertErrors = Object.values(writeResult.error).filter(function (error) { - if (error.status === 409 && !error.writeRow.previous && !error.writeRow.document._deleted && (0, _util.ensureNotFalsy)(error.documentInDb)._deleted) { + if (error.status === 409 && !error.writeRow.previous && !error.writeRow.document._deleted && (0, _utils.ensureNotFalsy)(error.documentInDb)._deleted) { return true; } return false; }); if (reInsertErrors.length > 0) { var useWriteResult = { - error: (0, _util.flatClone)(writeResult.error), - success: (0, _util.flatClone)(writeResult.success) + error: (0, _utils.flatClone)(writeResult.error), + success: (0, _utils.flatClone)(writeResult.success) }; var reInserts = reInsertErrors.map(function (error) { delete useWriteResult.error[error.documentId]; return { previous: error.documentInDb, document: Object.assign({}, error.writeRow.document, { - _rev: (0, _util.createRevision)(database.hashFunction, error.writeRow.document, error.documentInDb) + _rev: (0, _utils.createRevision)(database.token, error.documentInDb) }) }; }); @@ -556,7 +597,7 @@ rxJsonSchema) { }, getChangedDocumentsSince: function getChangedDocumentsSince(limit, checkpoint) { return database.lockedRun(function () { - return storageInstance.getChangedDocumentsSince((0, _util.ensureNotFalsy)(limit), checkpoint); + return storageInstance.getChangedDocumentsSince((0, _utils.ensureNotFalsy)(limit), checkpoint); }); }, cleanup: function cleanup(minDeletedTime) { @@ -585,11 +626,11 @@ rxJsonSchema) { return storageInstance.resolveConflictResultionTask(taskSolution); } var doc = Object.assign({}, taskSolution.output.documentData, { - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), _attachments: {} }); - var documentData = (0, _util.flatClone)(doc); + var documentData = (0, _utils.flatClone)(doc); delete documentData._meta; delete documentData._rev; delete documentData._attachments; @@ -602,7 +643,6 @@ rxJsonSchema) { }); } }; - ret.originalStorageInstance = storageInstance; return ret; } diff --git a/dist/lib/rx-storage-helper.js.map b/dist/lib/rx-storage-helper.js.map index 10a3a1a6799..3fccfffd97f 100644 --- a/dist/lib/rx-storage-helper.js.map +++ b/dist/lib/rx-storage-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-helper.js","names":["writeSingle","instance","writeRow","context","bulkWrite","writeResult","Object","keys","error","length","firstPropertyValueOfObject","ret","success","getSingleDocument","storageInstance","documentId","findDocumentsById","results","doc","INTERNAL_STORAGE_NAME","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","stackCheckpoints","checkpoints","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","documentData","previousDocumentData","eventId","collectionName","name","undefined","startTime","endTime","operation","overwritable","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","newRxError","id","data","getNewestOfDocumentStates","primaryPath","docs","forEach","_meta","lwt","ensureNotFalsy","categorizeBulkWriteRows","docsInDb","bulkWriteRows","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","changedDocumentIds","eventBulk","randomCouchString","events","checkpoint","attachmentsAdd","attachmentsRemove","attachmentsUpdate","now","docsByIdIsMap","get","document","documentInDb","attachmentError","insertedIsDeleted","_deleted","entries","_attachments","attachmentId","attachmentData","isError","push","stripAttachmentsDataFromRow","getUniqueDeterministicEventKey","stripAttachmentsDataFromDocument","previous","revInDb","_rev","err","updatedRow","find","previousAttachmentData","newDigest","digest","writeDoc","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","defaultHashFunction","type","useDoc","flatClone","flatCloneDocWithMeta","docId","binaryValues","binary","map","v","join","eventKey","databaseName","getWrappedStorageInstance","database","rxJsonSchema","getPrimaryFieldOfPrimaryKey","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","fillPrimaryKey","metaFieldName","hasOwnProperty","dataBefore","dataAfter","createRevision","hashFunction","internals","options","rows","toStorageWriteRows","row","lockedRun","then","reInsertErrors","values","filter","useWriteResult","reInserts","subResult","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","close","changeStream","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","getDefaultRxDocumentMeta","getDefaultRevision","originalStorageInstance","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","jsonSchema","encrypted"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable';\nimport { newRxError } from './rx-error';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n ById,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageBulkWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys\n} from './types';\nimport {\n createRevision,\n defaultHashFunction,\n ensureNotFalsy,\n firstPropertyValueOfObject,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now,\n randomCouchString\n} from './util';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | null> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[documentId];\n if (doc) {\n return doc;\n } else {\n return null;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (Object.keys(writeResult.error).length > 0) {\n const error = firstPropertyValueOfObject(writeResult.error);\n throw error;\n } else {\n const ret = firstPropertyValueOfObject(writeResult.success);\n return ret;\n }\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n eventId: rxStorageChangeEvent.eventId,\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n startTime: rxStorageChangeEvent.startTime,\n endTime: rxStorageChangeEvent.endTime,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageBulkWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('COL19', {\n collection: collection.name,\n id: documentId,\n error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * From a list of documents,\n * it will return the document that has the 'newest' state\n * which must be used to create the correct checkpoint\n * for the whole list.\n */\nexport function getNewestOfDocumentStates(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData {\n let ret: RxDocumentData | null = null;\n docs.forEach(doc => {\n if (\n !ret ||\n doc._meta.lwt > ret._meta.lwt ||\n (\n doc._meta.lwt === ret._meta.lwt &&\n (doc as any)[primaryPath] > (ret as any)[primaryPath]\n )\n ) {\n ret = doc;\n }\n\n });\n return ensureNotFalsy(ret as any);\n}\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This can be a Map for better performance\n * but it can also be an object because some storages\n * need to work with something that is JSON-stringify-able\n * and we do not want to transform a big object into a Map\n * each time we use it.\n */\n docsInDb:\n Map[StringKeys] | string, RxDocumentData> |\n ById>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: ById> = {};\n const changedDocumentIds: RxDocType[StringKeys][] = [];\n const eventBulk: EventBulk>, any> = {\n id: randomCouchString(10),\n events: [],\n checkpoint: null,\n context\n };\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n\n\n const startTime = now();\n\n const docsByIdIsMap = typeof docsInDb.get === 'function';\n\n bulkWriteRows.forEach(writeRow => {\n const id = writeRow.document[primaryPath];\n const documentInDb = docsByIdIsMap ? (docsInDb as any).get(id) : (docsInDb as any)[id];\n let attachmentError: RxStorageBulkWriteError | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = writeRow.document._deleted ? true : false;\n Object.entries(writeRow.document._attachments).forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n isError: true,\n status: 510,\n writeRow\n };\n errors[id as any] = attachmentError;\n } else {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n }\n });\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n } else {\n bulkInsertDocs.push(writeRow as any);\n }\n }\n\n if (!insertedIsDeleted) {\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n operation: 'INSERT',\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(writeRow.document) : writeRow.document as any,\n previousDocumentData: hasAttachments && writeRow.previous ? stripAttachmentsDataFromDocument(writeRow.previous) : writeRow.previous as any,\n startTime,\n endTime: now()\n });\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !writeRow.previous\n ) ||\n (\n !!writeRow.previous &&\n revInDb !== writeRow.previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageBulkWriteError = {\n isError: true,\n status: 409,\n documentId: id as any,\n writeRow: writeRow,\n documentInDb\n };\n errors[id as any] = err;\n return;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (writeRow.document._deleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (writeRow.previous) {\n Object\n .keys(writeRow.previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: id as any,\n attachmentId\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(writeRow.document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n documentInDb: documentInDb,\n isError: true,\n status: 510,\n writeRow\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(writeRow.document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData\n });\n }\n }\n });\n }\n }\n if (attachmentError) {\n errors[id as any] = attachmentError;\n } else {\n bulkUpdateDocs.push(updatedRow);\n }\n\n const writeDoc = writeRow.document;\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (writeRow.previous && writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n } else if (writeRow.previous && !writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n previousEventDocumentData = writeRow.previous;\n } else if (writeDoc._deleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(writeRow.document) as any;\n previousEventDocumentData = writeRow.previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n documentData: ensureNotFalsy(eventDocumentData),\n previousDocumentData: previousEventDocumentData,\n operation: operation,\n startTime,\n endTime: now()\n });\n }\n });\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n errors,\n changedDocumentIds,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n digest: defaultHashFunction(data),\n length: getAttachmentSize(data),\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\n/**\n * Each event is labeled with the id\n * to make it easy to filter out duplicates.\n */\nexport function getUniqueDeterministicEventKey(\n storageInstance: RxStorageInstance,\n primaryPath: string,\n writeRow: BulkWriteRow\n): string {\n const docId = writeRow.document[primaryPath];\n const binaryValues: boolean[] = [\n !!writeRow.previous,\n (writeRow.previous && writeRow.previous._deleted),\n !!writeRow.document._deleted\n ];\n const binary = binaryValues.map(v => v ? '1' : '0').join('');\n const eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev;\n return eventKey;\n}\n\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): RxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!writeRow.document._meta.hasOwnProperty(metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.hashFunction,\n data,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: RxStorageInstance = {\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const reInsertErrors: RxStorageBulkWriteError[] = Object\n .values(writeResult.error)\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n return false;\n });\n\n if (reInsertErrors.length > 0) {\n const useWriteResult: typeof writeResult = {\n error: flatClone(writeResult.error),\n success: flatClone(writeResult.success)\n };\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n delete useWriteResult.error[error.documentId];\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.hashFunction,\n error.writeRow.document,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n useWriteResult.error = Object.assign(\n useWriteResult.error,\n subResult.error\n );\n useWriteResult.success = Object.assign(\n useWriteResult.success,\n subResult.success\n );\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId)\n );\n },\n getChangedDocumentsSince(limit: number, checkpoint?: any) {\n return database.lockedRun(\n () => storageInstance.getChangedDocumentsSince(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n (ret as any).originalStorageInstance = storageInstance;\n\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAIA;AACA;AACA;AAwBA;AA9BA;AACA;AACA;AAwDA;AACA;AACA;AACA;AAHA,IAIsBA,WAAW,YAAXA,WAAW,CAC7BC,QAAgD,EAChDC,QAAiC,EACjCC,OAAe;EAAA,IACmB;IAAA,uBACRF,QAAQ,CAACG,SAAS,CACxC,CAACF,QAAQ,CAAC,EACVC,OAAO,CACV,iBAHKE,WAAW;MAAA,IAIbC,MAAM,CAACC,IAAI,CAACF,WAAW,CAACG,KAAK,CAAC,CAACC,MAAM,GAAG,CAAC;QACzC,IAAMD,KAAK,GAAG,IAAAE,gCAA0B,EAACL,WAAW,CAACG,KAAK,CAAC;QAC3D,MAAMA,KAAK;MA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7G,MAAM,CAAC,EAAE;IAC9B,MAAM,IAAAd,mBAAU,EAAC,KAAK,EAAE;MAAEwD,IAAI,EAAE;QAAEmE,MAAM,EAANA;MAAO;IAAE,CAAC,CAAC;EACjD;AACJ;AAEO,SAASE,aAAa,CAACC,UAA6B,EAAW;EAClE,IACK,CAAC,CAACA,UAAU,CAACC,SAAS,IAAID,UAAU,CAACC,SAAS,CAACjK,MAAM,GAAG,CAAC,IACzDgK,UAAU,CAAC/G,WAAW,IAAI+G,UAAU,CAAC/G,WAAW,CAACgH,SAAU,EAC9D;IACE,OAAO,IAAI;EACf,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file +{"version":3,"file":"rx-storage-helper.js","names":["INTERNAL_STORAGE_NAME","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","getSingleDocument","storageInstance","documentId","findDocumentsById","results","doc","writeSingle","instance","writeRow","context","bulkWrite","writeResult","Object","keys","error","length","firstPropertyValueOfObject","ret","success","stackCheckpoints","checkpoints","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","documentData","previousDocumentData","eventId","collectionName","name","undefined","startTime","endTime","operation","overwritable","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","newRxError","id","writeError","data","getNewestOfDocumentStates","primaryPath","docs","forEach","_meta","lwt","ensureNotFalsy","categorizeBulkWriteRows","docsInDb","bulkWriteRows","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","changedDocumentIds","eventBulk","randomCouchString","events","checkpoint","attachmentsAdd","attachmentsRemove","attachmentsUpdate","now","docsByIdIsMap","get","document","documentInDb","attachmentError","insertedIsDeleted","_deleted","entries","_attachments","attachmentId","attachmentData","isError","push","stripAttachmentsDataFromRow","getUniqueDeterministicEventKey","stripAttachmentsDataFromDocument","previous","revInDb","_rev","err","updatedRow","find","previousAttachmentData","newDigest","digest","writeDoc","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","defaultHashFunction","type","useDoc","flatClone","flatCloneDocWithMeta","docId","binaryValues","binary","map","v","join","eventKey","databaseName","getWrappedStorageInstance","database","rxJsonSchema","getPrimaryFieldOfPrimaryKey","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","fillPrimaryKey","metaFieldName","hasOwnProperty","dataBefore","dataAfter","createRevision","token","originalStorageInstance","internals","options","rows","toStorageWriteRows","row","lockedRun","then","reInsertErrors","values","filter","useWriteResult","reInserts","subResult","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","close","changeStream","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","getDefaultRxDocumentMeta","getDefaultRevision","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","jsonSchema","encrypted"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable';\nimport { newRxError } from './rx-error';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n ById,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys,\n RxStorageWriteErrorConflict,\n RxStorageWriteErrorAttachment\n} from './types';\nimport {\n createRevision,\n defaultHashFunction,\n ensureNotFalsy,\n firstPropertyValueOfObject,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n now,\n randomCouchString\n} from './plugins/utils';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | null> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[documentId];\n if (doc) {\n return doc;\n } else {\n return null;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (Object.keys(writeResult.error).length > 0) {\n const error = firstPropertyValueOfObject(writeResult.error);\n throw error;\n } else {\n const ret = firstPropertyValueOfObject(writeResult.success);\n return ret;\n }\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n eventId: rxStorageChangeEvent.eventId,\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n startTime: rxStorageChangeEvent.startTime,\n endTime: rxStorageChangeEvent.endTime,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('CONFLICT', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else if (error.status === 422) {\n throw newRxError('VD2', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * From a list of documents,\n * it will return the document that has the 'newest' state\n * which must be used to create the correct checkpoint\n * for the whole list.\n */\nexport function getNewestOfDocumentStates(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData {\n let ret: RxDocumentData | null = null;\n docs.forEach(doc => {\n if (\n !ret ||\n doc._meta.lwt > ret._meta.lwt ||\n (\n doc._meta.lwt === ret._meta.lwt &&\n (doc as any)[primaryPath] > (ret as any)[primaryPath]\n )\n ) {\n ret = doc;\n }\n\n });\n return ensureNotFalsy(ret as any);\n}\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This can be a Map for better performance\n * but it can also be an object because some storages\n * need to work with something that is JSON-stringify-able\n * and we do not want to transform a big object into a Map\n * each time we use it.\n */\n docsInDb:\n Map[StringKeys] | string, RxDocumentData> |\n ById>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: ById> = {};\n const changedDocumentIds: RxDocType[StringKeys][] = [];\n const eventBulk: EventBulk>, any> = {\n id: randomCouchString(10),\n events: [],\n checkpoint: null,\n context\n };\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[] = [];\n\n\n const startTime = now();\n\n const docsByIdIsMap = typeof docsInDb.get === 'function';\n\n bulkWriteRows.forEach(writeRow => {\n const id = writeRow.document[primaryPath];\n const documentInDb = docsByIdIsMap ? (docsInDb as any).get(id) : (docsInDb as any)[id];\n let attachmentError: RxStorageWriteErrorAttachment | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = writeRow.document._deleted ? true : false;\n Object.entries(writeRow.document._attachments).forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n errors[id as any] = attachmentError;\n } else {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n }\n });\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n } else {\n bulkInsertDocs.push(writeRow as any);\n }\n }\n\n if (!insertedIsDeleted) {\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n operation: 'INSERT',\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(writeRow.document) : writeRow.document as any,\n previousDocumentData: hasAttachments && writeRow.previous ? stripAttachmentsDataFromDocument(writeRow.previous) : writeRow.previous as any,\n startTime,\n endTime: now()\n });\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !writeRow.previous\n ) ||\n (\n !!writeRow.previous &&\n revInDb !== writeRow.previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageWriteError = {\n isError: true,\n status: 409,\n documentId: id as any,\n writeRow: writeRow,\n documentInDb\n };\n errors[id as any] = err;\n return;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (writeRow.document._deleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (writeRow.previous) {\n Object\n .keys(writeRow.previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: id as any,\n attachmentId\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(writeRow.document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: id as any,\n documentInDb,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(writeRow.document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = writeRow.previous ? writeRow.previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as any\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: id as any,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData\n });\n }\n }\n });\n }\n }\n if (attachmentError) {\n errors[id as any] = attachmentError;\n } else {\n bulkUpdateDocs.push(updatedRow);\n }\n\n const writeDoc = writeRow.document;\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (writeRow.previous && writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n } else if (writeRow.previous && !writeRow.previous._deleted && !writeDoc._deleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(writeDoc) : writeDoc as any;\n previousEventDocumentData = writeRow.previous;\n } else if (writeDoc._deleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(writeRow.document) as any;\n previousEventDocumentData = writeRow.previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n changedDocumentIds.push(id);\n eventBulk.events.push({\n eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath as any, writeRow),\n documentId: id as any,\n documentData: ensureNotFalsy(eventDocumentData),\n previousDocumentData: previousEventDocumentData,\n operation: operation,\n startTime,\n endTime: now()\n });\n }\n });\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n errors,\n changedDocumentIds,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n digest: defaultHashFunction(data),\n length: getAttachmentSize(data),\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\n/**\n * Each event is labeled with the id\n * to make it easy to filter out duplicates.\n */\nexport function getUniqueDeterministicEventKey(\n storageInstance: RxStorageInstance,\n primaryPath: string,\n writeRow: BulkWriteRow\n): string {\n const docId = writeRow.document[primaryPath];\n const binaryValues: boolean[] = [\n !!writeRow.previous,\n (writeRow.previous && writeRow.previous._deleted),\n !!writeRow.document._deleted\n ];\n const binary = binaryValues.map(v => v ? '1' : '0').join('');\n const eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev;\n return eventKey;\n}\n\n\nexport type WrappedRxStorageInstance = RxStorageInstance & {\n originalStorageInstance: RxStorageInstance;\n};\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): WrappedRxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!writeRow.document._meta.hasOwnProperty(metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.token,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: WrappedRxStorageInstance = {\n originalStorageInstance: storageInstance,\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const reInsertErrors: RxStorageWriteErrorConflict[] = Object\n .values(writeResult.error)\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n return false;\n }) as any;\n\n if (reInsertErrors.length > 0) {\n const useWriteResult: typeof writeResult = {\n error: flatClone(writeResult.error),\n success: flatClone(writeResult.success)\n };\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n delete useWriteResult.error[error.documentId];\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.token,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n useWriteResult.error = Object.assign(\n useWriteResult.error,\n subResult.error\n );\n useWriteResult.success = Object.assign(\n useWriteResult.success,\n subResult.success\n );\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId)\n );\n },\n getChangedDocumentsSince(limit: number, checkpoint?: any) {\n return database.lockedRun(\n () => storageInstance.getChangedDocumentsSince(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAIA;AACA;AACA;AA0BA;AAhCA;AACA;AACA;;AA0CO,IAAMA,qBAAqB,GAAG,gBAAgB;AAAC;AAC/C,IAAMC,mCAAmC,GAAG,0BAA0B;AAAC;AAAA,SAExDC,iBAAiB;EAAA;AAAA;AAavC;AACA;AACA;AACA;AAHA;EAAA,mGAbO,iBACHC,eAAuD,EACvDC,UAAkB;IAAA;IAAA;MAAA;QAAA;UAAA;UAAA,OAEID,eAAe,CAACE,iBAAiB,CAAC,CAACD,UAAU,CAAC,EAAE,KAAK,CAAC;QAAA;UAAtEE,OAAO;UACPC,GAAG,GAAGD,OAAO,CAACF,UAAU,CAAC;UAAA,KAC3BG,GAAG;YAAA;YAAA;UAAA;UAAA,iCACIA,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,EAAZA;QACJ;MACJ,CAAC,CAAC;IACN;EACJ,CAAC;EAED,OAAOT,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASmJ,uCAAuC,CACnDC,MAAiD,EACnD;EACE,IAAIA,MAAM,CAAC7G,MAAM,CAAC8G,cAAc,EAAE;IAC9B,MAAM,IAAA7H,mBAAU,EAAC,KAAK,EAAE;MAAEyD,IAAI,EAAE;QAAEmE,MAAM,EAANA;MAAO;IAAE,CAAC,CAAC;EACjD;EACA,IAAIE,aAAa,CAACF,MAAM,CAAC7G,MAAM,CAAC,EAAE;IAC9B,MAAM,IAAAf,mBAAU,EAAC,KAAK,EAAE;MAAEyD,IAAI,EAAE;QAAEmE,MAAM,EAANA;MAAO;IAAE,CAAC,CAAC;EACjD;AACJ;AAEO,SAASE,aAAa,CAACC,UAA6B,EAAW;EAClE,IACK,CAAC,CAACA,UAAU,CAACC,SAAS,IAAID,UAAU,CAACC,SAAS,CAAC1J,MAAM,GAAG,CAAC,IACzDyJ,UAAU,CAAC/G,WAAW,IAAI+G,UAAU,CAAC/G,WAAW,CAACgH,SAAU,EAC9D;IACE,OAAO,IAAI;EACf,CAAC,MAAM;IACH,OAAO,KAAK;EAChB;AACJ"} \ No newline at end of file diff --git a/dist/lib/rx-storage-multiinstance.js b/dist/lib/rx-storage-multiinstance.js index 8480d87572b..a636bdb041d 100644 --- a/dist/lib/rx-storage-multiinstance.js +++ b/dist/lib/rx-storage-multiinstance.js @@ -1,5 +1,6 @@ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -7,6 +8,8 @@ exports.BROADCAST_CHANNEL_BY_TOKEN = void 0; exports.addRxStorageMultiInstanceSupport = addRxStorageMultiInstanceSupport; exports.getBroadcastChannelReference = getBroadcastChannelReference; exports.removeBroadcastChannelReference = removeBroadcastChannelReference; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); var _broadcastChannel = require("broadcast-channel"); @@ -103,40 +106,48 @@ providedBroadcastChannel) { return changesFromOtherInstances$.asObservable().pipe((0, _operators.mergeWith)(oldChangestream$)); }; var oldClose = instance.close.bind(instance); - instance.close = function () { - try { - closed = true; - sub.unsubscribe(); - broadcastChannel.removeEventListener('message', eventListener); - var _temp = function () { - if (!providedBroadcastChannel) { - return Promise.resolve(removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance)).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return oldClose(); - }) : oldClose()); - } catch (e) { - return Promise.reject(e); - } - }; + instance.close = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + closed = true; + sub.unsubscribe(); + broadcastChannel.removeEventListener('message', eventListener); + if (providedBroadcastChannel) { + _context.next = 6; + break; + } + _context.next = 6; + return removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance); + case 6: + return _context.abrupt("return", oldClose()); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); var oldRemove = instance.remove.bind(instance); - instance.remove = function () { - try { - closed = true; - sub.unsubscribe(); - broadcastChannel.removeEventListener('message', eventListener); - var _temp2 = function () { - if (!providedBroadcastChannel) { - return Promise.resolve(removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance)).then(function () {}); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(function () { - return oldRemove(); - }) : oldRemove()); - } catch (e) { - return Promise.reject(e); - } - }; + instance.remove = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + closed = true; + sub.unsubscribe(); + broadcastChannel.removeEventListener('message', eventListener); + if (providedBroadcastChannel) { + _context2.next = 6; + break; + } + _context2.next = 6; + return removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance); + case 6: + return _context2.abrupt("return", oldRemove()); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); } //# sourceMappingURL=rx-storage-multiinstance.js.map \ No newline at end of file diff --git a/dist/lib/rx-storage-multiinstance.js.map b/dist/lib/rx-storage-multiinstance.js.map index 53469d7860b..0f394d9f9ad 100644 --- a/dist/lib/rx-storage-multiinstance.js.map +++ b/dist/lib/rx-storage-multiinstance.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-multiinstance.js","names":["BROADCAST_CHANNEL_BY_TOKEN","Map","getBroadcastChannelReference","databaseInstanceToken","databaseName","refObject","state","get","bc","BroadcastChannel","refs","Set","set","add","removeBroadcastChannelReference","size","close","addRxStorageMultiInstanceSupport","storageName","instanceCreationParams","instance","providedBroadcastChannel","multiInstance","broadcastChannel","changesFromOtherInstances$","Subject","eventListener","msg","collectionName","version","schema","next","eventBulk","addEventListener","oldChangestream$","changeStream","closed","sub","subscribe","postMessage","asObservable","pipe","mergeWith","oldClose","bind","unsubscribe","removeEventListener","oldRemove","remove"],"sources":["../../src/rx-storage-multiinstance.ts"],"sourcesContent":["/**\n * When a persistend RxStorage is used in more the one JavaScript process,\n * the even stream of the changestream() function must be broadcasted to the other\n * RxStorageInstances of the same databaseName+collectionName.\n *\n * In the past this was done by RxDB but it makes more sense to do this\n * at the RxStorage level so that the broadcasting etc can all happen inside of a WebWorker\n * and not on the main thread.\n * Also it makes it less complex to stack up different RxStorages onto each other\n * like what we do with the in-memory plugin.\n *\n * This is intened to be used inside of createStorageInstance() of a storage.\n * Do not use this if the storage anyway broadcasts the events like when using MongoDB\n * or in the future W3C might introduce a way to listen to IndexedDB changes.\n */\n\nimport { Observable, Subject } from 'rxjs';\nimport { mergeWith } from 'rxjs/operators';\nimport type {\n EventBulk,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\n\nimport {\n BroadcastChannel\n} from 'broadcast-channel';\n\n/**\n * The broadcast-channel is reused by the databaseInstanceToken.\n * This is required so that it is easy to simulate multi-tab usage\n * in the test where different instances of the same RxDatabase must\n * have different broadcast channels.\n * But also it ensures that for each RxDatabase we only create a single\n * broadcast channel that can even be reused in the leader election plugin.\n *\n * TODO at the end of the unit tests,\n * we should ensure that all channels are closed and cleaned up.\n * Otherwise we have forgot something.\n */\nexport const BROADCAST_CHANNEL_BY_TOKEN: Map;\n /**\n * Contains all context objects that currently use the channel.\n * If this becomes empty, we can close the channel\n */\n refs: Set;\n}> = new Map();\n\n\nexport type RxStorageMultiInstanceBroadcastType = {\n storageName: string;\n collectionName: string;\n /**\n * collection.schema.version\n */\n version: number;\n databaseName: string;\n eventBulk: EventBulk;\n};\n\nexport function getBroadcastChannelReference(\n databaseInstanceToken: string,\n databaseName: string,\n refObject: any\n): BroadcastChannel {\n let state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n state = {\n /**\n * We have to use the databaseName instead of the databaseInstanceToken\n * in the BroadcastChannel name because different instances must end with the same\n * channel name to be able to broadcast messages between each other.\n */\n bc: new BroadcastChannel('RxDB:' + databaseName),\n refs: new Set()\n };\n BROADCAST_CHANNEL_BY_TOKEN.set(databaseInstanceToken, state);\n }\n state.refs.add(refObject);\n return state.bc;\n}\n\nexport function removeBroadcastChannelReference(\n databaseInstanceToken: string,\n refObject: any\n) {\n const state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n return;\n }\n state.refs.delete(refObject);\n if (state.refs.size === 0) {\n BROADCAST_CHANNEL_BY_TOKEN.delete(databaseInstanceToken);\n return state.bc.close();\n }\n}\n\n\nexport function addRxStorageMultiInstanceSupport(\n storageName: string,\n instanceCreationParams: RxStorageInstanceCreationParams,\n instance: RxStorageInstance,\n /**\n * If provided, that channel will be used\n * instead of an own one.\n */\n providedBroadcastChannel?: BroadcastChannel\n) {\n if (!instanceCreationParams.multiInstance) {\n return;\n }\n\n type Emit = EventBulk, any>;\n\n const broadcastChannel = providedBroadcastChannel ?\n providedBroadcastChannel :\n getBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance.databaseName,\n instance\n );\n\n const changesFromOtherInstances$: Subject = new Subject();\n\n\n const eventListener = (msg: RxStorageMultiInstanceBroadcastType) => {\n if (\n msg.storageName === storageName &&\n msg.databaseName === instanceCreationParams.databaseName &&\n msg.collectionName === instanceCreationParams.collectionName &&\n msg.version === instanceCreationParams.schema.version\n ) {\n changesFromOtherInstances$.next(msg.eventBulk);\n }\n };\n broadcastChannel.addEventListener('message', eventListener);\n\n const oldChangestream$ = instance.changeStream();\n\n let closed = false;\n const sub = oldChangestream$.subscribe(eventBulk => {\n if (closed) {\n return;\n }\n broadcastChannel.postMessage({\n storageName: storageName,\n databaseName: instanceCreationParams.databaseName,\n collectionName: instanceCreationParams.collectionName,\n version: instanceCreationParams.schema.version,\n eventBulk\n });\n });\n\n instance.changeStream = function (): Observable {\n return changesFromOtherInstances$.asObservable().pipe(\n mergeWith(oldChangestream$)\n );\n };\n\n const oldClose = instance.close.bind(instance);\n instance.close = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldClose();\n };\n\n const oldRemove = instance.remove.bind(instance);\n instance.remove = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldRemove();\n };\n}\n"],"mappings":";;;;;;;;;AAgBA;AACA;AAQA;AAzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AAQ,CAACJ,KAAK;IAAA,IAAqB;MAC/BoB,MAAM,GAAG,IAAI;MACbC,GAAG,CAACQ,WAAW,EAAE;MACjBtB,gBAAgB,CAACuB,mBAAmB,CAAC,SAAS,EAAEpB,aAAa,CAAC;MAAC;QAAA,IAC3D,CAACL,wBAAwB;UAAA,uBACnBP,+BAA+B,CACjCK,sBAAsB,CAAChB,qBAAqB,EAC5CiB,QAAQ,CACX;QAAA;MAAA;MAAA;QAEL,OAAOuB,QAAQ,EAAE;MAAC,KAAXA,QAAQ,EAAE;IACrB,CAAC;MAAA;IAAA;EAAA;EAED,IAAMI,SAAS,GAAG3B,QAAQ,CAAC4B,MAAM,CAACJ,IAAI,CAACxB,QAAQ,CAAC;EAChDA,QAAQ,CAAC4B,MAAM;IAAA,IAAqB;MAChCZ,MAAM,GAAG,IAAI;MACbC,GAAG,CAACQ,WAAW,EAAE;MACjBtB,gBAAgB,CAACuB,mBAAmB,CAAC,SAAS,EAAEpB,aAAa,CAAC;MAAC;QAAA,IAC3D,CAACL,wBAAwB;UAAA,uBACnBP,+BAA+B,CACjCK,sBAAsB,CAAChB,qBAAqB,EAC5CiB,QAAQ,CACX;QAAA;MAAA;MAAA;QAEL,OAAO2B,SAAS,EAAE;MAAC,KAAZA,SAAS,EAAE;IACtB,CAAC;MAAA;IAAA;EAAA;AACL"} \ No newline at end of file +{"version":3,"file":"rx-storage-multiinstance.js","names":["BROADCAST_CHANNEL_BY_TOKEN","Map","getBroadcastChannelReference","databaseInstanceToken","databaseName","refObject","state","get","bc","BroadcastChannel","refs","Set","set","add","removeBroadcastChannelReference","size","close","addRxStorageMultiInstanceSupport","storageName","instanceCreationParams","instance","providedBroadcastChannel","multiInstance","broadcastChannel","changesFromOtherInstances$","Subject","eventListener","msg","collectionName","version","schema","next","eventBulk","addEventListener","oldChangestream$","changeStream","closed","sub","subscribe","postMessage","asObservable","pipe","mergeWith","oldClose","bind","unsubscribe","removeEventListener","oldRemove","remove"],"sources":["../../src/rx-storage-multiinstance.ts"],"sourcesContent":["/**\n * When a persistend RxStorage is used in more the one JavaScript process,\n * the even stream of the changestream() function must be broadcasted to the other\n * RxStorageInstances of the same databaseName+collectionName.\n *\n * In the past this was done by RxDB but it makes more sense to do this\n * at the RxStorage level so that the broadcasting etc can all happen inside of a WebWorker\n * and not on the main thread.\n * Also it makes it less complex to stack up different RxStorages onto each other\n * like what we do with the in-memory plugin.\n *\n * This is intened to be used inside of createStorageInstance() of a storage.\n * Do not use this if the storage anyway broadcasts the events like when using MongoDB\n * or in the future W3C might introduce a way to listen to IndexedDB changes.\n */\n\nimport { Observable, Subject } from 'rxjs';\nimport { mergeWith } from 'rxjs/operators';\nimport type {\n EventBulk,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from './types';\n\nimport {\n BroadcastChannel\n} from 'broadcast-channel';\n\n/**\n * The broadcast-channel is reused by the databaseInstanceToken.\n * This is required so that it is easy to simulate multi-tab usage\n * in the test where different instances of the same RxDatabase must\n * have different broadcast channels.\n * But also it ensures that for each RxDatabase we only create a single\n * broadcast channel that can even be reused in the leader election plugin.\n *\n * TODO at the end of the unit tests,\n * we should ensure that all channels are closed and cleaned up.\n * Otherwise we have forgot something.\n */\nexport const BROADCAST_CHANNEL_BY_TOKEN: Map;\n /**\n * Contains all context objects that currently use the channel.\n * If this becomes empty, we can close the channel\n */\n refs: Set;\n}> = new Map();\n\n\nexport type RxStorageMultiInstanceBroadcastType = {\n storageName: string;\n collectionName: string;\n /**\n * collection.schema.version\n */\n version: number;\n databaseName: string;\n eventBulk: EventBulk;\n};\n\nexport function getBroadcastChannelReference(\n databaseInstanceToken: string,\n databaseName: string,\n refObject: any\n): BroadcastChannel {\n let state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n state = {\n /**\n * We have to use the databaseName instead of the databaseInstanceToken\n * in the BroadcastChannel name because different instances must end with the same\n * channel name to be able to broadcast messages between each other.\n */\n bc: new BroadcastChannel('RxDB:' + databaseName),\n refs: new Set()\n };\n BROADCAST_CHANNEL_BY_TOKEN.set(databaseInstanceToken, state);\n }\n state.refs.add(refObject);\n return state.bc;\n}\n\nexport function removeBroadcastChannelReference(\n databaseInstanceToken: string,\n refObject: any\n) {\n const state = BROADCAST_CHANNEL_BY_TOKEN.get(databaseInstanceToken);\n if (!state) {\n return;\n }\n state.refs.delete(refObject);\n if (state.refs.size === 0) {\n BROADCAST_CHANNEL_BY_TOKEN.delete(databaseInstanceToken);\n return state.bc.close();\n }\n}\n\n\nexport function addRxStorageMultiInstanceSupport(\n storageName: string,\n instanceCreationParams: RxStorageInstanceCreationParams,\n instance: RxStorageInstance,\n /**\n * If provided, that channel will be used\n * instead of an own one.\n */\n providedBroadcastChannel?: BroadcastChannel\n) {\n if (!instanceCreationParams.multiInstance) {\n return;\n }\n\n type Emit = EventBulk, any>;\n\n const broadcastChannel = providedBroadcastChannel ?\n providedBroadcastChannel :\n getBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance.databaseName,\n instance\n );\n\n const changesFromOtherInstances$: Subject = new Subject();\n\n\n const eventListener = (msg: RxStorageMultiInstanceBroadcastType) => {\n if (\n msg.storageName === storageName &&\n msg.databaseName === instanceCreationParams.databaseName &&\n msg.collectionName === instanceCreationParams.collectionName &&\n msg.version === instanceCreationParams.schema.version\n ) {\n changesFromOtherInstances$.next(msg.eventBulk);\n }\n };\n broadcastChannel.addEventListener('message', eventListener);\n\n const oldChangestream$ = instance.changeStream();\n\n let closed = false;\n const sub = oldChangestream$.subscribe(eventBulk => {\n if (closed) {\n return;\n }\n broadcastChannel.postMessage({\n storageName: storageName,\n databaseName: instanceCreationParams.databaseName,\n collectionName: instanceCreationParams.collectionName,\n version: instanceCreationParams.schema.version,\n eventBulk\n });\n });\n\n instance.changeStream = function (): Observable {\n return changesFromOtherInstances$.asObservable().pipe(\n mergeWith(oldChangestream$)\n );\n };\n\n const oldClose = instance.close.bind(instance);\n instance.close = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldClose();\n };\n\n const oldRemove = instance.remove.bind(instance);\n instance.remove = async function () {\n closed = true;\n sub.unsubscribe();\n broadcastChannel.removeEventListener('message', eventListener);\n if (!providedBroadcastChannel) {\n await removeBroadcastChannelReference(\n instanceCreationParams.databaseInstanceToken,\n instance\n );\n }\n return oldRemove();\n };\n}\n"],"mappings":";;;;;;;;;;;;AAgBA;AACA;AAQA;AAzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMA,0BAOX,GAAG,IAAIC,GAAG,EAAE;AAAC;AAcR,SAASC,4BAA4B,CACxCC,qBAA6B,EAC7BC,YAAoB,EACpBC,SAAc,EACuC;EACrD,IAAIC,KAAK,GAAGN,0BAA0B,CAACO,GAAG,CAACJ,qBAAqB,CAAC;EACjE,IAAI,CAACG,KAAK,EAAE;IACRA,KAAK,GAAG;MACJ;AACZ;AACA;AACA;AACA;MACYE,EAAE,EAAE,IAAIC,kCAAgB,CAAC,OAAO,GAAGL,YAAY,CAAC;MAChDM,IAAI,EAAE,IAAIC,GAAG;IACjB,CAAC;IACDX,0BAA0B,CAACY,GAAG,CAACT,qBAAqB,EAAEG,KAAK,CAAC;EAChE;EACAA,KAAK,CAACI,IAAI,CAACG,GAAG,CAACR,SAAS,CAAC;EACzB,OAAOC,KAAK,CAACE,EAAE;AACnB;AAEO,SAASM,+BAA+B,CAC3CX,qBAA6B,EAC7BE,SAAc,EAChB;EACE,IAAMC,KAAK,GAAGN,0BAA0B,CAACO,GAAG,CAACJ,qBAAqB,CAAC;EACnE,IAAI,CAACG,KAAK,EAAE;IACR;EACJ;EACAA,KAAK,CAACI,IAAI,UAAO,CAACL,S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;EAAA,CACrB;AACL"} \ No newline at end of file diff --git a/dist/lib/types/index.d.js b/dist/lib/types/index.d.js index 915e556cb1c..e8f76aae06b 100644 --- a/dist/lib/types/index.d.js +++ b/dist/lib/types/index.d.js @@ -212,17 +212,6 @@ Object.keys(_replicationGraphql).forEach(function (key) { } }); }); -var _replicationCouchdb = require("./plugins/replication-couchdb"); -Object.keys(_replicationCouchdb).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _replicationCouchdb[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _replicationCouchdb[key]; - } - }); -}); var _localDocuments = require("./plugins/local-documents"); Object.keys(_localDocuments).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -234,17 +223,6 @@ Object.keys(_localDocuments).forEach(function (key) { } }); }); -var _serverCouchdb = require("./plugins/server-couchdb"); -Object.keys(_serverCouchdb).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _serverCouchdb[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _serverCouchdb[key]; - } - }); -}); var _migration = require("./plugins/migration"); Object.keys(_migration).forEach(function (key) { if (key === "default" || key === "__esModule") return; diff --git a/dist/lib/types/index.d.js.map b/dist/lib/types/index.d.js.map index 293581b4c4a..ab33ab40380 100644 --- a/dist/lib/types/index.d.js.map +++ b/dist/lib/types/index.d.js.map @@ -1 +1 @@ -{"version":3,"file":"index.d.js","names":[],"sources":["../../../src/types/index.d.ts"],"sourcesContent":["export * from './pouch';\nexport * from './rx-attachment';\nexport * from './rx-collection';\nexport * from './rx-database';\nexport * from './rx-database-internal-store';\nexport * from './rx-document';\nexport * from './rx-error';\nexport * from './rx-plugin';\nexport * from './rx-query';\nexport * from './rx-schema';\nexport * from './rx-storage';\nexport * from './rx-storage.interface';\nexport * from './replication-protocol';\nexport * from './conflict-handling';\nexport * from './rx-change-event';\nexport * from './query-planner';\nexport * from './util';\n\n// plugins\nexport * from './plugins/replication';\nexport * from './plugins/replication-graphql';\nexport * from './plugins/replication-couchdb';\nexport * from './plugins/replication';\nexport * from './plugins/local-documents';\nexport * from './plugins/server-couchdb';\nexport * from './plugins/migration';\nexport * from './plugins/backup';\nexport * from './plugins/cleanup';\nexport * from './plugins/lokijs';\nexport * from './plugins/dexie';\nexport * from './plugins/update';\nexport * from './plugins/crdt';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAGA;AAGA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAFA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file +{"version":3,"file":"index.d.js","names":[],"sources":["../../../src/types/index.d.ts"],"sourcesContent":["export * from './pouch';\nexport * from './rx-attachment';\nexport * from './rx-collection';\nexport * from './rx-database';\nexport * from './rx-database-internal-store';\nexport * from './rx-document';\nexport * from './rx-error';\nexport * from './rx-plugin';\nexport * from './rx-query';\nexport * from './rx-schema';\nexport * from './rx-storage';\nexport * from './rx-storage.interface';\nexport * from './replication-protocol';\nexport * from './conflict-handling';\nexport * from './rx-change-event';\nexport * from './query-planner';\nexport * from './util';\n\n// plugins\nexport * from './plugins/replication';\nexport * from './plugins/replication-graphql';\nexport * from './plugins/replication';\nexport * from './plugins/local-documents';\nexport * from './plugins/migration';\nexport * from './plugins/backup';\nexport * from './plugins/cleanup';\nexport * from './plugins/lokijs';\nexport * from './plugins/dexie';\nexport * from './plugins/update';\nexport * from './plugins/crdt';\n"],"mappings":";;;;;AAAA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAGA;AAEA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AADA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AAEA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;AACA;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-adapter-http.d.js b/dist/lib/types/modules/pouchdb-adapter-http.d.js deleted file mode 100644 index ddf1696d050..00000000000 --- a/dist/lib/types/modules/pouchdb-adapter-http.d.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=pouchdb-adapter-http.d.js.map \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-adapter-http.d.js.map b/dist/lib/types/modules/pouchdb-adapter-http.d.js.map deleted file mode 100644 index 66e5e9cf6c7..00000000000 --- a/dist/lib/types/modules/pouchdb-adapter-http.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-adapter-http.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-adapter-http.d.ts"],"sourcesContent":["declare module 'pouchdb-adapter-http';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-md5.d.js b/dist/lib/types/modules/pouchdb-md5.d.js deleted file mode 100644 index 7a49bf03a1a..00000000000 --- a/dist/lib/types/modules/pouchdb-md5.d.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=pouchdb-md5.d.js.map \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-md5.d.js.map b/dist/lib/types/modules/pouchdb-md5.d.js.map deleted file mode 100644 index eb521ef8067..00000000000 --- a/dist/lib/types/modules/pouchdb-md5.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-md5.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-md5.d.ts"],"sourcesContent":["declare module 'pouchdb-md5';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-replication.d.js b/dist/lib/types/modules/pouchdb-replication.d.js deleted file mode 100644 index d7aa4d29df5..00000000000 --- a/dist/lib/types/modules/pouchdb-replication.d.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=pouchdb-replication.d.js.map \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-replication.d.js.map b/dist/lib/types/modules/pouchdb-replication.d.js.map deleted file mode 100644 index be040bb64ca..00000000000 --- a/dist/lib/types/modules/pouchdb-replication.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-replication.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-replication.d.ts"],"sourcesContent":["declare module 'pouchdb-replication';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-utils.d.js b/dist/lib/types/modules/pouchdb-utils.d.js deleted file mode 100644 index 3ee630fa98d..00000000000 --- a/dist/lib/types/modules/pouchdb-utils.d.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=pouchdb-utils.d.js.map \ No newline at end of file diff --git a/dist/lib/types/modules/pouchdb-utils.d.js.map b/dist/lib/types/modules/pouchdb-utils.d.js.map deleted file mode 100644 index e4c0540f1b4..00000000000 --- a/dist/lib/types/modules/pouchdb-utils.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"pouchdb-utils.d.js","names":[],"sources":["../../../../src/types/modules/pouchdb-utils.d.ts"],"sourcesContent":["declare module 'pouchdb-utils';\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/plugins/local-documents.d.js.map b/dist/lib/types/plugins/local-documents.d.js.map index c717687767f..16165794bcf 100644 --- a/dist/lib/types/plugins/local-documents.d.js.map +++ b/dist/lib/types/plugins/local-documents.d.js.map @@ -1 +1 @@ -{"version":3,"file":"local-documents.d.js","names":[],"sources":["../../../../src/types/plugins/local-documents.d.ts"],"sourcesContent":["import { DocCache } from '../../doc-cache';\nimport { RxCollection } from '../rx-collection';\nimport { RxDatabase } from '../rx-database';\nimport { RxDocumentBase } from '../rx-document';\nimport { RxStorageInstance } from '../rx-storage.interface';\nimport { Override } from '../util';\n\nexport type LocalDocumentParent = RxDatabase | RxCollection;\nexport type LocalDocumentState = {\n database: RxDatabase;\n parent: LocalDocumentParent;\n storageInstance: RxStorageInstance;\n docCache: DocCache>;\n};\nexport type RxLocalDocumentData<\n Data = {\n // local documents are schemaless and contain any data\n [key: string]: any;\n }\n> = {\n id: string;\n data: Data;\n};\n\ndeclare type LocalDocumentAtomicUpdateFunction = (\n doc: Data,\n rxLocalDocument: RxLocalDocument\n) => Data | Promise;\n\n\nexport declare type RxLocalDocument = Override<\nRxDocumentBase, {}>,\n{\n readonly parent: Parent;\n isLocal(): true;\n\n /**\n * Because local documents store their relevant data inside of the 'data' property,\n * the atomic mutation methods are changed a bit to only allow to change parts of the data property.\n */\n atomicUpdate(mutationFunction: LocalDocumentAtomicUpdateFunction): Promise>;\n atomicPatch(patch: Partial): Promise>;\n}\n>;\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"local-documents.d.js","names":[],"sources":["../../../../src/types/plugins/local-documents.d.ts"],"sourcesContent":["import { DocumentCache } from '../../doc-cache';\nimport { IncrementalWriteQueue } from '../../incremental-write';\nimport { RxCollection } from '../rx-collection';\nimport { RxDatabase } from '../rx-database';\nimport { RxDocumentBase } from '../rx-document';\nimport { RxStorageInstance } from '../rx-storage.interface';\nimport { Override } from '../util';\n\nexport type LocalDocumentParent = RxDatabase | RxCollection;\nexport type LocalDocumentState = {\n database: RxDatabase;\n parent: LocalDocumentParent;\n storageInstance: RxStorageInstance;\n docCache: DocumentCache;\n incrementalWriteQueue: IncrementalWriteQueue;\n};\nexport type RxLocalDocumentData<\n Data = {\n // local documents are schemaless and contain any data\n [key: string]: any;\n }\n> = {\n id: string;\n data: Data;\n};\n\ndeclare type LocalDocumentModifyFunction = (\n doc: Data,\n rxLocalDocument: RxLocalDocument\n) => Data | Promise;\n\n\nexport declare type RxLocalDocument = Override<\nRxDocumentBase, {}>,\n{\n readonly parent: Parent;\n isLocal(): true;\n\n /**\n * Because local documents store their relevant data inside of the 'data' property,\n * the incremental mutation methods are changed a bit to only allow to change parts of the data property.\n */\n incrementalModify(mutationFunction: LocalDocumentModifyFunction): Promise>;\n incrementalPatch(patch: Partial): Promise>;\n}\n>;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/plugins/lokijs.d.js.map b/dist/lib/types/plugins/lokijs.d.js.map index 39ec25a9d6c..d9ccfd4eb93 100644 --- a/dist/lib/types/plugins/lokijs.d.js.map +++ b/dist/lib/types/plugins/lokijs.d.js.map @@ -1 +1 @@ -{"version":3,"file":"lokijs.d.js","names":[],"sources":["../../../../src/types/plugins/lokijs.d.ts"],"sourcesContent":["import type { LeaderElector } from 'broadcast-channel';\nimport type {\n Collection\n} from 'lokijs';\nimport { AddReturn } from 'unload';\nimport { LokiSaveQueue } from '../../plugins/lokijs/loki-save-queue';\n\nexport type LokiDatabaseSettings = Partial & {};\n\nexport type LokiCollectionSettings = Partial>;\n\nexport type LokiSettings = {\n database?: LokiDatabaseSettings;\n collection?: LokiCollectionSettings;\n};\n\nexport type LokiStorageInternals = {\n leaderElector?: LeaderElector;\n localState?: Promise;\n};\n\nexport type LokiRemoteRequestBroadcastMessage = {\n response: false;\n type: string;\n databaseName: string;\n collectionName: string;\n operation: string;\n params: any[];\n requestId: string;\n};\n\nexport type LokiRemoteResponseBroadcastMessage = {\n response: true;\n type: string;\n databaseName: string;\n collectionName: string;\n requestId: string;\n result: any | any[];\n // if true, the result property will contain an error state\n isError: boolean;\n};\n\nexport type LokiDatabaseState = {\n database: Loki;\n databaseSettings: LokiDatabaseSettings;\n saveQueue: LokiSaveQueue;\n\n // all known collections of the database\n collections: {\n [collectionName: string]: Collection;\n };\n\n /**\n * Registered unload handlers\n * so we can remove them on close.\n */\n unloads: AddReturn[];\n};\n\nexport type LokiLocalDatabaseState = {\n databaseState: LokiDatabaseState;\n collection: Collection;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"lokijs.d.js","names":[],"sources":["../../../../src/types/plugins/lokijs.d.ts"],"sourcesContent":["import type { LeaderElector } from 'broadcast-channel';\nimport type {\n Collection\n} from 'lokijs';\nimport { AddReturn } from 'unload';\nimport { LokiSaveQueue } from '../../plugins/storage-lokijs/loki-save-queue';\n\nexport type LokiDatabaseSettings = Partial & {};\n\nexport type LokiCollectionSettings = Partial>;\n\nexport type LokiSettings = {\n database?: LokiDatabaseSettings;\n collection?: LokiCollectionSettings;\n};\n\nexport type LokiStorageInternals = {\n leaderElector?: LeaderElector;\n localState?: Promise;\n};\n\nexport type LokiRemoteRequestBroadcastMessage = {\n response: false;\n type: string;\n databaseName: string;\n collectionName: string;\n operation: string;\n params: any[];\n requestId: string;\n};\n\nexport type LokiRemoteResponseBroadcastMessage = {\n response: true;\n type: string;\n databaseName: string;\n collectionName: string;\n requestId: string;\n result: any | any[];\n // if true, the result property will contain an error state\n isError: boolean;\n};\n\nexport type LokiDatabaseState = {\n database: Loki;\n databaseSettings: LokiDatabaseSettings;\n saveQueue: LokiSaveQueue;\n\n // all known collections of the database\n collections: {\n [collectionName: string]: Collection;\n };\n\n /**\n * Registered unload handlers\n * so we can remove them on close.\n */\n unloads: AddReturn[];\n};\n\nexport type LokiLocalDatabaseState = {\n databaseState: LokiDatabaseState;\n collection: Collection;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/plugins/replication-couchdb.d.js b/dist/lib/types/plugins/replication-couchdb.d.js deleted file mode 100644 index 1eb323f6841..00000000000 --- a/dist/lib/types/plugins/replication-couchdb.d.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=replication-couchdb.d.js.map \ No newline at end of file diff --git a/dist/lib/types/plugins/replication-couchdb.d.js.map b/dist/lib/types/plugins/replication-couchdb.d.js.map deleted file mode 100644 index 7f972d71fbc..00000000000 --- a/dist/lib/types/plugins/replication-couchdb.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"replication-couchdb.d.js","names":[],"sources":["../../../../src/types/plugins/replication-couchdb.d.ts"],"sourcesContent":["import { Observable } from 'rxjs';\n\nimport type {\n RxQuery,\n RxCollection\n} from '../../types';\nimport type {\n PouchReplicationOptions,\n PouchSyncHandler\n} from '../pouch';\nimport type { RxCouchDBReplicationStateBase } from '../../plugins/replication-couchdb';\n\nexport declare class RxCouchDBReplicationState extends RxCouchDBReplicationStateBase {\n collection: RxCollection;\n\n change$: Observable;\n docs$: Observable;\n denied$: Observable;\n active$: Observable;\n alive$: Observable;\n complete$: Observable;\n error$: Observable;\n\n /**\n * waits until the initial replication is done\n * and the client can be expected to have the same data as the server\n */\n awaitInitialReplication(): Promise;\n\n // can be used for debugging or custom event-handling\n // will be set some time after sync() is called\n _pouchEventEmitterObject: PouchSyncHandler | null;\n\n // if you do a custom sync, put the thing you get back from pouch here\n setPouchEventEmitter(pouchSyncState: any): void;\n}\n\nexport type SyncOptions = {\n remote: string | any;\n waitForLeadership?: boolean;\n direction?: {\n push?: boolean;\n pull?: boolean;\n };\n // for options see https://pouchdb.com/api.html#replication\n options?: PouchReplicationOptions;\n query?: RxQuery;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/plugins/replication-graphql.d.js.map b/dist/lib/types/plugins/replication-graphql.d.js.map index 90ea25e5091..7fbea9e715b 100644 --- a/dist/lib/types/plugins/replication-graphql.d.js.map +++ b/dist/lib/types/plugins/replication-graphql.d.js.map @@ -1 +1 @@ -{"version":3,"file":"replication-graphql.d.js","names":[],"sources":["../../../../src/types/plugins/replication-graphql.d.ts"],"sourcesContent":["import { RxReplicationWriteToMasterRow } from '../replication-protocol';\nimport { ById, MaybePromise } from '../util';\nimport { ReplicationOptions, ReplicationPullHandlerResult, ReplicationPullOptions, ReplicationPushOptions } from './replication';\n\nexport interface RxGraphQLReplicationQueryBuilderResponseObject {\n query: string;\n variables: any;\n}\n\nexport type RxGraphQLReplicationClientState = {\n headers: ById;\n credentials: RequestCredentials | undefined;\n};\n\nexport type RxGraphQLReplicationQueryBuilderResponse =\n RxGraphQLReplicationQueryBuilderResponseObject |\n Promise;\nexport type RxGraphQLReplicationPushQueryBuilder = (\n // typed 'any' because the data might be modified by the push.modifier.\n rows: RxReplicationWriteToMasterRow[]\n) => RxGraphQLReplicationQueryBuilderResponse;\n\n\nexport type RxGraphQLReplicationPullQueryBuilder = (\n latestPulledCheckpoint: CheckpointType | null,\n limit: number\n) => RxGraphQLReplicationQueryBuilderResponse;\nexport type GraphQLSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {\n queryBuilder: RxGraphQLReplicationPullQueryBuilder;\n streamQueryBuilder?: RxGraphQLReplicationPullStreamQueryBuilder;\n dataPath?: string;\n responseModifier?: RxGraphQLPullResponseModifier;\n};\n\nexport type RxGraphQLPullResponseModifier = (\n // the exact response that was returned from the server\n plainResponse: ReplicationPullHandlerResult | any,\n // either 'handler' if it came from the pull.handler, or 'stream' if it came from the pull.stream\n origin: 'handler' | 'stream',\n requestCheckpoint?: CheckpointType\n) => MaybePromise>;\n\nexport type RxGraphQLReplicationPullStreamQueryBuilder = (headers: { [k: string]: string; }) => RxGraphQLReplicationQueryBuilderResponse;\n\nexport type GraphQLSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {\n queryBuilder: RxGraphQLReplicationPushQueryBuilder;\n};\n\nexport type GraphQLServerUrl = {\n http?: string;\n ws?: string;\n};\n\nexport type SyncOptionsGraphQL = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier' | 'collection'\n> & {\n url: GraphQLServerUrl;\n headers?: { [k: string]: string; }; // send with all requests to the endpoint\n credentials?: RequestCredentials;\n pull?: GraphQLSyncPullOptions;\n push?: GraphQLSyncPushOptions;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"replication-graphql.d.js","names":[],"sources":["../../../../src/types/plugins/replication-graphql.d.ts"],"sourcesContent":["import { RxReplicationWriteToMasterRow } from '../replication-protocol';\nimport { ById, MaybePromise } from '../util';\nimport { ReplicationOptions, ReplicationPullHandlerResult, ReplicationPullOptions, ReplicationPushOptions } from './replication';\n\nexport interface RxGraphQLReplicationQueryBuilderResponseObject {\n query: string;\n variables: any;\n}\n\nexport type RxGraphQLReplicationClientState = {\n headers: ById;\n credentials: RequestCredentials | undefined;\n};\n\nexport type RxGraphQLReplicationQueryBuilderResponse =\n RxGraphQLReplicationQueryBuilderResponseObject |\n Promise;\nexport type RxGraphQLReplicationPushQueryBuilder = (\n // typed 'any' because the data might be modified by the push.modifier.\n rows: RxReplicationWriteToMasterRow[]\n) => RxGraphQLReplicationQueryBuilderResponse;\n\n\nexport type RxGraphQLReplicationPullQueryBuilder = (\n latestPulledCheckpoint: CheckpointType | null,\n limit: number\n) => RxGraphQLReplicationQueryBuilderResponse;\nexport type GraphQLSyncPullOptions = Omit<\nReplicationPullOptions,\n'handler' | 'stream$'\n> & {\n queryBuilder: RxGraphQLReplicationPullQueryBuilder;\n streamQueryBuilder?: RxGraphQLReplicationPullStreamQueryBuilder;\n dataPath?: string;\n responseModifier?: RxGraphQLPullResponseModifier;\n};\n\nexport type RxGraphQLPullResponseModifier = (\n // the exact response that was returned from the server\n plainResponse: ReplicationPullHandlerResult | any,\n // either 'handler' if it came from the pull.handler, or 'stream' if it came from the pull.stream\n origin: 'handler' | 'stream',\n requestCheckpoint?: CheckpointType\n) => MaybePromise>;\n\nexport type RxGraphQLReplicationPullStreamQueryBuilder = (headers: { [k: string]: string; }) => RxGraphQLReplicationQueryBuilderResponse;\n\nexport type GraphQLSyncPushOptions = Omit<\nReplicationPushOptions,\n'handler'\n> & {\n queryBuilder: RxGraphQLReplicationPushQueryBuilder;\n};\n\nexport type GraphQLServerUrl = {\n http?: string;\n ws?: string;\n};\n\nexport type SyncOptionsGraphQL = Omit<\nReplicationOptions,\n'pull' | 'push' | 'replicationIdentifier'\n> & {\n url: GraphQLServerUrl;\n headers?: { [k: string]: string; }; // send with all requests to the endpoint\n credentials?: RequestCredentials;\n pull?: GraphQLSyncPullOptions;\n push?: GraphQLSyncPushOptions;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/plugins/replication.d.js.map b/dist/lib/types/plugins/replication.d.js.map index 5c8a7c1cfd8..fbf934d9c8c 100644 --- a/dist/lib/types/plugins/replication.d.js.map +++ b/dist/lib/types/plugins/replication.d.js.map @@ -1 +1 @@ -{"version":3,"file":"replication.d.js","names":[],"sources":["../../../../src/types/plugins/replication.d.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport type {\n InternalStoreDocType,\n MaybePromise,\n RxCollection,\n RxDocumentData,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n WithDeleted\n} from '../../types';\n\n\nexport type InternalStoreReplicationPushDocType = InternalStoreDocType<{\n checkpoint: any;\n}>;\nexport type InternalStoreReplicationPullDocType = InternalStoreDocType<{\n lastPulledDoc: RxDocumentData;\n}>;\n\nexport type ReplicationPullHandlerResult = {\n checkpoint: CheckpointType;\n documents: WithDeleted[];\n};\n\nexport type ReplicationPullHandler = (\n lastPulledCheckpoint: CheckpointType,\n batchSize: number\n) => Promise>;\nexport type ReplicationPullOptions = {\n /**\n * A handler that pulls the new remote changes\n * from the remote actor.\n */\n handler: ReplicationPullHandler;\n\n\n /**\n * An observable that streams all document changes\n * that are happening on the backend.\n * Emits an document bulk together with the latest checkpoint of these documents.\n * Also can emit a 'RESYNC' event when the client was offline and is online again.\n *\n * Not required for non-live replication.\n */\n stream$?: Observable>;\n\n /**\n * Amount of documents that the remote will send in one request.\n * If the response contains less then [batchSize] documents,\n * RxDB will assume there are no more changes on the backend\n * that are not replicated.\n * [default=100]\n */\n batchSize?: number;\n\n /**\n * A modifier that runs on all documents that are pulled,\n * before they are used by RxDB.\n * - the ones from the pull handler\n * - the ones from the pull stream\n */\n modifier?: (docData: any) => MaybePromise>;\n};\n\n/**\n * Gets the new write rows.\n * Returns the current master state of all conflicting writes,\n * so that they can be resolved on the client.\n */\nexport type ReplicationPushHandler = (docs: RxReplicationWriteToMasterRow[]) => Promise[]>;\nexport type ReplicationPushOptions = {\n /**\n * A handler that sends the new local changes\n * to the remote actor.\n * On error, all documents are send again at later time.\n */\n handler: ReplicationPushHandler;\n\n\n /**\n * A modifier that runs on all pushed documents before\n * they are send into the push handler.\n */\n modifier?: (docData: WithDeleted) => MaybePromise;\n\n /**\n * How many local changes to process at once.\n */\n batchSize?: number;\n};\n\n\nexport type ReplicationOptions = {\n /**\n * An id for the replication to identify it\n * and so that RxDB is able to resume the replication on app reload.\n * If you replicate with a remote server, it is recommended to put the\n * server url into the replicationIdentifier.\n * Like 'my-rest-replication-to-https://example.com/api/sync'\n */\n replicationIdentifier: string;\n collection: RxCollection;\n /**\n * Define a custom property that is used\n * to flag a document as being deleted.\n * @default '_deleted'\n */\n deletedField?: '_deleted' | string;\n pull?: ReplicationPullOptions;\n push?: ReplicationPushOptions;\n /**\n * By default it will do an ongoing realtime replication.\n * By settings live: false the replication will run once until the local state\n * is in sync with the remote state, then it will cancel itself.\n * @default true\n */\n live?: boolean;\n /**\n * Time in milliseconds after when a failed backend request\n * has to be retried.\n * This time will be skipped if a offline->online switch is detected\n * via `navigator.onLine`\n * @default 5000\n */\n retryTime?: number;\n /**\n * When multiInstance is `true`, like when you use RxDB in multiple browser tabs,\n * the replication should always run in only one of the open browser tabs.\n * If waitForLeadership is `true`, it will wait until the current instance is leader.\n * If waitForLeadership is `false`, it will start replicating, even if it is not leader.\n * @default true\n */\n waitForLeadership?: boolean;\n /**\n * If this is set to `false`,\n * the replication will not start automatically\n * but will wait for `replicationState.start()` being called.\n * @default true\n */\n autoStart?: boolean;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"replication.d.js","names":[],"sources":["../../../../src/types/plugins/replication.d.ts"],"sourcesContent":["import { Observable } from 'rxjs';\nimport type {\n InternalStoreDocType,\n MaybePromise,\n RxCollection,\n RxDocumentData,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n WithDeleted\n} from '../../types';\n\n\nexport type InternalStoreReplicationPushDocType = InternalStoreDocType<{\n checkpoint: any;\n}>;\nexport type InternalStoreReplicationPullDocType = InternalStoreDocType<{\n lastPulledDoc: RxDocumentData;\n}>;\n\nexport type ReplicationPullHandlerResult = {\n checkpoint: CheckpointType;\n documents: WithDeleted[];\n};\n\nexport type ReplicationPullHandler = (\n lastPulledCheckpoint: CheckpointType,\n batchSize: number\n) => Promise>;\nexport type ReplicationPullOptions = {\n /**\n * A handler that pulls the new remote changes\n * from the remote actor.\n */\n handler: ReplicationPullHandler;\n\n\n /**\n * An observable that streams all document changes\n * that are happening on the backend.\n * Emits an document bulk together with the latest checkpoint of these documents.\n * Also can emit a 'RESYNC' event when the client was offline and is online again.\n *\n * Not required for non-live replication.\n */\n stream$?: Observable>;\n\n /**\n * Amount of documents that the remote will send in one request.\n * If the response contains less then [batchSize] documents,\n * RxDB will assume there are no more changes on the backend\n * that are not replicated.\n * [default=100]\n */\n batchSize?: number;\n\n /**\n * A modifier that runs on all documents that are pulled,\n * before they are used by RxDB.\n * - the ones from the pull handler\n * - the ones from the pull stream\n */\n modifier?: (docData: any) => MaybePromise>;\n};\n\n/**\n * Gets the new write rows.\n * Returns the current master state of all conflicting writes,\n * so that they can be resolved on the client.\n */\nexport type ReplicationPushHandler = (docs: RxReplicationWriteToMasterRow[]) => Promise[]>;\nexport type ReplicationPushOptions = {\n /**\n * A handler that sends the new local changes\n * to the remote actor.\n * On error, all documents are send again at later time.\n */\n handler: ReplicationPushHandler;\n\n\n /**\n * A modifier that runs on all pushed documents before\n * they are send into the push handler.\n */\n modifier?: (docData: WithDeleted) => MaybePromise;\n\n /**\n * How many local changes to process at once.\n */\n batchSize?: number;\n};\n\n\nexport type ReplicationOptions = {\n /**\n * An id for the replication to identify it\n * and so that RxDB is able to resume the replication on app reload.\n * If you replicate with a remote server, it is recommended to put the\n * server url into the replicationIdentifier.\n * Like 'my-rest-replication-to-https://example.com/api/sync'\n */\n replicationIdentifier: string;\n collection: RxCollection;\n /**\n * Define a custom property that is used\n * to flag a document as being deleted.\n * @default '_deleted'\n */\n deletedField?: '_deleted' | string;\n pull?: ReplicationPullOptions;\n push?: ReplicationPushOptions;\n /**\n * By default it will do an ongoing realtime replication.\n * By settings live: false the replication will run once until the local state\n * is in sync with the remote state, then it will cancel itself.\n * @default true\n */\n live?: boolean;\n /**\n * Time in milliseconds after when a failed backend request\n * has to be retried.\n * This time will be skipped if a offline->online switch is detected\n * via `navigator.onLine`\n * @default 5000\n */\n retryTime?: number;\n /**\n * When multiInstance is `true`, like when you use RxDB in multiple browser tabs,\n * the replication should always run in only one of the open browser tabs.\n * If waitForLeadership is `true`, it will wait until the current instance is leader.\n * If waitForLeadership is `false`, it will start replicating, even if it is not leader.\n * @default true\n */\n waitForLeadership?: boolean;\n /**\n * If this is set to `false`,\n * the replication will not start automatically\n * but will wait for `replicationState.start()` being called.\n * @default true\n */\n autoStart?: boolean;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/plugins/server-couchdb.d.js b/dist/lib/types/plugins/server-couchdb.d.js deleted file mode 100644 index 940bd216141..00000000000 --- a/dist/lib/types/plugins/server-couchdb.d.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -//# sourceMappingURL=server-couchdb.d.js.map \ No newline at end of file diff --git a/dist/lib/types/plugins/server-couchdb.d.js.map b/dist/lib/types/plugins/server-couchdb.d.js.map deleted file mode 100644 index 9d9557ec15e..00000000000 --- a/dist/lib/types/plugins/server-couchdb.d.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"server-couchdb.d.js","names":[],"sources":["../../../../src/types/plugins/server-couchdb.d.ts"],"sourcesContent":["export type CouchDBServerResponse = {\n app: any;\n pouchApp: any;\n server: any;\n};\n\n\n/**\n * Options that can be passed to express-pouchdb\n * @link https://github.com/pouchdb/pouchdb-server#api\n */\nexport type PouchDBExpressServerOptions = {\n // a path to the configuration file to use. Defaults to './config.json'.\n configPath?: string;\n // a path to the log file to use. Defaults to './rxdb-server-log.txt' in the tmp folder of the os.\n logPath?: string;\n // If true (=default) the config file is not written to configPath but stored in memory.\n inMemoryConfig?: boolean;\n // determines which parts of the HTTP API express-pouchdb offers are enabled\n mode?: 'fullCouchDB' | 'minimumForPouchDB' | 'custom';\n // Sometimes the preprogrammed modes are insufficient for your needs\n overrideMode?: {\n // a javascript array that specifies parts to include on top of the ones specified by opts.mode\n include?: any[];\n // a javascript array that specifies parts to exclude from the ones specified by opts.mode\n exclude?: any[];\n };\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/pouch.d.js.map b/dist/lib/types/pouch.d.js.map index ebf22577264..9c468aebd77 100644 --- a/dist/lib/types/pouch.d.js.map +++ b/dist/lib/types/pouch.d.js.map @@ -1 +1 @@ -{"version":3,"file":"pouch.d.js","names":[],"sources":["../../../src/types/pouch.d.ts"],"sourcesContent":["import { MangoQuery, MangoQuerySelector, MangoQuerySortPart } from './rx-query';\nimport { BulkWriteRow } from './rx-storage';\n\n/**\n * this file contains types that are pouchdb-specific\n * most of it is copied from @types/pouchdb\n * because it is outdated and strange\n */\n\nexport interface PouchReplicationOptions {\n live?: boolean;\n retry?: boolean;\n filter?: Function;\n doc_ids?: string[];\n query_params?: any;\n view?: any;\n since?: number | 'now';\n heartbeat?: number;\n timeout?: number;\n batch_size?: number;\n batches_limit?: number;\n back_off_function?: Function;\n checkpoint?: false | 'source' | 'target';\n include_docs?: boolean;\n limit?: number;\n}\n\n/**\n * @link https://pouchdb.com/api.html#changes\n */\nexport interface PouchChangesOptionsBase {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n descending?: boolean;\n since?: any;\n limit?: number;\n timeout?: any;\n heartbeat?: number | boolean;\n filter?: any;\n doc_ids?: string | string[];\n query_param?: any;\n view?: any;\n return_docs?: boolean;\n batch_size?: number;\n style?: string;\n}\n\nexport interface PouchChangesOptionsLive extends PouchChangesOptionsBase {\n live: true;\n}\n\nexport interface PouchChangesOptionsNonLive extends PouchChangesOptionsBase {\n live: false;\n}\ninterface PouchChangesOnChangeEvent {\n on: (eventName: string, handler: Function) => void;\n off: (eventName: string, handler: Function) => void;\n cancel(): void;\n}\n\nexport type PouchWriteError = {\n /**\n * status code from pouchdb\n * 409 for 'conflict'\n */\n status: number;\n error: true;\n /**\n * primary key value of the errored document\n */\n id: string;\n};\n\n/**\n * possible pouch-settings\n * @link https://pouchdb.com/api.html#create_database\n */\nexport interface PouchSettings {\n auto_compaction?: boolean;\n revs_limit?: number;\n ajax?: any;\n fetch?: any;\n auth?: any;\n skip_setup?: boolean;\n storage?: any;\n size?: number;\n location?: string;\n iosDatabaseLocation?: string;\n}\n\n/**\n * options for pouch.allDocs()\n * @link https://pouchdb.com/api.html#batch_fetch\n */\nexport type PouchAllDocsOptions = {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n startkey?: string;\n endkey?: string;\n inclusive_end?: boolean;\n limit?: number;\n skip?: number;\n descending?: boolean;\n key?: string;\n keys?: string[];\n update_seq?: string;\n\n // undocument but needed\n revs?: boolean;\n deleted?: 'ok';\n};\n\nexport type PouchSyncHandlerEvents = 'change' | 'paused' | 'active' | 'error' | 'complete';\nexport type PouchSyncHandler = {\n on(ev: PouchSyncHandlerEvents, fn: (el: any) => void): void;\n off(ev: PouchSyncHandlerEvents, fn: any): void;\n cancel(): void;\n};\n\nexport type PouchChangeRow = {\n id: string;\n seq: number;\n deleted?: true;\n changes: {\n rev: 'string';\n }[];\n /**\n * only if include_docs === true\n */\n doc?: PouchChangeDoc;\n};\n\nexport type PouchAttachmentMeta = {\n digest: string;\n content_type: string;\n length: number;\n stub: boolean;\n\n /**\n * 'revpos indicates the generation number (numeric prefix in the revID) at which the attachment was last altered'\n * @link https://github.com/couchbase/couchbase-lite-ios/issues/1200#issuecomment-206444554\n */\n revpos: number;\n};\n\nexport type BlobBuffer = Buffer | Blob;\n\nexport type PouchAttachmentWithData = PouchAttachmentMeta & {\n /**\n * Base64 string with the data\n * or directly a buffer\n */\n data: BlobBuffer;\n type: string;\n /**\n * If set, must be false\n * because we have the full data and not only a stub.\n */\n stub?: false;\n};\n\nexport type PouchChangeDoc = {\n _id: string;\n _rev: string;\n /**\n * True if the document is deleted.\n */\n _deleted?: boolean;\n _attachments: {\n [attachmentId: string]: PouchAttachmentMeta;\n };\n};\n\nexport type WithAttachments = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: PouchAttachmentMeta;\n };\n};\nexport type WithAttachmentsData = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: PouchAttachmentWithData;\n };\n};\n\n\nexport type WithPouchMeta = Data & {\n _rev: string;\n _attachments?: {\n [attachmentId: string]: PouchAttachmentMeta;\n };\n _deleted?: boolean;\n};\n\nexport type PouchdbChangesResult = {\n results: PouchChangeRow[];\n last_seq: number;\n};\n\ndeclare type Debug = {\n enable(what: string): void;\n disable(): void;\n};\n\nexport type PouchDbSorting = (string | string[] | { [k: string]: 'asc' | 'desc' | 1 | -1; })[];\n\n// this is not equal to the standard MangoQuery\n// because of different sorting\nexport type PouchdbQuery = MangoQuery & {\n sort?: PouchDbSorting;\n};\n\nexport type PouchBulkDocResultRow = {\n ok: boolean;\n id: string;\n rev: string;\n\n error?: 'conflict';\n reason?: string;\n};\n\nexport type PouchCheckpoint = {\n sequence: number;\n};\n\nexport type PouchBulkDocOptions = {\n new_edits?: boolean;\n\n // custom options for RxDB\n isDeeper?: boolean;\n custom?: {\n primaryPath: string;\n writeRowById: Map>;\n insertDocsById: Map;\n previousDocsInDb: Map;\n context: string;\n };\n};\n\nexport type PouchMangoQuery = MangoQuery & {\n index: undefined;\n use_index?: string;\n};\n\nexport type ExplainedPouchQuery = {\n dbname: string;\n index: {\n ddoc: string | null;\n name: string; // 'idx-rxdb-index-age,_id'\n type: 'json';\n def: {\n fields: MangoQuerySortPart[];\n };\n };\n selector: MangoQuerySelector;\n range: {\n start_key: any[];\n end_key: any[];\n };\n opts: {\n use_index: string[];\n bookmark: string;\n sort: MangoQuerySortPart[];\n conflicts: boolean;\n r: any[];\n };\n skip: number;\n};\n\nexport type PouchAllDocsResponse = {\n offset: number;\n rows: {\n id: string;\n doc: any;\n key: string;\n value: {\n rev: string;\n deleted?: boolean;\n };\n error?: 'not_found' | string;\n }[];\n total_rows: number;\n};\n\nexport declare class PouchDBInstance {\n constructor(\n name: string,\n options: { adapter: string; }\n );\n readonly name: string;\n readonly adapter: string;\n\n readonly __opts: {\n db: any | string; // contains the adapter function\n deterministic_revs: boolean;\n name: string;\n adapter: string;\n };\n\n static debug: Debug;\n\n static plugin(p: any): void;\n static isInstanceOf(instance: any): boolean;\n info(): Promise;\n\n allDocs(options?: PouchAllDocsOptions): Promise;\n\n bulkDocs(\n docs: { docs: any[]; } | any[],\n options?: PouchBulkDocOptions,\n ): Promise<(PouchBulkDocResultRow | PouchWriteError)[]>;\n\n\n find(mangoQuery: PouchdbQuery): Promise<{\n docs: WithPouchMeta[];\n }>;\n compact(options?: any): Promise;\n destroy(options?: any): Promise;\n get(\n docId: string,\n options?: any\n ): Promise;\n put(\n doc: any,\n options?: any,\n ): Promise;\n remove(\n doc: any | string,\n options?: any,\n ): Promise;\n\n changes(options?: PouchChangesOptionsNonLive): Promise;\n changes(options: PouchChangesOptionsLive): PouchChangesOnChangeEvent;\n\n sync(remoteDb: string | any, options?: PouchReplicationOptions): PouchSyncHandler;\n replicate(options?: PouchReplicationOptions): PouchSyncHandler;\n\n close(): Promise;\n putAttachment(\n docId: string,\n attachmentId: string,\n rev: string,\n attachment: any,\n type: string\n ): Promise;\n getAttachment(\n docId: string,\n attachmentId: string,\n options?: { rev?: string; },\n ): Promise;\n removeAttachment(\n docId: string,\n attachmentId: string,\n rev: string\n ): Promise;\n\n /**\n * @link https://pouchdb.com/api.html#bulk_get\n */\n bulkGet(options: {\n docs: {\n // ID of the document to fetch\n id: string;\n // Revision of the document to fetch. If this is not specified, all available revisions are fetched\n rev?: string;\n\n // I could not find out what this should be\n atts_since?: any;\n }[];\n // Each returned revision body will include its revision history as a _revisions property. Default is false\n revs?: boolean;\n // what does this?\n latest?: boolean;\n // Include attachment data in the response. Default is false, resulting in only stubs being returned.\n attachments?: boolean;\n // Return attachment data as Blobs/Buffers, instead of as base64-encoded strings. Default is false\n binary?: boolean;\n }): Promise<{\n results: {\n id: string;\n docs: {\n ok?: {\n _id: string;\n _rev: string;\n _revisions: {\n ids: string[];\n start: number;\n };\n };\n error?: {\n error: string;\n id: string;\n reason: string;\n rev: string;\n };\n }[];\n }[];\n }>;\n\n revsDiff(diff: any): Promise;\n explain(query: PouchMangoQuery): Promise>;\n\n getIndexes(): Promise<{\n indexes: {\n ddoc: any | null;\n name: string;\n type: string;\n def: {\n fields: {\n [key: string]: 'asc' | 'desc';\n }[];\n };\n }[];\n total_rows: number;\n }>;\n\n createIndex(opts: {\n name: string;\n ddoc: string;\n index: any;\n }): Promise;\n\n /**\n * @link https://pouchdb.com/errors.html#event_emitter_limit\n */\n setMaxListeners(maxListenersAmount: number): void;\n getMaxListeners(): number;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"pouch.d.js","names":[],"sources":["../../../src/types/pouch.d.ts"],"sourcesContent":["import {\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart\n} from './rx-query';\nimport { BulkWriteRow } from './rx-storage';\n\n/**\n * This file contains types that are CouchDB specific\n */\n\nexport interface CouchReplicationOptions {\n live?: boolean;\n retry?: boolean;\n filter?: Function;\n doc_ids?: string[];\n query_params?: any;\n view?: any;\n since?: number | 'now';\n heartbeat?: number;\n timeout?: number;\n batch_size?: number;\n batches_limit?: number;\n back_off_function?: Function;\n checkpoint?: false | 'source' | 'target';\n include_docs?: boolean;\n limit?: number;\n}\n\nexport interface CouchChangesOptionsBase {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n descending?: boolean;\n since?: any;\n limit?: number;\n timeout?: any;\n heartbeat?: number | boolean;\n filter?: any;\n doc_ids?: string | string[];\n query_param?: any;\n view?: any;\n return_docs?: boolean;\n batch_size?: number;\n style?: string;\n}\n\nexport interface CouchChangesOptionsLive extends CouchChangesOptionsBase {\n live: true;\n}\n\nexport interface CouchChangesOptionsNonLive extends CouchChangesOptionsBase {\n live: false;\n}\ninterface CouchChangesOnChangeEvent {\n on: (eventName: string, handler: Function) => void;\n off: (eventName: string, handler: Function) => void;\n cancel(): void;\n}\n\nexport type CouchWriteError = {\n /**\n * status code from couchdb\n * 409 for 'conflict'\n */\n status: number;\n error: true;\n /**\n * primary key value of the errored document\n */\n id: string;\n};\n\n/**\n * possible couch-settings\n * @link https://couchdb.com/api.html#create_database\n */\nexport interface CouchSettings {\n auto_compaction?: boolean;\n revs_limit?: number;\n ajax?: any;\n fetch?: any;\n auth?: any;\n skip_setup?: boolean;\n storage?: any;\n size?: number;\n location?: string;\n iosDatabaseLocation?: string;\n}\n\n/**\n * options for couch.allDocs()\n * @link https://couchdb.com/api.html#batch_fetch\n */\nexport type CouchAllDocsOptions = {\n include_docs?: boolean;\n conflicts?: boolean;\n attachments?: boolean;\n binary?: boolean;\n startkey?: string;\n endkey?: string;\n inclusive_end?: boolean;\n limit?: number;\n skip?: number;\n descending?: boolean;\n key?: string;\n keys?: string[];\n update_seq?: string;\n\n // undocument but needed\n revs?: boolean;\n deleted?: 'ok';\n};\n\nexport type CouchSyncHandlerEvents = 'change' | 'paused' | 'active' | 'error' | 'complete';\nexport type CouchSyncHandler = {\n on(ev: CouchSyncHandlerEvents, fn: (el: any) => void): void;\n off(ev: CouchSyncHandlerEvents, fn: any): void;\n cancel(): void;\n};\n\nexport type CouchChangeRow = {\n id: string;\n seq: number;\n deleted?: true;\n changes: {\n rev: 'string';\n }[];\n /**\n * only if include_docs === true\n */\n doc?: CouchChangeDoc;\n};\n\nexport type CouchAttachmentMeta = {\n digest: string;\n content_type: string;\n length: number;\n stub: boolean;\n\n /**\n * 'revpos indicates the generation number (numeric prefix in the revID) at which the attachment was last altered'\n * @link https://github.com/couchbase/couchbase-lite-ios/issues/1200#issuecomment-206444554\n */\n revpos: number;\n};\n\nexport type BlobBuffer = Buffer | Blob;\n\nexport type CouchAttachmentWithData = CouchAttachmentMeta & {\n /**\n * Base64 string with the data\n * or directly a buffer\n */\n data: BlobBuffer;\n type: string;\n /**\n * If set, must be false\n * because we have the full data and not only a stub.\n */\n stub?: false;\n};\n\nexport type CouchChangeDoc = {\n _id: string;\n _rev: string;\n /**\n * True if the document is deleted.\n */\n _deleted?: boolean;\n _attachments: {\n [attachmentId: string]: CouchAttachmentMeta;\n };\n};\n\nexport type WithAttachments = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: CouchAttachmentMeta;\n };\n};\nexport type WithAttachmentsData = Data & {\n /**\n * Intentional optional,\n * if the document has no attachments,\n * we do NOT have an empty object.\n */\n _attachments?: {\n [attachmentId: string]: CouchAttachmentWithData;\n };\n};\n\n\nexport type WithCouchMeta = Data & {\n _rev: string;\n _attachments?: {\n [attachmentId: string]: CouchAttachmentMeta;\n };\n _deleted?: boolean;\n};\n\nexport type CouchdbChangesResult = {\n results: CouchChangeRow[];\n last_seq: number;\n};\n\ndeclare type Debug = {\n enable(what: string): void;\n disable(): void;\n};\n\nexport type CouchDbSorting = (string | string[] | { [k: string]: 'asc' | 'desc' | 1 | -1; })[];\n\n// this is not equal to the standard MangoQuery\n// because of different sorting\nexport type CouchdbQuery = MangoQuery & {\n sort?: CouchDbSorting;\n};\n\nexport type CouchBulkDocResultRow = {\n ok: boolean;\n id: string;\n rev: string;\n\n error?: 'conflict';\n reason?: string;\n};\n\nexport type CouchCheckpoint = {\n sequence: number;\n};\n\nexport type CouchBulkDocOptions = {\n new_edits?: boolean;\n\n // custom options for RxDB\n isDeeper?: boolean;\n custom?: {\n primaryPath: string;\n writeRowById: Map>;\n insertDocsById: Map;\n previousDocsInDb: Map;\n context: string;\n };\n};\n\nexport type CouchMangoQuery = MangoQuery & {\n index: undefined;\n use_index?: string;\n};\n\nexport type ExplainedCouchQuery = {\n dbname: string;\n index: {\n ddoc: string | null;\n name: string; // 'idx-rxdb-index-age,_id'\n type: 'json';\n def: {\n fields: MangoQuerySortPart[];\n };\n };\n selector: MangoQuerySelector;\n range: {\n start_key: any[];\n end_key: any[];\n };\n opts: {\n use_index: string[];\n bookmark: string;\n sort: MangoQuerySortPart[];\n conflicts: boolean;\n r: any[];\n };\n skip: number;\n};\n\nexport type CouchAllDocsResponse = {\n offset: number;\n rows: {\n id: string;\n doc: any;\n key: string;\n value: {\n rev: string;\n deleted?: boolean;\n };\n error?: 'not_found' | string;\n }[];\n total_rows: number;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/rx-database.d.js.map b/dist/lib/types/rx-database.d.js.map index 8e696707939..53ad70ca32c 100644 --- a/dist/lib/types/rx-database.d.js.map +++ b/dist/lib/types/rx-database.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.d.js","names":[],"sources":["../../../src/types/rx-database.d.ts"],"sourcesContent":["import {\n MigrationState,\n RxCollection,\n RxDumpCollection,\n RxDumpCollectionAsAny\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from '../rx-database';\nimport { Observable } from 'rxjs';\nimport { RxStorage } from './rx-storage.interface';\nimport { PouchDBExpressServerOptions } from './plugins/server-couchdb';\nimport { RxLocalDocument } from './plugins/local-documents';\nimport { RxCleanupPolicy } from './plugins/cleanup';\nimport { HashFunction } from './util';\n\nexport interface RxDatabaseCreator {\n storage: RxStorage;\n instanceCreationOptions?: InstanceCreationOptions;\n name: string;\n password?: string | any;\n multiInstance?: boolean;\n eventReduce?: boolean;\n ignoreDuplicate?: boolean;\n options?: any;\n cleanupPolicy?: Partial;\n /**\n * Set this to true if you want to store local documents\n * in the RxDatabase instance.\n */\n localDocuments?: boolean;\n\n hashFunction?: HashFunction;\n\n /**\n * By default, count() queries in 'slow' mode are not allowed.\n */\n allowSlowCount?: boolean;\n}\n\n// options for the server-plugin\nexport interface CouchDBServerOptions {\n path?: string;\n port?: number;\n cors?: boolean;\n startServer?: boolean;\n pouchdbExpressOptions?: PouchDBExpressServerOptions;\n}\n\nexport type CollectionsOfDatabase = { [key: string]: RxCollection; };\nexport type RxDatabase<\n Collections = CollectionsOfDatabase,\n Internals = any,\n InstanceCreationOptions = any,\n> = RxDatabaseBase<\nInternals,\nInstanceCreationOptions,\nCollections\n> &\nCollections & RxDatabaseGenerated;\n\nexport type AllMigrationStates = {\n collection: RxCollection;\n state: MigrationState;\n}[];\n\nexport interface RxLocalDocumentMutation {\n insertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n upsertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n getLocal(id: string): Promise<\n RxLocalDocument | null\n >;\n getLocal$(id: string): Observable<\n RxLocalDocument | null\n >;\n}\n\nexport interface RxDatabaseGenerated extends RxLocalDocumentMutation> { }\n\n/**\n * Extract the **DocumentType** of a collection.\n */\ntype ExtractDTcol

= P extends RxCollection ? T : { [prop: string]: any; };\n\ninterface RxDumpDatabaseBase {\n instanceToken: string;\n name: string;\n passwordHash: string | null;\n}\nexport interface RxDumpDatabase extends RxDumpDatabaseBase {\n collections: RxDumpCollection>[];\n}\n/**\n * All base properties are typed as any because they can be encrypted.\n */\nexport interface RxDumpDatabaseAny extends RxDumpDatabaseBase {\n collections: RxDumpCollection>>[];\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-database.d.js","names":[],"sources":["../../../src/types/rx-database.d.ts"],"sourcesContent":["import {\n MigrationState,\n RxCollection,\n RxDumpCollection,\n RxDumpCollectionAsAny\n} from './rx-collection';\nimport {\n RxDatabaseBase\n} from '../rx-database';\nimport { Observable } from 'rxjs';\nimport { RxStorage } from './rx-storage.interface';\nimport { RxLocalDocument } from './plugins/local-documents';\nimport { RxCleanupPolicy } from './plugins/cleanup';\nimport { HashFunction } from './util';\n\nexport interface RxDatabaseCreator {\n storage: RxStorage;\n instanceCreationOptions?: InstanceCreationOptions;\n name: string;\n password?: string | any;\n multiInstance?: boolean;\n eventReduce?: boolean;\n ignoreDuplicate?: boolean;\n options?: any;\n cleanupPolicy?: Partial;\n /**\n * Set this to true if you want to store local documents\n * in the RxDatabase instance.\n */\n localDocuments?: boolean;\n\n hashFunction?: HashFunction;\n\n /**\n * By default, count() queries in 'slow' mode are not allowed.\n */\n allowSlowCount?: boolean;\n}\n\nexport type CollectionsOfDatabase = { [key: string]: RxCollection; };\nexport type RxDatabase<\n Collections = CollectionsOfDatabase,\n Internals = any,\n InstanceCreationOptions = any,\n> = RxDatabaseBase<\nInternals,\nInstanceCreationOptions,\nCollections\n> &\nCollections & RxDatabaseGenerated;\n\nexport type AllMigrationStates = {\n collection: RxCollection;\n state: MigrationState;\n}[];\n\nexport interface RxLocalDocumentMutation {\n insertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n upsertLocal(id: string, data: LocalDocType): Promise<\n RxLocalDocument\n >;\n getLocal(id: string): Promise<\n RxLocalDocument | null\n >;\n getLocal$(id: string): Observable<\n RxLocalDocument | null\n >;\n}\n\nexport interface RxDatabaseGenerated extends RxLocalDocumentMutation> { }\n\n/**\n * Extract the **DocumentType** of a collection.\n */\ntype ExtractDTcol

= P extends RxCollection ? T : { [prop: string]: any; };\n\ninterface RxDumpDatabaseBase {\n instanceToken: string;\n name: string;\n passwordHash: string | null;\n}\nexport interface RxDumpDatabase extends RxDumpDatabaseBase {\n collections: RxDumpCollection>[];\n}\n/**\n * All base properties are typed as any because they can be encrypted.\n */\nexport interface RxDumpDatabaseAny extends RxDumpDatabaseBase {\n collections: RxDumpCollection>>[];\n}\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/rx-document.d.js.map b/dist/lib/types/rx-document.d.js.map index f6a9da3a41d..881042a6102 100644 --- a/dist/lib/types/rx-document.d.js.map +++ b/dist/lib/types/rx-document.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-document.d.js","names":[],"sources":["../../../src/types/rx-document.d.ts"],"sourcesContent":["import {\n Observable,\n BehaviorSubject\n} from 'rxjs';\n\nimport {\n RxCollection,\n} from './rx-collection';\nimport {\n RxAttachment,\n RxAttachmentCreator\n} from './rx-attachment';\nimport { RxDocumentData } from './rx-storage';\nimport { RxChangeEvent } from './rx-change-event';\nimport { DeepReadonly, PlainJsonValue } from './util';\nimport { UpdateQuery } from './plugins/update';\nimport { CRDTEntry } from './plugins/crdt';\n\nexport type RxDocument = RxDocumentBase & RxDocumentType & OrmMethods;\n\ndeclare type AtomicUpdateFunction = (\n doc: RxDocumentData,\n rxDocument: RxDocument\n) => RxDocumentType | Promise;\n\n/**\n * Meta data that is attached to each document by RxDB.\n */\nexport type RxDocumentMeta = {\n /**\n * Last write time.\n * Unix epoch in milliseconds.\n */\n lwt: number;\n\n /**\n * Any other value can be attached to the _meta data.\n * Mostly done by plugins to mark documents.\n */\n [k: string]: PlainJsonValue;\n};\n\nexport declare interface RxDocumentBase {\n isInstanceOfRxDocument: true;\n collection: RxCollection;\n readonly deleted: boolean;\n\n readonly $: Observable>;\n readonly deleted$: Observable;\n\n readonly primary: string;\n readonly allAttachments$: Observable[]>;\n\n // internal things\n _dataSync$: BehaviorSubject>;\n _data: RxDocumentData;\n primaryPath: string;\n revision: string;\n _atomicQueue: Promise;\n $emit(cE: RxChangeEvent): void;\n _saveData(newData: any, oldData: any): Promise;\n // /internal things\n\n get$(path: string): Observable;\n get(objPath: string): DeepReadonly;\n populate(objPath: string): Promise | any | null>;\n\n /**\n * mutate the document with a function\n */\n atomicUpdate(mutationFunction: AtomicUpdateFunction, context?: string): Promise>;\n /**\n * patches the given properties\n */\n atomicPatch(patch: Partial): Promise>;\n\n update(updateObj: UpdateQuery): Promise;\n updateCRDT(updateObj: CRDTEntry | CRDTEntry[]): Promise;\n remove(): Promise;\n _handleChangeEvent(cE: any): void;\n\n // only for temporary documents\n set(objPath: string, value: any): RxDocument;\n save(): Promise;\n\n // attachments\n putAttachment(\n creator: RxAttachmentCreator,\n /**\n * If set to true and data is equal,\n * operation will be skipped.\n * This prevents us from upgrading the revision\n * and causing events in the change stream.\n * (default = true)\n */\n skipIfSame?: boolean\n ): Promise>;\n getAttachment(id: string): RxAttachment | null;\n allAttachments(): RxAttachment[];\n\n toJSON(withRevAndAttachments: true): DeepReadonly>;\n toJSON(withRevAndAttachments?: false): DeepReadonly;\n\n toMutableJSON(withRevAndAttachments: true): RxDocumentData;\n toMutableJSON(withRevAndAttachments?: false): RxDocType;\n\n destroy(): void;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-document.d.js","names":[],"sources":["../../../src/types/rx-document.d.ts"],"sourcesContent":["import {\n Observable\n} from 'rxjs';\n\nimport {\n RxCollection,\n} from './rx-collection';\nimport {\n RxAttachment,\n RxAttachmentCreator\n} from './rx-attachment';\nimport { RxDocumentData, WithDeleted } from './rx-storage';\nimport { RxChangeEvent } from './rx-change-event';\nimport { DeepReadonly, MaybePromise, PlainJsonValue } from './util';\nimport { UpdateQuery } from './plugins/update';\nimport { CRDTEntry } from './plugins/crdt';\n\nexport type RxDocument = RxDocumentBase & RxDocumentType & OrmMethods;\n\n\n/**\n * The public facing modify update function.\n * It only gets the document parts as input, that\n * are mutateable by the user.\n */\nexport type ModifyFunction = (\n doc: WithDeleted\n) => MaybePromise> | MaybePromise;\n\n/**\n * Meta data that is attached to each document by RxDB.\n */\nexport type RxDocumentMeta = {\n /**\n * Last write time.\n * Unix epoch in milliseconds.\n */\n lwt: number;\n\n /**\n * Any other value can be attached to the _meta data.\n * Mostly done by plugins to mark documents.\n */\n [k: string]: PlainJsonValue;\n};\n\nexport declare interface RxDocumentBase {\n isInstanceOfRxDocument: true;\n collection: RxCollection;\n readonly deleted: boolean;\n\n readonly $: Observable>>;\n readonly deleted$: Observable;\n\n readonly primary: string;\n readonly allAttachments$: Observable[]>;\n\n // internal things\n _data: RxDocumentData;\n primaryPath: string;\n revision: string;\n $emit(cE: RxChangeEvent): void;\n _saveData(newData: any, oldData: any): Promise>;\n // /internal things\n\n // Returns the latest state of the document\n getLatest(): RxDocument;\n\n\n get$(path: string): Observable;\n get(objPath: string): DeepReadonly;\n populate(objPath: string): Promise | any | null>;\n\n /**\n * mutate the document with a function\n */\n modify(mutationFunction: ModifyFunction, context?: string): Promise>;\n incrementalModify(mutationFunction: ModifyFunction, context?: string): Promise>;\n\n /**\n * patches the given properties\n */\n patch(patch: Partial): Promise>;\n incrementalPatch(patch: Partial): Promise>;\n\n update(updateObj: UpdateQuery): Promise>;\n incrementalUpdate(updateObj: UpdateQuery): Promise>;\n\n updateCRDT(updateObj: CRDTEntry | CRDTEntry[]): Promise>;\n\n remove(): Promise>;\n incrementalRemove(): Promise>;\n\n // only for temporary documents\n set(objPath: string, value: any): RxDocument;\n save(): Promise;\n\n // attachments\n putAttachment(\n creator: RxAttachmentCreator\n ): Promise>;\n getAttachment(id: string): RxAttachment | null;\n allAttachments(): RxAttachment[];\n\n toJSON(withRevAndAttachments: true): DeepReadonly>;\n toJSON(withRevAndAttachments?: false): DeepReadonly;\n\n toMutableJSON(withRevAndAttachments: true): RxDocumentData;\n toMutableJSON(withRevAndAttachments?: false): RxDocType;\n\n destroy(): void;\n}\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/rx-error.d.js.map b/dist/lib/types/rx-error.d.js.map index 023f5fe05df..4baab9f02e6 100644 --- a/dist/lib/types/rx-error.d.js.map +++ b/dist/lib/types/rx-error.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import { RxJsonSchema } from './rx-schema';\nimport {\n RxSchema\n} from '../rx-schema';\nimport { RxPlugin } from './rx-plugin';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages';\nimport { RxReplicationWriteToMasterRow } from './replication-protocol';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport declare class RxError extends Error {\n readonly rxdb: boolean; // always true, use this to detect if its an rxdb-error\n readonly parameters: RxErrorParameters; // an object with parameters to use the programmatically\n readonly code: RxErrorKey; // error-code\n readonly typeError: false; // true if is TypeError\n}\n\nexport declare class RxTypeError extends TypeError {\n readonly rxdb: boolean; // always true, use this to detect if its an rxdb-error\n readonly parameters: RxErrorParameters; // an object with parameters to use the programmatically\n readonly code: RxErrorKey; // error-code\n readonly typeError: true; // true if is TypeError\n}\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: any;\n readonly errors?: RxErrorItem[];\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly pouchDbError?: any;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport interface RxErrorItem {\n readonly field: string;\n readonly message: string;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import { RxJsonSchema } from './rx-schema';\nimport {\n RxSchema\n} from '../rx-schema';\nimport { RxPlugin } from './rx-plugin';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages';\nimport { RxReplicationWriteToMasterRow } from './replication-protocol';\nimport { BulkWriteRow, RxDocumentData } from './rx-storage';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport type {\n RxError,\n RxTypeError\n} from '../rx-error';\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: PlainJsonError;\n readonly errors?: PlainJsonError[];\n readonly writeError?: RxStorageWriteError;\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport type RxValidationError = {\n readonly field: string;\n readonly message: string;\n};\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n rxdb?: true;\n code?: RxErrorKey;\n parameters?: RxErrorParameters;\n stack?: string;\n};\n\n\n\n\n\n/**\n * Error that can happer per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageWriteErrorBase = {\n\n status: number\n | 409 // conflict\n | 422 // schema validation error\n | 510 // attachment data missing\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n};\n\nexport type RxStorageWriteErrorConflict = RxStorageWriteErrorBase & {\n status: 409;\n /**\n * A conflict error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb: RxDocumentData;\n};\n\nexport type RxStorageWriteErrorValidation = RxStorageWriteErrorBase & {\n status: 422;\n /**\n * Other properties that give\n * information about the error,\n * for example a schema validation error\n * might contain the exact error from the validator here.\n * Must be plain JSON!\n */\n validationErrors: RxValidationError[];\n};\n\nexport type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & {\n status: 510;\n attachmentId: string;\n documentInDb?: RxDocumentData;\n};\n\n\nexport type RxStorageWriteError =\n RxStorageWriteErrorConflict |\n RxStorageWriteErrorValidation |\n RxStorageWriteErrorAttachment;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/rx-query.d.js.map b/dist/lib/types/rx-query.d.js.map index ef01b66de82..756778fd29b 100644 --- a/dist/lib/types/rx-query.d.js.map +++ b/dist/lib/types/rx-query.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-query.d.js","names":[],"sources":["../../../src/types/rx-query.d.ts"],"sourcesContent":["import {\n RxQueryBase\n} from '../rx-query';\nimport { StringKeys } from './util';\n\n/**\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport interface RxQueryOptions {\n $eq?: T;\n $gt?: T;\n $gte?: T;\n $lt?: T;\n $lte?: T;\n $ne?: T;\n $in?: T[];\n $nin?: T[];\n $regex?: RegExp;\n $exists?: boolean;\n $type?: 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object';\n $mod?: number;\n $not?: T;\n $size?: number;\n $elemMatch?: RxQueryOptions;\n}\n\nexport type RxQueryObject = keyof T & { [P in keyof T]?: T[P] | RxQueryOptions; } & {\n $or: RxQueryObject[];\n $nor: RxQueryObject[];\n $and: RxQueryObject[];\n};\n\n// TODO this should be typed\nexport type MangoQuerySelector = {\n [k: string]: MangoQuerySelector | any;\n};\n\n/**\n * Discussion was at:\n * @link https://github.com/pubkey/rxdb/issues/1972\n */\nexport type MangoQuerySortDirection = 'asc' | 'desc';\nexport type MangoQuerySortPart = {\n [k in StringKeys | string]: MangoQuerySortDirection;\n};\n\nexport type MangoQuerySelectorAndIndex = {\n /**\n * Selector is optional,\n * if not given, the query matches all documents\n * that are not _deleted=true.\n */\n selector?: MangoQuerySelector;\n /**\n * By default, the RxStorage implementation\n * decides which index to use when running the query.\n *\n * For better performance, a different index might be defined\n * by setting it in the query.\n * How this improves performance and if the defined index is used,\n * depends on the RxStorage implementation.\n */\n index?: string | string[];\n};\n\nexport type MangoQueryNoLimit = MangoQuerySelectorAndIndex & {\n /**\n * Sorting of the results.\n * If no sort is set, RxDB will sort by the primary key.\n * Also if sort is set, RxDB will add primaryKey sorting\n * if the primaryKey was not in the sort parameters before.\n * This ensures that there is a deterministic sorting of the\n * results, not mather at which order the documents have been\n * inserted into the storage.\n */\n sort?: MangoQuerySortPart[];\n};\n\nexport type MangoQuery = MangoQueryNoLimit & {\n skip?: number;\n limit?: number;\n};\n\nexport type RxQueryOP = 'find' | 'findOne' | 'count';\n\nexport declare class RxQuery extends RxQueryBase {\n equals(queryObj: any): RxQuery;\n eq(queryObj: any): RxQuery;\n or(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n nor(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n and(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n gt(queryObj: any): RxQuery;\n gte(queryObj: any): RxQuery;\n lt(queryObj: any): RxQuery;\n lte(queryObj: any): RxQuery;\n ne(queryObj: any): RxQuery;\n in(queryObj: any[]): RxQuery;\n nin(queryObj: any[]): RxQuery;\n all(queryObj: any): RxQuery;\n regex(queryObj: RegExp): RxQuery;\n exists(queryObj: any): RxQuery;\n elemMatch(queryObj: any): RxQuery;\n mod(p1: any, p2: any, p3: any): RxQuery;\n}\n"],"mappings":";;AAAA"} \ No newline at end of file +{"version":3,"file":"rx-query.d.js","names":[],"sources":["../../../src/types/rx-query.d.ts"],"sourcesContent":["import {\n RxQueryBase\n} from '../rx-query';\nimport { StringKeys } from './util';\n\n/**\n * Typed Mango Query Selector\n * @link https://github.com/mongodb/node-mongodb-native/blob/26bce4a8debb65df5a42dc8599e886c9c83de10d/src/mongo_types.ts\n * @link https://stackoverflow.com/a/58436959/3443137\n */\n\ntype Join = K extends string | number ?\n P extends string | number ?\n `${K}${'' extends P ? '' : '.'}${P}`\n : never : never;\n\nexport type Paths = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: K extends string | number ?\n `${K}` | (Paths extends infer R ? Join : never)\n : never\n }[keyof T] : '';\n\nexport type Leaves = [D] extends [never] ? never : T extends object ?\n { [K in keyof T]-?: Join> }[keyof T] : '';\ntype Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]];\n\nexport type PropertyType = string extends Property\n ? unknown\n : Property extends keyof Type\n ? Type[Property]\n : Property extends `${number}`\n ? Type extends ReadonlyArray\n ? ArrayType\n : unknown\n : Property extends `${infer Key}.${infer Rest}`\n ? Key extends `${number}`\n ? Type extends ReadonlyArray\n ? PropertyType\n : unknown\n : Key extends keyof Type\n ? Type[Key] extends Map\n ? MapType\n : PropertyType\n : unknown\n : unknown;\n\n\n/*\n * The MongoDB query library is huge and we do not need all the operators.\n * If you add an operator here, make sure that you properly add a test in\n * the file /test/unit/rx-storage-query-correctness.test.ts\n *\n * @link https://github.com/kofrasa/mingo#es6\n */\nexport interface MangoQueryOperators {\n $eq?: PathValueType;\n $gt?: PathValueType;\n $gte?: PathValueType;\n $lt?: PathValueType;\n $lte?: PathValueType;\n $ne?: PathValueType;\n $in?: PathValueType[];\n $nin?: PathValueType[];\n $regex?: string | RegExp;\n $exists?: boolean;\n $type?: 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object';\n $mod?: number;\n $not?: PathValueType;\n $size?: number;\n $elemMatch?: MangoQuerySelector;\n}\n\nexport type MangoQuerySelector = Partial<{\n [Property in Paths]: MangoQueryOperators | PropertyType;\n}> & {\n $and?: MangoQuerySelector[];\n $or?: MangoQuerySelector[];\n $nor?: MangoQuerySelector[];\n};\n\n/**\n * Discussion was at:\n * @link https://github.com/pubkey/rxdb/issues/1972\n */\nexport type MangoQuerySortDirection = 'asc' | 'desc';\nexport type MangoQuerySortPart = {\n [k in StringKeys | string]: MangoQuerySortDirection;\n};\n\nexport type MangoQuerySelectorAndIndex = {\n /**\n * Selector is optional,\n * if not given, the query matches all documents\n * that are not _deleted=true.\n */\n selector?: MangoQuerySelector;\n /**\n * By default, the RxStorage implementation\n * decides which index to use when running the query.\n *\n * For better performance, a different index might be defined\n * by setting it in the query.\n * How this improves performance and if the defined index is used,\n * depends on the RxStorage implementation.\n */\n index?: string | string[];\n};\n\nexport type MangoQueryNoLimit = MangoQuerySelectorAndIndex & {\n /**\n * Sorting of the results.\n * If no sort is set, RxDB will sort by the primary key.\n * Also if sort is set, RxDB will add primaryKey sorting\n * if the primaryKey was not in the sort parameters before.\n * This ensures that there is a deterministic sorting of the\n * results, not mather at which order the documents have been\n * inserted into the storage.\n */\n sort?: MangoQuerySortPart[];\n};\n\nexport type MangoQuery = MangoQueryNoLimit & {\n skip?: number;\n limit?: number;\n};\n\nexport type RxQueryOP = 'find' | 'findOne' | 'count' | 'findByIds';\n\nexport declare class RxQuery extends RxQueryBase {\n equals(queryObj: any): RxQuery;\n eq(queryObj: any): RxQuery;\n or(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n nor(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n and(queryObj: keyof RxDocumentType | string | any[]): RxQuery;\n gt(queryObj: any): RxQuery;\n gte(queryObj: any): RxQuery;\n lt(queryObj: any): RxQuery;\n lte(queryObj: any): RxQuery;\n ne(queryObj: any): RxQuery;\n in(queryObj: any[]): RxQuery;\n nin(queryObj: any[]): RxQuery;\n all(queryObj: any): RxQuery;\n regex(queryObj: RegExp): RxQuery;\n exists(queryObj: any): RxQuery;\n elemMatch(queryObj: any): RxQuery;\n mod(p1: any, p2: any, p3: any): RxQuery;\n}\n"],"mappings":";;AAAA"} \ No newline at end of file diff --git a/dist/lib/types/rx-storage.d.js.map b/dist/lib/types/rx-storage.d.js.map index b462c8add28..5dd65ed6288 100644 --- a/dist/lib/types/rx-storage.d.js.map +++ b/dist/lib/types/rx-storage.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage.d.js","names":[],"sources":["../../../src/types/rx-storage.d.ts"],"sourcesContent":["import type { ChangeEvent } from 'event-reduce-js';\nimport { RxChangeEvent } from './rx-change-event';\nimport { RxDocumentMeta } from './rx-document';\nimport { MangoQuery } from './rx-query';\nimport { RxJsonSchema } from './rx-schema';\nimport { ById, Override, StringKeys } from './util';\n\n/**\n * The document data how it comes out of the storage instance.\n * Contains all meta data like revision, attachments and deleted-flag.\n */\nexport type RxDocumentData = T & {\n\n /**\n * As other NoSQL databases,\n * RxDB also assumes that no data is finally deleted.\n * Instead the documents are stored with _deleted: true\n * which means they will not be returned at queries.\n */\n _deleted: boolean;\n\n /**\n * The attachments meta data is stored besides to document.\n */\n _attachments: {\n [attachmentId: string]: RxAttachmentData;\n };\n\n /**\n * Contains a revision which is concated with a [height: number]-[identifier: string]\n * like: '1-3hl4kj3l4kgj34g34glk'.\n * The revision is used to detect write conflicts and have a document history.\n * Revisions behave similar to couchdb revisions:\n * @link https://docs.couchdb.org/en/stable/replication/conflicts.html#revision-tree\n\n * When writing a document, you must send the correct revision in the previous-field\n * to make sure that you do not cause a write conflict.\n * The revision of the 'new' document-field must be created, for example via util.createRevision().\n * Any revision that matches the [height]-[hash] format can be used.\n */\n _rev: string;\n _meta: RxDocumentMeta;\n};\n\nexport type RxDocumentDataById = {\n [documentId: string]: RxDocumentData;\n};\n\n/**\n * The document data how it is send to the\n * storage instance to save it.\n */\n// We & T here instead of in RxDocumentData to preserver indexability by keyof T which the Override breaks\nexport type RxDocumentWriteData = T & Override, {\n _attachments: {\n /**\n * To create a new attachment, set the write data\n * To delete an attachment, leave it out on the _attachments property.\n * To change an attachment, set the new write data.\n * To not touch an attachment, just send the stub again\n * which came out of the storage instance.\n */\n [attachmentId: string]: RxAttachmentData | RxAttachmentWriteData;\n };\n}>;\n\nexport type WithDeleted = DocType & {\n _deleted: boolean;\n};\n\n/**\n * Send to the bulkWrite() method of a storage instance.\n */\nexport type BulkWriteRow = {\n /**\n * The current document state in the storage engine,\n * assumed by the application.\n * Undefined if the document is a new insert.\n * While with pouchdb we have to practically only provide the previous revision\n * we here have to send the full previous document data.\n * The reason is that to get the previous revision you anyway have to get the full\n * previous document and so it is easier to just send it all to the storage instance.\n * This will later allow us to use something different then the _rev key for conflict detection\n * when we implement other storage instances.\n */\n previous?: RxDocumentData;\n /**\n * The new document data to be stored in the storage instance.\n */\n document: RxDocumentWriteData;\n};\nexport type BulkWriteRowById = {\n [documentId: string]: BulkWriteRow;\n};\n\n/**\n * After the RxStorage has processed all rows,\n * we have this to work with afterwards.\n */\nexport type BulkWriteRowProcessed = BulkWriteRow & {\n document: RxDocumentData;\n};\n\n\nexport type RxAttachmentDataBase = {\n /**\n * Size of the attachments data\n */\n length: number;\n /**\n * Content type like 'plain/text'\n */\n type: string;\n};\n\n\n/**\n * Meta data of the attachment\n * how it is send to, or comes out of the RxStorage implementation.\n */\nexport type RxAttachmentData = RxAttachmentDataBase & {\n /**\n * The hash of the attachments content.\n * It is NOT calculated by RxDB, instead it is calculated\n * by the RxStorage.\n * There is no way to pre-calculate the hash from the outside because\n * the RxStorage might hash a compressed binary or do a different base64 transformation\n * before hashing.\n * The only guarantee is that the digest will change when the attachments data changes.\n * @link https://github.com/pouchdb/pouchdb/issues/3156#issuecomment-66831010\n * @link https://github.com/pubkey/rxdb/pull/4107\n */\n digest: string;\n};\n\n/**\n * Data which is needed for new attachments\n * that are send from RxDB to the RxStorage implementation.\n */\nexport type RxAttachmentWriteData = RxAttachmentDataBase & {\n /**\n * The data of the attachment. As string in base64 format.\n * In the past we used BlobBuffer internally but it created many\n * problems because of then we need the full data (for encryption/compression)\n * so we anyway have to get the string value out of the BlobBuffer.\n *\n * Also using BlobBuffer has no performance benefit because in some RxStorage implementations,\n * like PouchDB, it just keeps the transaction open for longer because the BlobBuffer\n * has be be read.\n */\n data: string;\n};\n\n\n/**\n * Error that can happer per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageBulkWriteError = {\n\n status: number |\n 409 // conflict\n /**\n * Before you add any other status code,\n * check pouchdb/packages/node_modules/pouch-errors/src/index.js\n * and try to use the same code as PouchDB does.\n */\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n\n /**\n * The error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb?: RxDocumentData;\n};\n\nexport type RxStorageBulkWriteResponse = {\n /**\n * A map that is indexed by the documentId\n * contains all succeeded writes.\n */\n success: RxDocumentDataById;\n\n /**\n * A map that is indexed by the documentId\n * contains all errored writes.\n */\n error: ById>;\n};\n\nexport type PreparedQuery = MangoQuery | any;\n\n/**\n * We return a complex object instead of a single array\n * so we are able to add additional fields in the future.\n */\nexport type RxStorageQueryResult = {\n // the found documents, sort order is important.\n documents: RxDocumentData[];\n};\n\nexport type RxStorageCountResult = {\n count: number;\n /**\n * Returns the mode which was used by the storage\n * to count the documents.\n * If this returns 'slow', RxDB will throw by default\n * if 'allowSlowCount' is not set.\n */\n mode: 'fast' | 'slow';\n};\n\nexport type RxStorageInstanceCreationParams = {\n\n /**\n * A string to uniquely identify the instance of the JavaScript object\n * of the RxDatabase where this RxStorageInstance belongs to.\n * In most cases you would use RxDatabase.token here.\n *\n * This is used so that we can add caching or reuse stuff that belongs to the same RxDatabase.\n * For example the BroadcastChannel that is used for event propagation between multiple browser tabs\n * is cached by this token.\n *\n * In theory we could just use the databaseName for that. But to make it easier in unit tests\n * to simulate cross-tab usage, we cannot assume that the databaseName is unique in a single\n * JavaScript process. Therefore we use the instance token instead.\n */\n databaseInstanceToken: string;\n\n\n databaseName: string;\n collectionName: string;\n schema: RxJsonSchema>;\n options: InstanceCreationOptions;\n /**\n * If multiInstance is true, there can be more\n * then one instance of the database, for example\n * when multiple browser tabs exist or more then one Node.js\n * process relies on the same storage.\n */\n multiInstance: boolean;\n password?: string;\n};\n\nexport type ChangeStreamOptions = {\n\n /**\n * Sequence number of the first event to start with.\n * If you want to get all ongoing events,\n * first get the latest sequence number and input it here.\n *\n * Optional on changeStream,\n * will start from the newest sequence.\n */\n startSequence?: number;\n /**\n * limits the amount of results\n */\n limit?: number;\n};\n\n/**\n * In the past we handles each RxChangeEvent by its own.\n * But it has been shown that this take way more performance then needed,\n * especially when the events get transferred over a data layer\n * like with WebWorkers or the BroadcastChannel.\n * So we now process events as bulks internally.\n */\nexport type EventBulk = {\n /**\n * Unique id of the bulk,\n * used to detect duplicate bulks\n * that have already been processed.\n */\n id: string;\n events: EventType[];\n\n /**\n * Required for replication.\n * Passing this checkpoint into getChangedDocumentsSince()\n * must return all items that have been modied AFTER this write event.\n */\n checkpoint: CheckpointType;\n\n /**\n * The context that was given at the call to bulkWrite()\n * that caused this EventBulk.\n */\n context: string;\n};\n\nexport type ChangeStreamEvent = ChangeEvent> & {\n /**\n * An integer that is increasing\n * and unique per event.\n * Can be used to sort events or get information\n * about how many events there are.\n */\n sequence: number;\n /**\n * The value of the primary key\n * of the changed document\n */\n id: string;\n};\n\nexport type RxStorageChangeEvent = Omit, 'isLocal' | 'collectionName'>;\n\n/**\n * An example for how a RxStorage checkpoint can look like.\n * NOTICE: Not all implementations use this type.\n */\nexport type RxStorageDefaultCheckpoint = {\n id: string;\n lwt: number;\n};\n\n\n\nexport type CategorizeBulkWriteRowsOutput = {\n bulkInsertDocs: BulkWriteRowProcessed[];\n bulkUpdateDocs: BulkWriteRowProcessed[];\n /**\n * Ids of all documents that are changed\n * and so their change must be written into the\n * sequences table so that they can be fetched via\n * RxStorageInstance().getChangedDocumentsSince().\n */\n changedDocumentIds: RxDocType[StringKeys][];\n errors: ById>;\n eventBulk: EventBulk>, any>;\n attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[];\n attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-storage.d.js","names":[],"sources":["../../../src/types/rx-storage.d.ts"],"sourcesContent":["import type { ChangeEvent } from 'event-reduce-js';\nimport { RxChangeEvent } from './rx-change-event';\nimport { RxDocumentMeta } from './rx-document';\nimport { RxStorageWriteError } from './rx-error';\nimport { MangoQuery } from './rx-query';\nimport { RxJsonSchema } from './rx-schema';\nimport { ById, Override, StringKeys } from './util';\n\n/**\n * The document data how it comes out of the storage instance.\n * Contains all meta data like revision, attachments and deleted-flag.\n */\nexport type RxDocumentData = T & {\n\n /**\n * As other NoSQL databases,\n * RxDB also assumes that no data is finally deleted.\n * Instead the documents are stored with _deleted: true\n * which means they will not be returned at queries.\n */\n _deleted: boolean;\n\n /**\n * The attachments meta data is stored besides to document.\n */\n _attachments: {\n [attachmentId: string]: RxAttachmentData;\n };\n\n /**\n * Contains a revision which is concated with a [height: number]-[identifier: string]\n * like: '1-3hl4kj3l4kgj34g34glk'.\n * The revision is used to detect write conflicts and have a document history.\n * Revisions behave similar to couchdb revisions:\n * @link https://docs.couchdb.org/en/stable/replication/conflicts.html#revision-tree\n\n * When writing a document, you must send the correct revision in the previous-field\n * to make sure that you do not cause a write conflict.\n * The revision of the 'new' document-field must be created, for example via util.createRevision().\n * Any revision that matches the [height]-[hash] format can be used.\n */\n _rev: string;\n _meta: RxDocumentMeta;\n};\n\nexport type RxDocumentDataById = {\n [documentId: string]: RxDocumentData;\n};\n\n/**\n * The document data how it is send to the\n * storage instance to save it.\n */\n// We & T here instead of in RxDocumentData to preserver indexability by keyof T which the Override breaks\nexport type RxDocumentWriteData = T & Override, {\n _attachments: {\n /**\n * To create a new attachment, set the write data\n * To delete an attachment, leave it out on the _attachments property.\n * To change an attachment, set the new write data.\n * To not touch an attachment, just send the stub again\n * which came out of the storage instance.\n */\n [attachmentId: string]: RxAttachmentData | RxAttachmentWriteData;\n };\n}>;\n\nexport type WithDeleted = DocType & {\n _deleted: boolean;\n};\n\n/**\n * Send to the bulkWrite() method of a storage instance.\n */\nexport type BulkWriteRow = {\n /**\n * The current document state in the storage engine,\n * assumed by the application.\n * Undefined if the document is a new insert.\n * Notice that we send the full document data as 'previous', not just the revision.\n * The reason is that to get the previous revision you anyway have to get the full\n * previous document and so it is easier to just send it all to the storage instance.\n * This will later allow us to use something different then the _rev key for conflict detection\n * when we implement other storage instances.\n */\n previous?: RxDocumentData;\n /**\n * The new document data to be stored in the storage instance.\n */\n document: RxDocumentWriteData;\n};\nexport type BulkWriteRowById = {\n [documentId: string]: BulkWriteRow;\n};\n\n/**\n * After the RxStorage has processed all rows,\n * we have this to work with afterwards.\n */\nexport type BulkWriteRowProcessed = BulkWriteRow & {\n document: RxDocumentData;\n};\n\n\nexport type RxAttachmentDataBase = {\n /**\n * Size of the attachments data\n */\n length: number;\n /**\n * Content type like 'plain/text'\n */\n type: string;\n};\n\n\n/**\n * Meta data of the attachment\n * how it is send to, or comes out of the RxStorage implementation.\n */\nexport type RxAttachmentData = RxAttachmentDataBase & {\n /**\n * The hash of the attachments content.\n * It is NOT calculated by RxDB, instead it is calculated\n * by the RxStorage.\n * There is no way to pre-calculate the hash from the outside because\n * the RxStorage might hash a compressed binary or do a different base64 transformation\n * before hashing.\n * The only guarantee is that the digest will change when the attachments data changes.\n * @link https://github.com/pouchdb/pouchdb/issues/3156#issuecomment-66831010\n * @link https://github.com/pubkey/rxdb/pull/4107\n */\n digest: string;\n};\n\n/**\n * Data which is needed for new attachments\n * that are send from RxDB to the RxStorage implementation.\n */\nexport type RxAttachmentWriteData = RxAttachmentDataBase & {\n /**\n * The data of the attachment. As string in base64 format.\n * In the past we used BlobBuffer internally but it created many\n * problems because of then we need the full data (for encryption/compression)\n * so we anyway have to get the string value out of the BlobBuffer.\n *\n * Also using BlobBuffer has no performance benefit because in some RxStorage implementations,\n * it just keeps the transaction open for longer because the BlobBuffer\n * has be be read.\n */\n data: string;\n};\n\n\n\n\nexport type RxStorageBulkWriteResponse = {\n /**\n * A map that is indexed by the documentId\n * contains all succeeded writes.\n */\n success: RxDocumentDataById;\n\n /**\n * A map that is indexed by the documentId\n * contains all errored writes.\n */\n error: ById>;\n};\n\nexport type PreparedQuery = MangoQuery | any;\n\n/**\n * We return a complex object instead of a single array\n * so we are able to add additional fields in the future.\n */\nexport type RxStorageQueryResult = {\n // the found documents, sort order is important.\n documents: RxDocumentData[];\n};\n\nexport type RxStorageCountResult = {\n count: number;\n /**\n * Returns the mode which was used by the storage\n * to count the documents.\n * If this returns 'slow', RxDB will throw by default\n * if 'allowSlowCount' is not set.\n */\n mode: 'fast' | 'slow';\n};\n\nexport type RxStorageInstanceCreationParams = {\n\n /**\n * A string to uniquely identify the instance of the JavaScript object\n * of the RxDatabase where this RxStorageInstance belongs to.\n * In most cases you would use RxDatabase.token here.\n *\n * This is used so that we can add caching or reuse stuff that belongs to the same RxDatabase.\n * For example the BroadcastChannel that is used for event propagation between multiple browser tabs\n * is cached by this token.\n *\n * In theory we could just use the databaseName for that. But to make it easier in unit tests\n * to simulate cross-tab usage, we cannot assume that the databaseName is unique in a single\n * JavaScript process. Therefore we use the instance token instead.\n */\n databaseInstanceToken: string;\n\n\n databaseName: string;\n collectionName: string;\n schema: RxJsonSchema>;\n options: InstanceCreationOptions;\n /**\n * If multiInstance is true, there can be more\n * then one instance of the database, for example\n * when multiple browser tabs exist or more then one Node.js\n * process relies on the same storage.\n */\n multiInstance: boolean;\n password?: string;\n};\n\nexport type ChangeStreamOptions = {\n\n /**\n * Sequence number of the first event to start with.\n * If you want to get all ongoing events,\n * first get the latest sequence number and input it here.\n *\n * Optional on changeStream,\n * will start from the newest sequence.\n */\n startSequence?: number;\n /**\n * limits the amount of results\n */\n limit?: number;\n};\n\n/**\n * In the past we handles each RxChangeEvent by its own.\n * But it has been shown that this take way more performance then needed,\n * especially when the events get transferred over a data layer\n * like with WebWorkers or the BroadcastChannel.\n * So we now process events as bulks internally.\n */\nexport type EventBulk = {\n /**\n * Unique id of the bulk,\n * used to detect duplicate bulks\n * that have already been processed.\n */\n id: string;\n events: EventType[];\n\n /**\n * Required for replication.\n * Passing this checkpoint into getChangedDocumentsSince()\n * must return all items that have been modied AFTER this write event.\n */\n checkpoint: CheckpointType;\n\n /**\n * The context that was given at the call to bulkWrite()\n * that caused this EventBulk.\n */\n context: string;\n};\n\nexport type ChangeStreamEvent = ChangeEvent> & {\n /**\n * An integer that is increasing\n * and unique per event.\n * Can be used to sort events or get information\n * about how many events there are.\n */\n sequence: number;\n /**\n * The value of the primary key\n * of the changed document\n */\n id: string;\n};\n\nexport type RxStorageChangeEvent = Omit, 'isLocal' | 'collectionName'>;\n\n/**\n * An example for how a RxStorage checkpoint can look like.\n * NOTICE: Not all implementations use this type.\n */\nexport type RxStorageDefaultCheckpoint = {\n id: string;\n lwt: number;\n};\n\n\n\nexport type CategorizeBulkWriteRowsOutput = {\n bulkInsertDocs: BulkWriteRowProcessed[];\n bulkUpdateDocs: BulkWriteRowProcessed[];\n /**\n * Ids of all documents that are changed\n * and so their change must be written into the\n * sequences table so that they can be fetched via\n * RxStorageInstance().getChangedDocumentsSince().\n */\n changedDocumentIds: RxDocType[StringKeys][];\n errors: ById>;\n eventBulk: EventBulk>, any>;\n attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n }[];\n attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n }[];\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/rx-storage.interface.d.js.map b/dist/lib/types/rx-storage.interface.d.js.map index 578d51d359f..d6fc4ceb444 100644 --- a/dist/lib/types/rx-storage.interface.d.js.map +++ b/dist/lib/types/rx-storage.interface.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage.interface.d.js","names":[],"sources":["../../../src/types/rx-storage.interface.d.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n RxDocumentData,\n RxDocumentDataById,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from './rx-storage';\nimport type {\n DeepReadonly,\n JsonSchema,\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n Override,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxJsonSchema\n} from './';\nimport type {\n Observable\n} from 'rxjs';\n\n/**\n * RxStorage\n * This is an interface that abstracts the storage engine.\n * This allows us to use RxDB with different engines like PouchDB or LokiJS.\n *\n * Also see\n * @link https://github.com/pubkey/rxdb/issues/1636\n *\n */\n\n\n/**\n * A RxStorage is a module that acts\n * as a factory that can create multiple RxStorageInstance\n * objects.\n *\n * All data inputs and outputs of a StorageInstance must be plain json objects.\n * Do not use Map, Set or anything else that cannot be JSON.stringify-ed.\n * This will ensure that the storage can exchange data\n * when it is a WebWorker or a WASM process or data is send via BroadcastChannel.\n */\nexport interface RxStorage {\n /**\n * name of the storage engine\n * used to detect if plugins do not work so we can throw proper errors.\n */\n readonly name: string;\n\n /**\n * Static functions\n */\n readonly statics: RxStorageStatics;\n\n /**\n * creates a storage instance\n * that can contain the internal database\n * For example the PouchDB instance\n */\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise>;\n}\n\n\n/**\n * User provided mango queries will be filled up by RxDB via normalizeMangoQuery()\n * so we do not have to do many if-field-exist tests in the internals.\n */\nexport type FilledMangoQuery = Override<\nMangoQuery,\n{\n /**\n * The selector is required here.\n */\n selector: MangoQuerySelector;\n\n /**\n * In contrast to the user-provided MangoQuery,\n * the sorting is required here because\n * RxDB has to ensure that the primary key is always\n * part of the sort params.\n */\n sort: MangoQuerySortPart[];\n\n /**\n * In the normalized mango query,\n * the index must always be a string[],\n * never just a string.\n * This makes it easier to use the query because\n * we do not have to do an array check.\n */\n index?: string[];\n\n /**\n * Skip must be set which defaults to 0\n */\n skip: number;\n}\n>;\n\n/**\n * Static functions of the RxStorage.\n * Can be used without creating an instance of any kind.\n * These functions are not directly children of RxStorage because\n * we might need them without having to import the whole storage engine.\n * For example when the Worker plugin is used, the main process only needs the\n * static functions, while the worker process needs the whole storage engine.\n */\nexport type RxStorageStatics = Readonly<{\n /**\n * PouchDB and others have some bugs\n * and behaviors that must be worked around\n * before querying the db.\n *\n * Also some storages do optimizations\n * and other things related to query planning.\n *\n * For performance reason this preparation\n * runs in a single step so it can be cached\n * when the query is used multiple times.\n *\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\n prepareQuery(\n schema: RxJsonSchema>,\n /**\n * a query that can be mutated by the function without side effects.\n */\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery;\n\n /**\n * Returns the sort-comparator,\n * which is able to sort documents in the same way\n * a query over the db would do.\n */\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator;\n\n /**\n * Returns a function\n * that can be used to check if a document\n * matches the query.\n */\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher>;\n\n /**\n * Contains the JsonSchema that matches the checkpoint\n * of this RxStorage.\n * Used in some plugins like the graphql plugin\n * where it is used to create a GraphQL Schema from the checkpoint.\n */\n checkpointSchema: DeepReadonly;\n}>;\n\n\nexport interface RxStorageInstance<\n /**\n * The type of the documents that can be stored in this instance.\n * All documents in an instance must comply to the same schema.\n * Also all documents are RxDocumentData with the meta properties like\n * _deleted or _rev etc.\n */\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType = any\n> {\n readonly databaseName: string;\n /**\n * Returns the internal data that is used by the storage engine.\n * For example the pouchdb instance.\n */\n readonly internals: Readonly;\n readonly options: Readonly;\n /**\n * The schema that defines the documents that are stored in this instance.\n * Notice that the schema must be enhanced with the meta properties like\n * _meta, _rev and _deleted etc. which are added by fillWithDefaultSettings()\n */\n readonly schema: Readonly>>;\n readonly collectionName: string;\n\n /**\n * Writes multiple documents to the storage instance.\n * The write for each single document is atomic, there\n * is no transaction around all documents.\n * The written documents must be the newest revision of that documents data.\n * If the previous document is not the current newest revision, a conflict error\n * must be returned.\n * It must be possible that some document writes succeed\n * and others error. We need this to have a similar behavior as most NoSQL databases.\n */\n bulkWrite(\n documentWrites: BulkWriteRow[],\n /**\n * Context will be used in all\n * changeStream()-events that are emitted as a result\n * of that bulkWrite() operation.\n * Used in plugins so that we can detect that event X\n * comes from operation Y.\n */\n context: string\n ): Promise<\n /**\n * returns the response, split into success and error lists.\n */\n RxStorageBulkWriteResponse\n >;\n\n /**\n * Get Multiple documents by their primary value.\n * This must also return deleted documents.\n */\n findDocumentsById(\n /**\n * List of primary values\n * of the documents to find.\n */\n ids: string[],\n /**\n * If set to true, deleted documents will also be returned.\n */\n withDeleted: boolean\n ): Promise>;\n\n /**\n * Runs a NoSQL 'mango' query over the storage\n * and returns the found documents data.\n * Having all storage instances behave similar\n * is likely the most difficult thing when creating a new\n * rx-storage implementation. Atm we use the pouchdb-find plugin\n * as reference to how NoSQL-queries must work.\n * But the past has shown that pouchdb find can behave wrong,\n * which must be fixed or at least documented.\n */\n query(\n /**\n * Here we get the result of this.prepareQuery()\n * instead of the plain mango query.\n * This makes it easier to have good performance\n * when transformations of the query must be done.\n */\n preparedQuery: PreparedQuery\n ): Promise>;\n\n /**\n * Returns the amount of non-deleted documents\n * that match the given query.\n * Sort, skip and limit of the query must be ignored!\n */\n count(\n preparedQuery: PreparedQuery\n ): Promise;\n\n /**\n * Returns the plain data of a single attachment.\n */\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ): Promise;\n\n /**\n * Returns the current (not the old!) data of all documents that have been changed AFTER the given checkpoint.\n * If the returned array does not reach the limit, it can be assumed that the \"end\" is reached, when paginating over the changes.\n * Also returns a new checkpoint for each document which can be used to continue with the pagination from that change on.\n * Must never return the same document multiple times in the same call operation.\n * This is used by RxDB to known what has changed since X so these docs can be handled by the backup or the replication\n * plugin.\n */\n getChangedDocumentsSince(\n limit: number,\n /**\n * The checkpoint from with to start\n * when the events are sorted in time.\n * If we want to start from the beginning,\n * undefined is used as a checkpoint.\n */\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n }>;\n\n /**\n * Returns an ongoing stream\n * of all changes that happen to the\n * storage instance.\n * Do not forget to unsubscribe.\n *\n * If the RxStorage support multi-instance,\n * and the storage is persistend,\n * then the emitted changes of one RxStorageInstance\n * must be also emitted to other instances with the same databaseName+collectionName.\n * See ./rx-storage-multiinstance.ts\n */\n changeStream(): Observable, CheckpointType>>;\n\n /**\n * Runs a cleanup that removes all tompstones\n * of documents that have _deleted set to true\n * to free up disc space.\n *\n * Returns true if all cleanable documents have been removed.\n * Returns false if there are more documents to be cleaned up,\n * but not all have been purged because that would block the storage for too long.\n */\n cleanup(\n /**\n * The minimum time in milliseconds\n * of how long a document must have been deleted\n * until it is purged by the cleanup.\n */\n minimumDeletedTime: number\n ): Promise<\n /**\n * True if all docs cleaned up,\n * false if there are more docs to clean up\n */\n boolean\n >;\n\n /**\n * Closes the storage instance so it cannot be used\n * anymore and should clear all memory.\n * The returned promise must resolve when everything is cleaned up.\n */\n close(): Promise;\n\n /**\n * Remove the database and\n * deletes all of its data.\n */\n remove(): Promise;\n\n /**\n * Instead of passing the conflict-resolver function\n * into the storage, we have to work with an observable that emits tasks\n * and a resolver that takes resolved tasks.\n * This is needed because the RxStorageInstance might run inside of a Worker\n * other JavaScript process, so we cannot pass plain code.\n */\n conflictResultionTasks(): Observable>;\n resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise;\n}\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-storage.interface.d.js","names":[],"sources":["../../../src/types/rx-storage.interface.d.ts"],"sourcesContent":["import type {\n DeterministicSortComparator,\n QueryMatcher\n} from 'event-reduce-js';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n RxDocumentData,\n RxDocumentDataById,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from './rx-storage';\nimport type {\n DeepReadonly,\n JsonSchema,\n MangoQuery,\n MangoQuerySelector,\n MangoQuerySortPart,\n Override,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxJsonSchema\n} from './';\nimport type {\n Observable\n} from 'rxjs';\n\n/**\n * RxStorage\n * This is an interface that abstracts the storage engine.\n * This allows us to use RxDB with different storage engines.\n *\n * @link https://rxdb.info/rx-storage.html\n * @link https://github.com/pubkey/rxdb/issues/1636\n */\n\n\n/**\n * A RxStorage is a module that acts\n * as a factory that can create multiple RxStorageInstance\n * objects.\n *\n * All data inputs and outputs of a StorageInstance must be plain json objects.\n * Do not use Map, Set or anything else that cannot be JSON.stringify-ed.\n * This will ensure that the storage can exchange data\n * when it is a WebWorker or a WASM process or data is send via BroadcastChannel.\n */\nexport interface RxStorage {\n /**\n * name of the storage engine\n * used to detect if plugins do not work so we can throw proper errors.\n */\n readonly name: string;\n\n /**\n * Static functions\n */\n readonly statics: RxStorageStatics;\n\n /**\n * Creates a storage instance\n * that can contain the NoSQL documents of a collection.\n */\n createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise>;\n}\n\n\n/**\n * User provided mango queries will be filled up by RxDB via normalizeMangoQuery()\n * so we do not have to do many if-field-exist tests in the internals.\n */\nexport type FilledMangoQuery = Override<\nMangoQuery,\n{\n /**\n * The selector is required here.\n */\n selector: MangoQuerySelector;\n\n /**\n * In contrast to the user-provided MangoQuery,\n * the sorting is required here because\n * RxDB has to ensure that the primary key is always\n * part of the sort params.\n */\n sort: MangoQuerySortPart[];\n\n /**\n * In the normalized mango query,\n * the index must always be a string[],\n * never just a string.\n * This makes it easier to use the query because\n * we do not have to do an array check.\n */\n index?: string[];\n\n /**\n * Skip must be set which defaults to 0\n */\n skip: number;\n}\n>;\n\n/**\n * Static functions of the RxStorage.\n * Can be used without creating an instance of any kind.\n * These functions are not directly children of RxStorage because\n * we might need them without having to import the whole storage engine.\n * For example when the Worker plugin is used, the main process only needs the\n * static functions, while the worker process needs the whole storage engine.\n */\nexport type RxStorageStatics = Readonly<{\n /**\n * Storages can have some bugs\n * and behaviors that must be worked around\n * before querying the db.\n *\n * Also some storages do optimizations\n * and other things related to query planning.\n *\n * For performance reason this preparation\n * runs in a single step so it can be cached\n * when the query is used multiple times.\n *\n * @returns a format of the query that can be used with the storage\n * when calling RxStorageInstance().query()\n */\n prepareQuery(\n schema: RxJsonSchema>,\n /**\n * a query that can be mutated by the function without side effects.\n */\n mutateableQuery: FilledMangoQuery\n ): PreparedQuery;\n\n /**\n * Returns the sort-comparator,\n * which is able to sort documents in the same way\n * a query over the db would do.\n */\n getSortComparator(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): DeterministicSortComparator;\n\n /**\n * Returns a function\n * that can be used to check if a document\n * matches the query.\n */\n getQueryMatcher(\n schema: RxJsonSchema>,\n preparedQuery: PreparedQuery\n ): QueryMatcher>;\n\n /**\n * Contains the JsonSchema that matches the checkpoint\n * of this RxStorage.\n * Used in some plugins like the graphql plugin\n * where it is used to create a GraphQL Schema from the checkpoint.\n */\n checkpointSchema: DeepReadonly;\n}>;\n\n\nexport interface RxStorageInstance<\n /**\n * The type of the documents that can be stored in this instance.\n * All documents in an instance must comply to the same schema.\n * Also all documents are RxDocumentData with the meta properties like\n * _deleted or _rev etc.\n */\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType = any\n> {\n readonly databaseName: string;\n /**\n * Returns the internal data that is used by the storage engine.\n */\n readonly internals: Readonly;\n readonly options: Readonly;\n /**\n * The schema that defines the documents that are stored in this instance.\n * Notice that the schema must be enhanced with the meta properties like\n * _meta, _rev and _deleted etc. which are added by fillWithDefaultSettings()\n */\n readonly schema: Readonly>>;\n readonly collectionName: string;\n\n /**\n * Writes multiple documents to the storage instance.\n * The write for each single document is atomic, there\n * is no transaction around all documents.\n * The written documents must be the newest revision of that documents data.\n * If the previous document is not the current newest revision, a conflict error\n * must be returned.\n * It must be possible that some document writes succeed\n * and others error. We need this to have a similar behavior as most NoSQL databases.\n */\n bulkWrite(\n documentWrites: BulkWriteRow[],\n /**\n * Context will be used in all\n * changeStream()-events that are emitted as a result\n * of that bulkWrite() operation.\n * Used in plugins so that we can detect that event X\n * comes from operation Y.\n */\n context: string\n ): Promise<\n /**\n * returns the response, split into success and error lists.\n */\n RxStorageBulkWriteResponse\n >;\n\n /**\n * Get Multiple documents by their primary value.\n * This must also return deleted documents.\n */\n findDocumentsById(\n /**\n * List of primary values\n * of the documents to find.\n */\n ids: string[],\n /**\n * If set to true, deleted documents will also be returned.\n */\n withDeleted: boolean\n ): Promise>;\n\n /**\n * Runs a NoSQL 'mango' query over the storage\n * and returns the found documents data.\n * Having all storage instances behave similar\n * is likely the most difficult thing when creating a new\n * rx-storage implementation.\n */\n query(\n /**\n * Here we get the result of this.prepareQuery()\n * instead of the plain mango query.\n * This makes it easier to have good performance\n * when transformations of the query must be done.\n */\n preparedQuery: PreparedQuery\n ): Promise>;\n\n /**\n * Returns the amount of non-deleted documents\n * that match the given query.\n * Sort, skip and limit of the query must be ignored!\n */\n count(\n preparedQuery: PreparedQuery\n ): Promise;\n\n /**\n * Returns the plain data of a single attachment.\n */\n getAttachmentData(\n documentId: string,\n attachmentId: string\n ): Promise;\n\n /**\n * Returns the current (not the old!) data of all documents that have been changed AFTER the given checkpoint.\n * If the returned array does not reach the limit, it can be assumed that the \"end\" is reached, when paginating over the changes.\n * Also returns a new checkpoint for each document which can be used to continue with the pagination from that change on.\n * Must never return the same document multiple times in the same call operation.\n * This is used by RxDB to known what has changed since X so these docs can be handled by the backup or the replication\n * plugin.\n */\n getChangedDocumentsSince(\n limit: number,\n /**\n * The checkpoint from with to start\n * when the events are sorted in time.\n * If we want to start from the beginning,\n * undefined is used as a checkpoint.\n */\n checkpoint?: CheckpointType\n ): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n }>;\n\n /**\n * Returns an ongoing stream\n * of all changes that happen to the\n * storage instance.\n * Do not forget to unsubscribe.\n *\n * If the RxStorage support multi-instance,\n * and the storage is persistend,\n * then the emitted changes of one RxStorageInstance\n * must be also emitted to other instances with the same databaseName+collectionName.\n * See ./rx-storage-multiinstance.ts\n */\n changeStream(): Observable, CheckpointType>>;\n\n /**\n * Runs a cleanup that removes all tompstones\n * of documents that have _deleted set to true\n * to free up disc space.\n *\n * Returns true if all cleanable documents have been removed.\n * Returns false if there are more documents to be cleaned up,\n * but not all have been purged because that would block the storage for too long.\n */\n cleanup(\n /**\n * The minimum time in milliseconds\n * of how long a document must have been deleted\n * until it is purged by the cleanup.\n */\n minimumDeletedTime: number\n ): Promise<\n /**\n * True if all docs cleaned up,\n * false if there are more docs to clean up\n */\n boolean\n >;\n\n /**\n * Closes the storage instance so it cannot be used\n * anymore and should clear all memory.\n * The returned promise must resolve when everything is cleaned up.\n */\n close(): Promise;\n\n /**\n * Remove the database and\n * deletes all of its data.\n */\n remove(): Promise;\n\n /**\n * Instead of passing the conflict-resolver function\n * into the storage, we have to work with an observable that emits tasks\n * and a resolver that takes resolved tasks.\n * This is needed because the RxStorageInstance might run inside of a Worker\n * other JavaScript process, so we cannot pass plain code.\n */\n conflictResultionTasks(): Observable>;\n resolveConflictResultionTask(taskSolution: RxConflictResultionTaskSolution): Promise;\n}\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/types/util.d.js.map b/dist/lib/types/util.d.js.map index 76b17ac1f6c..5fd311185a7 100644 --- a/dist/lib/types/util.d.js.map +++ b/dist/lib/types/util.d.js.map @@ -1 +1 @@ -{"version":3,"file":"util.d.js","names":[],"sources":["../../../src/types/util.d.ts"],"sourcesContent":["import { RxStorage } from './rx-storage.interface';\n\nexport type MaybePromise = Promise | T;\n\n\nexport type PlainJsonValue = string | number | boolean | PlainSimpleJsonObject | PlainSimpleJsonObject[] | PlainJsonValue[];\nexport type PlainSimpleJsonObject = {\n [k: string]: PlainJsonValue | PlainJsonValue[];\n};\n\n/**\n * @link https://stackoverflow.com/a/49670389/3443137\n */\ntype DeepReadonly =\n T extends (infer R)[] ? DeepReadonlyArray :\n T extends Function ? T :\n T extends object ? DeepReadonlyObject :\n T;\n\ninterface DeepReadonlyArray extends ReadonlyArray> { }\n\ntype DeepReadonlyObject = {\n readonly [P in keyof T]: DeepReadonly;\n};\n\nexport type MaybeReadonly = T | Readonly;\n\n\n/**\n * Opposite of DeepReadonly,\n * makes everything mutable again.\n */\ntype DeepMutable = (\n T extends object\n ? {\n -readonly [K in keyof T]: (\n T[K] extends object\n ? DeepMutable\n : T[K]\n )\n }\n : never\n);\n\n/**\n * Can be used like 'keyof'\n * but only represents the string keys, not the Symbols or numbers.\n * @link https://stackoverflow.com/a/51808262/3443137\n */\nexport type StringKeys = Extract;\n\nexport type AnyKeys = { [P in keyof T]?: T[P] | any };\nexport interface AnyObject {\n [k: string]: any;\n}\n\n/**\n * @link https://dev.to/vborodulin/ts-how-to-override-properties-with-type-intersection-554l\n */\nexport type Override = Omit & T2;\n\n\n\nexport type ById = {\n [id: string]: T;\n};\n\n/**\n * To test a storage, we need these\n * configuration values.\n */\nexport type RxTestStorage = {\n // TODO remove name here, it can be read out already via getStorage().name\n readonly name: string;\n readonly getStorage: () => RxStorage;\n /**\n * Returns a storage that is used in performance tests.\n * For example in a browser it should return the storage with an IndexedDB based adapter,\n * while in node.js it must use the filesystem.\n */\n readonly getPerformanceStorage: () => {\n storage: RxStorage;\n /**\n * A description that describes the storage and setting.\n * For example 'pouchdb-idb'.\n */\n description: string;\n };\n /**\n * True if the storage is able to\n * keep data after an instance is closed and opened again.\n */\n readonly hasPersistence: boolean;\n readonly hasMultiInstance: boolean;\n readonly hasCouchDBReplication: boolean;\n readonly hasAttachments: boolean;\n // true if the storage supports $regex queries, false if not.\n readonly hasRegexSupport: boolean;\n};\n\n\nexport type HashFunction = (input: string) => string;\n\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n stack?: string;\n rxdb?: true;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"util.d.js","names":[],"sources":["../../../src/types/util.d.ts"],"sourcesContent":["import { RxStorage } from './rx-storage.interface';\n\nexport type MaybePromise = Promise | T;\n\n\nexport type PlainJsonValue = string | number | boolean | PlainSimpleJsonObject | PlainSimpleJsonObject[] | PlainJsonValue[];\nexport type PlainSimpleJsonObject = {\n [k: string]: PlainJsonValue | PlainJsonValue[];\n};\n\n/**\n * @link https://stackoverflow.com/a/49670389/3443137\n */\ntype DeepReadonly =\n T extends (infer R)[] ? DeepReadonlyArray :\n T extends Function ? T :\n T extends object ? DeepReadonlyObject :\n T;\n\ninterface DeepReadonlyArray extends ReadonlyArray> { }\n\ntype DeepReadonlyObject = {\n readonly [P in keyof T]: DeepReadonly;\n};\n\nexport type MaybeReadonly = T | Readonly;\n\n\n/**\n * Opposite of DeepReadonly,\n * makes everything mutable again.\n */\ntype DeepMutable = (\n T extends object\n ? {\n -readonly [K in keyof T]: (\n T[K] extends object\n ? DeepMutable\n : T[K]\n )\n }\n : never\n);\n\n/**\n * Can be used like 'keyof'\n * but only represents the string keys, not the Symbols or numbers.\n * @link https://stackoverflow.com/a/51808262/3443137\n */\nexport type StringKeys = Extract;\n\nexport type AnyKeys = { [P in keyof T]?: T[P] | any };\nexport interface AnyObject {\n [k: string]: any;\n}\n\n/**\n * @link https://dev.to/vborodulin/ts-how-to-override-properties-with-type-intersection-554l\n */\nexport type Override = Omit & T2;\n\n\n\nexport type ById = {\n [id: string]: T;\n};\n\n/**\n * To test a storage, we need these\n * configuration values.\n */\nexport type RxTestStorage = {\n // TODO remove name here, it can be read out already via getStorage().name\n readonly name: string;\n readonly getStorage: () => RxStorage;\n /**\n * Returns a storage that is used in performance tests.\n * For example in a browser it should return the storage with an IndexedDB based adapter,\n * while in node.js it must use the filesystem.\n */\n readonly getPerformanceStorage: () => {\n storage: RxStorage;\n /**\n * A description that describes the storage and setting.\n * For example 'dexie-native'.\n */\n description: string;\n };\n /**\n * True if the storage is able to\n * keep data after an instance is closed and opened again.\n */\n readonly hasPersistence: boolean;\n readonly hasMultiInstance: boolean;\n readonly hasCouchDBReplication: boolean;\n readonly hasAttachments: boolean;\n // true if the storage supports $regex queries, false if not.\n readonly hasRegexSupport: boolean;\n};\n\n\nexport type HashFunction = (input: string) => string;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/lib/util.js b/dist/lib/util.js deleted file mode 100644 index 1d6a7c2dc80..00000000000 --- a/dist/lib/util.js +++ /dev/null @@ -1,847 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RX_META_LWT_MINIMUM = exports.RXJS_SHARE_REPLAY_DEFAULTS = exports.RANDOM_STRING = exports.PROMISE_RESOLVE_VOID = exports.PROMISE_RESOLVE_TRUE = exports.PROMISE_RESOLVE_NULL = exports.PROMISE_RESOLVE_FALSE = void 0; -exports.adapterObject = adapterObject; -exports.areRxDocumentArraysEqual = areRxDocumentArraysEqual; -exports.arrayBufferToBase64 = arrayBufferToBase64; -exports.arrayFilterNotEmpty = arrayFilterNotEmpty; -exports.b64DecodeUnicode = b64DecodeUnicode; -exports.b64EncodeUnicode = b64EncodeUnicode; -exports.batchArray = batchArray; -exports.clone = exports.blobBufferUtil = void 0; -exports.createRevision = createRevision; -exports.deepFreeze = deepFreeze; -exports.defaultHashFunction = defaultHashFunction; -exports.ensureInteger = ensureInteger; -exports.ensureNotFalsy = ensureNotFalsy; -exports.errorToPlainJson = errorToPlainJson; -exports.fastUnsecureHash = fastUnsecureHash; -exports.firstPropertyNameOfObject = firstPropertyNameOfObject; -exports.firstPropertyValueOfObject = firstPropertyValueOfObject; -exports.flatClone = flatClone; -exports.flattenObject = flattenObject; -exports.getDefaultRevision = getDefaultRevision; -exports.getDefaultRxDocumentMeta = getDefaultRxDocumentMeta; -exports.getFromMapOrThrow = getFromMapOrThrow; -exports.getFromObjectOrThrow = getFromObjectOrThrow; -exports.getHeightOfRevision = getHeightOfRevision; -exports.getSortDocumentsByLastWriteTimeComparator = getSortDocumentsByLastWriteTimeComparator; -exports.isFolderPath = isFolderPath; -exports.isMaybeReadonlyArray = isMaybeReadonlyArray; -exports.lastOfArray = lastOfArray; -exports.nextTick = nextTick; -exports.now = now; -exports.objectPathMonad = objectPathMonad; -exports.overwriteGetterForCaching = overwriteGetterForCaching; -exports.parseRevision = parseRevision; -exports.pluginMissing = pluginMissing; -exports.promiseSeries = promiseSeries; -exports.promiseWait = promiseWait; -exports.randomCouchString = randomCouchString; -exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; -exports.requestIdleCallbackIfAvailable = requestIdleCallbackIfAvailable; -exports.requestIdlePromise = requestIdlePromise; -exports.runXTimes = runXTimes; -exports.shuffleArray = shuffleArray; -exports.sortDocumentsByLastWriteTime = sortDocumentsByLastWriteTime; -exports.sortObject = sortObject; -exports.stringifyFilter = stringifyFilter; -exports.toPromise = toPromise; -exports.trimDots = trimDots; -exports.ucfirst = ucfirst; -var _jsBase = require("js-base64"); -/** - * Returns an error that indicates that a plugin is missing - * We do not throw a RxError because this should not be handled - * programmatically but by using the correct import - */ -function pluginMissing(pluginKey) { - var keyParts = pluginKey.split('-'); - var pluginName = 'RxDB'; - keyParts.forEach(function (part) { - pluginName += ucfirst(part); - }); - pluginName += 'Plugin'; - return new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { " + pluginName + " } from 'rxdb/plugins/" + pluginKey + "';\n addRxPlugin(" + pluginName + ");\n "); -} - -/** - * This is a very fast hash method - * but it is not cryptographically secure. - * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int). - * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery - * @return a string as hash-result - */ -function fastUnsecureHash(inputString, -// used to test the polyfill -doNotUseTextEncoder) { - var hashValue = 0, - i, - chr, - len; - - /** - * For better performance we first transform all - * chars into their ascii numbers at once. - * - * This is what makes the murmurhash implementation such fast. - * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4 - */ - var encoded; - - /** - * All modern browsers support the TextEncoder - * @link https://caniuse.com/textencoder - * But to make RxDB work in other JavaScript runtimes, - * like when using it in flutter or QuickJS, we need to - * make it work even when there is no TextEncoder. - */ - if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) { - encoded = new TextEncoder().encode(inputString); - } else { - encoded = []; - for (var j = 0; j < inputString.length; j++) { - encoded.push(inputString.charCodeAt(j)); - } - } - for (i = 0, len = inputString.length; i < len; i++) { - chr = encoded[i]; - hashValue = (hashValue << 5) - hashValue + chr; - hashValue |= 0; // Convert to 32bit integer - } - - if (hashValue < 0) { - hashValue = hashValue * -1; - } - - /** - * To make the output smaller - * but still have it to represent the same value, - * we use the biggest radix of 36 instead of just - * transforming it into a hex string. - */ - return hashValue.toString(36); -} - -/** - * Default hash method used to create revision hashes - * that do not have to be cryptographically secure. - * IMPORTANT: Changing the default hashing method - * requires a BREAKING change! - */ -function defaultHashFunction(input) { - return fastUnsecureHash(input); -} - -/** - * Returns the current unix time in milliseconds (with two decmials!) - * Because the accuracy of getTime() in javascript is bad, - * and we cannot rely on performance.now() on all platforms, - * this method implements a way to never return the same value twice. - * This ensures that when now() is called often, we do not loose the information - * about which call came first and which came after. - * - * We had to move from having no decimals, to having two decimal - * because it turned out that some storages are such fast that - * calling this method too often would return 'the future'. - */ -var _lastNow = 0; -/** - * Returns the current time in milliseconds, - * also ensures to not return the same value twice. - */ -function now() { - var ret = new Date().getTime(); - ret = ret + 0.01; - if (ret <= _lastNow) { - ret = _lastNow + 0.01; - } - - /** - * Strip the returned number to max two decimals. - * In theory we would not need this but - * in practice JavaScript has no such good number precision - * so rounding errors could add another decimal place. - */ - var twoDecimals = parseFloat(ret.toFixed(2)); - _lastNow = twoDecimals; - return twoDecimals; -} - -/** - * returns a promise that resolves on the next tick - */ -function nextTick() { - return new Promise(function (res) { - return setTimeout(res, 0); - }); -} -function promiseWait() { - var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - return new Promise(function (res) { - return setTimeout(res, ms); - }); -} -function toPromise(maybePromise) { - if (maybePromise && typeof maybePromise.then === 'function') { - // is promise - return maybePromise; - } else { - return Promise.resolve(maybePromise); - } -} -var PROMISE_RESOLVE_TRUE = Promise.resolve(true); -exports.PROMISE_RESOLVE_TRUE = PROMISE_RESOLVE_TRUE; -var PROMISE_RESOLVE_FALSE = Promise.resolve(false); -exports.PROMISE_RESOLVE_FALSE = PROMISE_RESOLVE_FALSE; -var PROMISE_RESOLVE_NULL = Promise.resolve(null); -exports.PROMISE_RESOLVE_NULL = PROMISE_RESOLVE_NULL; -var PROMISE_RESOLVE_VOID = Promise.resolve(); -exports.PROMISE_RESOLVE_VOID = PROMISE_RESOLVE_VOID; -function requestIdlePromise() { - var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - if (typeof window === 'object' && window['requestIdleCallback']) { - return new Promise(function (res) { - return window['requestIdleCallback'](res, { - timeout: timeout - }); - }); - } else { - return promiseWait(0); - } -} - -/** - * like Promise.all() but runs in series instead of parallel - * @link https://github.com/egoist/promise.series/blob/master/index.js - * @param tasks array with functions that return a promise - */ -function promiseSeries(tasks, initial) { - return tasks.reduce(function (current, next) { - return current.then(next); - }, Promise.resolve(initial)); -} - -/** - * run the callback if requestIdleCallback available - * do nothing if not - * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback - */ -function requestIdleCallbackIfAvailable(fun) { - if (typeof window === 'object' && window['requestIdleCallback']) window['requestIdleCallback'](fun); -} - -/** - * uppercase first char - */ -function ucfirst(str) { - str += ''; - var f = str.charAt(0).toUpperCase(); - return f + str.substr(1); -} - -/** - * removes trailing and ending dots from the string - */ -function trimDots(str) { - // start - while (str.charAt(0) === '.') str = str.substr(1); - - // end - while (str.slice(-1) === '.') str = str.slice(0, -1); - return str; -} -function runXTimes(xTimes, fn) { - new Array(xTimes).fill(0).forEach(function (_v, idx) { - return fn(idx); - }); -} -function ensureNotFalsy(obj) { - if (!obj) { - throw new Error('ensureNotFalsy() is falsy'); - } - return obj; -} -function ensureInteger(obj) { - if (!Number.isInteger(obj)) { - throw new Error('ensureInteger() is falsy'); - } - return obj; -} - -/** - * deep-sort an object so its attributes are in lexical order. - * Also sorts the arrays inside of the object if no-array-sort not set - */ -function sortObject(obj) { - var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (!obj) return obj; // do not sort null, false or undefined - - // array - if (!noArraySort && Array.isArray(obj)) { - return obj.sort(function (a, b) { - if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b); - if (typeof a === 'object') return 1;else return -1; - }).map(function (i) { - return sortObject(i, noArraySort); - }); - } - - // object - // array is also of type object - if (typeof obj === 'object' && !Array.isArray(obj)) { - if (obj instanceof RegExp) { - return obj; - } - var out = {}; - Object.keys(obj).sort(function (a, b) { - return a.localeCompare(b); - }).forEach(function (key) { - out[key] = sortObject(obj[key], noArraySort); - }); - return out; - } - - // everything else - return obj; -} - -/** - * used to JSON.stringify() objects that contain a regex - * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs! - */ -function stringifyFilter(key, value) { - if (value instanceof RegExp) { - return value.toString(); - } - return value; -} - -/** - * get a random string which can be used with couchdb - * @link http://stackoverflow.com/a/1349426/3443137 - */ -function randomCouchString() { - var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; - var text = ''; - var possible = 'abcdefghijklmnopqrstuvwxyz'; - for (var i = 0; i < length; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } - return text; -} - -/** - * A random string that is never inside of any storage - */ -var RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX'; -exports.RANDOM_STRING = RANDOM_STRING; -function lastOfArray(ar) { - return ar[ar.length - 1]; -} - -/** - * shuffle the given array - */ -function shuffleArray(arr) { - return arr.sort(function () { - return Math.random() - 0.5; - }); -} - -/** - * Split array with items into smaller arrays with items - * @link https://stackoverflow.com/a/7273794/3443137 - */ -function batchArray(array, batchSize) { - array = array.slice(0); - var ret = []; - while (array.length) { - var batch = array.splice(0, batchSize); - ret.push(batch); - } - return ret; -} - -/** - * @link https://stackoverflow.com/a/15996017 - */ -function removeOneFromArrayIfMatches(ar, condition) { - ar = ar.slice(); - var i = ar.length; - var done = false; - while (i-- && !done) { - if (condition(ar[i])) { - done = true; - ar.splice(i, 1); - } - } - return ar; -} - -/** - * transforms the given adapter into a pouch-compatible object - */ -function adapterObject(adapter) { - var adapterObj = { - db: adapter - }; - if (typeof adapter === 'string') { - adapterObj = { - adapter: adapter, - db: undefined - }; - } - return adapterObj; -} - -/** - * Deep clone a plain json object. - * Does not work with recursive stuff - * or non-plain-json. - * IMPORANT: Performance of this is very important, - * do not change it without running performance tests! - * - * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts - */ -function deepClone(src) { - if (!src) { - return src; - } - if (src === null || typeof src !== 'object') { - return src; - } - if (Array.isArray(src)) { - var ret = new Array(src.length); - var i = ret.length; - while (i--) { - ret[i] = deepClone(src[i]); - } - return ret; - } - var dest = {}; - // eslint-disable-next-line guard-for-in - for (var key in src) { - // TODO we should not be required to deep clone RegEx objects, - // this must be fixed in RxDB. - if (src[key] instanceof RegExp) { - dest[key] = src[key]; - } else { - dest[key] = deepClone(src[key]); - } - } - return dest; -} -var clone = deepClone; - -/** - * does a flat copy on the objects, - * is about 3 times faster then using deepClone - * @link https://jsperf.com/object-rest-spread-vs-clone/2 - */ -exports.clone = clone; -function flatClone(obj) { - return Object.assign({}, obj); -} - -/** - * @link https://stackoverflow.com/a/11509718/3443137 - */ -function firstPropertyNameOfObject(obj) { - return Object.keys(obj)[0]; -} -function firstPropertyValueOfObject(obj) { - var key = Object.keys(obj)[0]; - return obj[key]; -} - -/** - * returns a flattened object - * @link https://gist.github.com/penguinboy/762197 - */ -function flattenObject(ob) { - var toReturn = {}; - for (var i in ob) { - if (!ob.hasOwnProperty(i)) continue; - if (typeof ob[i] === 'object') { - var flatObject = flattenObject(ob[i]); - for (var _x in flatObject) { - if (!flatObject.hasOwnProperty(_x)) continue; - toReturn[i + '.' + _x] = flatObject[_x]; - } - } else { - toReturn[i] = ob[i]; - } - } - return toReturn; -} -function parseRevision(revision) { - var split = revision.split('-'); - return { - height: parseInt(split[0], 10), - hash: split[1] - }; -} -function getHeightOfRevision(revision) { - return parseRevision(revision).height; -} - -/** - * Creates the next write revision for a given document. - */ -function createRevision(hashFunction, docData, previousDocData) { - var previousRevision = previousDocData ? previousDocData._rev : null; - var previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0; - var newRevisionHeight = previousRevisionHeigth + 1; - var docWithoutRev = Object.assign({}, docData, { - _rev: undefined, - _rev_tree: undefined, - /** - * All _meta properties MUST NOT be part of the - * revision hash. - * Plugins might temporarily store data in the _meta - * field and strip it away when the document is replicated - * or written to another storage. - */ - _meta: undefined - }); - - /** - * The revision height must be part of the hash - * as the last parameter of the document data. - * This is required to ensure we never ever create - * two different document states that have the same revision - * hash. Even writing the exact same document data - * must have to result in a different hash so that - * the replication can known if the state just looks equal - * or if it is really exactly the equal state in data and time. - */ - delete docWithoutRev._rev; - docWithoutRev._rev = previousDocData ? newRevisionHeight : 1; - var diggestString = JSON.stringify(docWithoutRev); - var revisionHash = hashFunction(diggestString); - return newRevisionHeight + '-' + revisionHash; -} - -/** - * Faster way to check the equalness of document lists - * compared to doing a deep-equal. - * Here we only check the ids and revisions. - */ -function areRxDocumentArraysEqual(primaryPath, ar1, ar2) { - if (ar1.length !== ar2.length) { - return false; - } - var i = 0; - var len = ar1.length; - while (i < len) { - var row1 = ar1[i]; - var row2 = ar2[i]; - i++; - if (row1._rev !== row2._rev || row1[primaryPath] !== row2[primaryPath]) { - return false; - } - } - return true; -} - -/** - * overwrites the getter with the actual value - * Mostly used for caching stuff on the first run - */ -function overwriteGetterForCaching(obj, getterName, value) { - Object.defineProperty(obj, getterName, { - get: function get() { - return value; - } - }); - return value; -} - -/** - * returns true if the given name is likely a folder path - */ -function isFolderPath(name) { - // do not check, if foldername is given - if (name.includes('/') || - // unix - name.includes('\\') // windows - ) { - return true; - } else { - return false; - } -} -function getFromMapOrThrow(map, key) { - var val = map.get(key); - if (typeof val === 'undefined') { - throw new Error('missing value from map ' + key); - } - return val; -} -function getFromObjectOrThrow(obj, key) { - var val = obj[key]; - if (!val) { - throw new Error('missing value from object ' + key); - } - return val; -} - -/** - * returns true if the supplied argument is either an Array or a Readonly> - */ -function isMaybeReadonlyArray(x) { - // While this looks strange, it's a workaround for an issue in TypeScript: - // https://github.com/microsoft/TypeScript/issues/17002 - // - // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array, - // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`. - // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while - // still performing runtime type inspection. - return Array.isArray(x); -} - -/** - * Use this in array.filter() to remove all empty slots - * and have the correct typings afterwards. - * @link https://stackoverflow.com/a/46700791/3443137 - */ -function arrayFilterNotEmpty(value) { - if (value === null || value === undefined) { - return false; - } - return true; -} - -/** - * NO! We cannot just use btoa() and atob() - * because they do not work correctly with binary data. - * @link https://stackoverflow.com/q/30106476/3443137 - */ - -/** - * atob() and btoa() do not work well with non ascii chars, - * so we have to use these helper methods instead. - * @link https://stackoverflow.com/a/30106551/3443137 - */ -// Encoding UTF8 -> base64 -function b64EncodeUnicode(str) { - return (0, _jsBase.encode)(str); -} - -// Decoding base64 -> UTF8 -function b64DecodeUnicode(str) { - return (0, _jsBase.decode)(str); -} - -/** - * @link https://stackoverflow.com/a/9458996/3443137 - */ -function arrayBufferToBase64(buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - var len = bytes.byteLength; - for (var i = 0; i < len; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} - -/** - * This is an abstraction over the Blob/Buffer data structure. - * We need this because it behaves different in different JavaScript runtimes. - * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support - * the Blob data structure which is also supported by the browsers. - */ -var blobBufferUtil = { - /** - * depending if we are on node or browser, - * we have to use Buffer(node) or Blob(browser) - */ - createBlobBuffer: function createBlobBuffer(data, type) { - var blobBuffer = new Blob([data], { - type: type - }); - return blobBuffer; - }, - /** - * depending if we are on node or browser, - * we have to use Buffer(node) or Blob(browser) - */ - createBlobBufferFromBase64: function createBlobBufferFromBase64(base64String, type) { - try { - return Promise.resolve(fetch("data:" + type + ";base64," + base64String)).then(function (base64Response) { - return Promise.resolve(base64Response.blob()); - }); - } catch (e) { - return Promise.reject(e); - } - }, - isBlobBuffer: function isBlobBuffer(data) { - if (data instanceof Blob || typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) { - return true; - } else { - return false; - } - }, - toString: function toString(blobBuffer) { - /** - * in the electron-renderer we have a typed array insteaf of a blob - * so we have to transform it. - * @link https://github.com/pubkey/rxdb/issues/1371 - */ - var blobBufferType = Object.prototype.toString.call(blobBuffer); - if (blobBufferType === '[object Uint8Array]') { - blobBuffer = new Blob([blobBuffer]); - } - if (typeof blobBuffer === 'string') { - return Promise.resolve(blobBuffer); - } - return blobBuffer.text(); - }, - toBase64String: function toBase64String(blobBuffer) { - try { - if (typeof blobBuffer === 'string') { - return Promise.resolve(blobBuffer); - } - - /** - * in the electron-renderer we have a typed array insteaf of a blob - * so we have to transform it. - * @link https://github.com/pubkey/rxdb/issues/1371 - */ - var blobBufferType = Object.prototype.toString.call(blobBuffer); - if (blobBufferType === '[object Uint8Array]') { - blobBuffer = new Blob([blobBuffer]); - } - return Promise.resolve(fetch(URL.createObjectURL(blobBuffer)).then(function (res) { - return res.arrayBuffer(); - })).then(arrayBufferToBase64); - } catch (e) { - return Promise.reject(e); - } - }, - size: function size(blobBuffer) { - return blobBuffer.size; - } -}; - -/** - * Using shareReplay() without settings will not unsubscribe - * if there are no more subscribers. - * So we use these defaults. - * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95 - */ -exports.blobBufferUtil = blobBufferUtil; -var RXJS_SHARE_REPLAY_DEFAULTS = { - bufferSize: 1, - refCount: true -}; - -/** - * We use 1 as minimum so that the value is never falsy. - * This const is used in several places because querying - * with a value lower then the minimum could give false results. - */ -exports.RXJS_SHARE_REPLAY_DEFAULTS = RXJS_SHARE_REPLAY_DEFAULTS; -var RX_META_LWT_MINIMUM = 1; -exports.RX_META_LWT_MINIMUM = RX_META_LWT_MINIMUM; -function getDefaultRxDocumentMeta() { - return { - /** - * Set this to 1 to not waste performance - * while calling new Date().. - * The storage wrappers will anyway update - * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage() - */ - lwt: RX_META_LWT_MINIMUM - }; -} - -/** - * Returns a revision that is not valid. - * Use this to have correct typings - * while the storage wrapper anyway will overwrite the revision. - */ -function getDefaultRevision() { - /** - * Use a non-valid revision format, - * to ensure that the RxStorage will throw - * when the revision is not replaced downstream. - */ - return ''; -} -function getSortDocumentsByLastWriteTimeComparator(primaryPath) { - return function (a, b) { - if (a._meta.lwt === b._meta.lwt) { - if (b[primaryPath] < a[primaryPath]) { - return 1; - } else { - return -1; - } - } else { - return a._meta.lwt - b._meta.lwt; - } - }; -} -function sortDocumentsByLastWriteTime(primaryPath, docs) { - return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath)); -} - -/** - * To get specific nested path values from objects, - * RxDB normally uses the 'object-path' npm module. - * But when performance is really relevant, this is not fast enough. - * Instead we use a monad that can prepare some stuff up front - * and we can re-use the generated function. - */ - -function objectPathMonad(objectPath) { - var split = objectPath.split('.'); - - /** - * Performance shortcut, - * if no nested path is used, - * directly return the field of the object. - */ - if (split.length === 1) { - return function (obj) { - return obj[objectPath]; - }; - } - return function (obj) { - var currentVal = obj; - var t = 0; - while (t < split.length) { - var subPath = split[t]; - currentVal = currentVal[subPath]; - if (typeof currentVal === 'undefined') { - return currentVal; - } - t++; - } - return currentVal; - }; -} -function deepFreeze(o) { - Object.freeze(o); - Object.getOwnPropertyNames(o).forEach(function (prop) { - if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop])) { - deepFreeze(o[prop]); - } - }); - return o; -} -function errorToPlainJson(err) { - var ret = { - name: err.name, - message: err.message, - stack: err.stack, - rxdb: err.rxdb - }; - return ret; -} -//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/dist/lib/util.js.map b/dist/lib/util.js.map deleted file mode 100644 index 9c6331f5db6..00000000000 --- a/dist/lib/util.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"util.js","names":["pluginMissing","pluginKey","keyParts","split","pluginName","forEach","part","ucfirst","Error","fastUnsecureHash","inputString","doNotUseTextEncoder","hashValue","i","chr","len","encoded","TextEncoder","encode","j","length","push","charCodeAt","toString","defaultHashFunction","input","_lastNow","now","ret","Date","getTime","twoDecimals","parseFloat","toFixed","nextTick","Promise","res","setTimeout","promiseWait","ms","toPromise","maybePromise","then","resolve","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_NULL","PROMISE_RESOLVE_VOID","requestIdlePromise","timeout","window","promiseSeries","tasks","initial","reduce","current","next","requestIdleCallbackIfAvailable","fun","str","f","charAt","toUpperCase","substr","trimDots","slice","runXTimes","xTimes","fn","Array","fill","_v","idx","ensureNotFalsy","obj","ensureInteger","Number","isInteger","sortObject","noArraySort","isArray","sort","a","b","localeCompare","map","RegExp","out","Object","keys","key","stringifyFilter","value","randomCouchString","text","possible","Math","floor","random","RANDOM_STRING","lastOfArray","ar","shuffleArray","arr","batchArray","array","batchSize","batch","splice","removeOneFromArrayIfMatches","condition","done","adapterObject","adapter","adapterObj","db","undefined","deepClone","src","dest","clone","flatClone","assign","firstPropertyNameOfObject","firstPropertyValueOfObject","flattenObject","ob","toReturn","hasOwnProperty","flatObject","x","parseRevision","revision","height","parseInt","hash","getHeightOfRevision","createRevision","hashFunction","docData","previousDocData","previousRevision","_rev","previousRevisionHeigth","newRevisionHeight","docWithoutRev","_rev_tree","_meta","diggestString","JSON","stringify","revisionHash","areRxDocumentArraysEqual","primaryPath","ar1","ar2","row1","row2","overwriteGetterForCaching","getterName","defineProperty","get","isFolderPath","name","includes","getFromMapOrThrow","val","getFromObjectOrThrow","isMaybeReadonlyArray","arrayFilterNotEmpty","b64EncodeUnicode","b64DecodeUnicode","decode","arrayBufferToBase64","buffer","binary","bytes","Uint8Array","byteLength","String","fromCharCode","btoa","blobBufferUtil","createBlobBuffer","data","type","blobBuffer","Blob","createBlobBufferFromBase64","base64String","fetch","base64Response","blob","isBlobBuffer","Buffer","isBuffer","blobBufferType","prototype","call","toBase64String","URL","createObjectURL","arrayBuffer","size","RXJS_SHARE_REPLAY_DEFAULTS","bufferSize","refCount","RX_META_LWT_MINIMUM","getDefaultRxDocumentMeta","lwt","getDefaultRevision","getSortDocumentsByLastWriteTimeComparator","sortDocumentsByLastWriteTime","docs","objectPathMonad","objectPath","currentVal","t","subPath","deepFreeze","o","freeze","getOwnPropertyNames","prop","isFrozen","errorToPlainJson","err","message","stack","rxdb"],"sources":["../../src/util.ts"],"sourcesContent":["import type {\n BlobBuffer,\n DeepReadonlyObject,\n HashFunction,\n MaybeReadonly,\n PlainJsonError,\n RxDocumentData,\n RxDocumentMeta,\n RxDocumentWriteData,\n RxError,\n RxTypeError,\n StringKeys\n} from './types';\n\n/**\n * Returns an error that indicates that a plugin is missing\n * We do not throw a RxError because this should not be handled\n * programmatically but by using the correct import\n */\nexport function pluginMissing(\n pluginKey: string\n): Error {\n const keyParts = pluginKey.split('-');\n let pluginName = 'RxDB';\n keyParts.forEach(part => {\n pluginName += ucfirst(part);\n });\n pluginName += 'Plugin';\n return new Error(\n `You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { ${pluginName} } from 'rxdb/plugins/${pluginKey}';\n addRxPlugin(${pluginName});\n `\n );\n}\n\n/**\n * This is a very fast hash method\n * but it is not cryptographically secure.\n * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int).\n * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery\n * @return a string as hash-result\n */\nexport function fastUnsecureHash(\n inputString: string,\n // used to test the polyfill\n doNotUseTextEncoder?: boolean\n): string {\n let hashValue = 0,\n i, chr, len;\n\n /**\n * For better performance we first transform all\n * chars into their ascii numbers at once.\n *\n * This is what makes the murmurhash implementation such fast.\n * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4\n */\n let encoded: Uint8Array | number[];\n\n /**\n * All modern browsers support the TextEncoder\n * @link https://caniuse.com/textencoder\n * But to make RxDB work in other JavaScript runtimes,\n * like when using it in flutter or QuickJS, we need to\n * make it work even when there is no TextEncoder.\n */\n if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) {\n encoded = new TextEncoder().encode(inputString);\n } else {\n encoded = [];\n for (let j = 0; j < inputString.length; j++) {\n encoded.push(inputString.charCodeAt(j));\n }\n }\n\n for (i = 0, len = inputString.length; i < len; i++) {\n chr = encoded[i];\n hashValue = ((hashValue << 5) - hashValue) + chr;\n hashValue |= 0; // Convert to 32bit integer\n }\n if (hashValue < 0) {\n hashValue = hashValue * -1;\n }\n\n /**\n * To make the output smaller\n * but still have it to represent the same value,\n * we use the biggest radix of 36 instead of just\n * transforming it into a hex string.\n */\n return hashValue.toString(36);\n}\n\n\n/**\n * Default hash method used to create revision hashes\n * that do not have to be cryptographically secure.\n * IMPORTANT: Changing the default hashing method\n * requires a BREAKING change!\n */\nexport function defaultHashFunction(input: string): string {\n return fastUnsecureHash(input);\n}\n\n/**\n * Returns the current unix time in milliseconds (with two decmials!)\n * Because the accuracy of getTime() in javascript is bad,\n * and we cannot rely on performance.now() on all platforms,\n * this method implements a way to never return the same value twice.\n * This ensures that when now() is called often, we do not loose the information\n * about which call came first and which came after.\n *\n * We had to move from having no decimals, to having two decimal\n * because it turned out that some storages are such fast that\n * calling this method too often would return 'the future'.\n */\nlet _lastNow: number = 0;\n/**\n * Returns the current time in milliseconds,\n * also ensures to not return the same value twice.\n */\nexport function now(): number {\n let ret = new Date().getTime();\n ret = ret + 0.01;\n if (ret <= _lastNow) {\n ret = _lastNow + 0.01;\n }\n\n /**\n * Strip the returned number to max two decimals.\n * In theory we would not need this but\n * in practice JavaScript has no such good number precision\n * so rounding errors could add another decimal place.\n */\n const twoDecimals = parseFloat(ret.toFixed(2));\n\n _lastNow = twoDecimals;\n return twoDecimals;\n}\n\n/**\n * returns a promise that resolves on the next tick\n */\nexport function nextTick(): Promise {\n return new Promise(res => setTimeout(res, 0));\n}\n\nexport function promiseWait(ms: number = 0): Promise {\n return new Promise(res => setTimeout(res, ms));\n}\n\nexport function toPromise(maybePromise: Promise | T): Promise {\n if (maybePromise && typeof (maybePromise as any).then === 'function') {\n // is promise\n return maybePromise as any;\n } else {\n return Promise.resolve(maybePromise);\n }\n}\n\nexport const PROMISE_RESOLVE_TRUE: Promise = Promise.resolve(true);\nexport const PROMISE_RESOLVE_FALSE: Promise = Promise.resolve(false);\nexport const PROMISE_RESOLVE_NULL: Promise = Promise.resolve(null);\nexport const PROMISE_RESOLVE_VOID: Promise = Promise.resolve();\n\nexport function requestIdlePromise(timeout: number | null = null) {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) {\n return new Promise(\n res => (window as any)['requestIdleCallback'](res, {\n timeout\n })\n );\n } else {\n return promiseWait(0);\n }\n}\n\n\n/**\n * like Promise.all() but runs in series instead of parallel\n * @link https://github.com/egoist/promise.series/blob/master/index.js\n * @param tasks array with functions that return a promise\n */\nexport function promiseSeries(\n tasks: Function[],\n initial?: any\n): Promise {\n return tasks\n .reduce(\n (current, next) => (current as any).then(next),\n Promise.resolve(initial)\n );\n}\n\n/**\n * run the callback if requestIdleCallback available\n * do nothing if not\n * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback\n */\nexport function requestIdleCallbackIfAvailable(fun: Function): void {\n if (\n typeof window === 'object' &&\n (window as any)['requestIdleCallback']\n ) (window as any)['requestIdleCallback'](fun);\n}\n\n/**\n * uppercase first char\n */\nexport function ucfirst(str: string): string {\n str += '';\n const f = str.charAt(0)\n .toUpperCase();\n return f + str.substr(1);\n}\n\n/**\n * removes trailing and ending dots from the string\n */\nexport function trimDots(str: string): string {\n // start\n while (str.charAt(0) === '.')\n str = str.substr(1);\n\n // end\n while (str.slice(-1) === '.')\n str = str.slice(0, -1);\n\n return str;\n}\n\n\nexport function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null): T {\n if (!obj) {\n throw new Error('ensureNotFalsy() is falsy');\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n/**\n * deep-sort an object so its attributes are in lexical order.\n * Also sorts the arrays inside of the object if no-array-sort not set\n */\nexport function sortObject(obj: any, noArraySort = false): any {\n if (!obj) return obj; // do not sort null, false or undefined\n\n // array\n if (!noArraySort && Array.isArray(obj)) {\n return obj\n .sort((a, b) => {\n if (typeof a === 'string' && typeof b === 'string')\n return a.localeCompare(b);\n\n if (typeof a === 'object') return 1;\n else return -1;\n })\n .map(i => sortObject(i, noArraySort));\n }\n\n // object\n // array is also of type object\n if (typeof obj === 'object' && !Array.isArray(obj)) {\n if (obj instanceof RegExp) {\n return obj;\n }\n\n const out: any = {};\n Object.keys(obj)\n .sort((a, b) => a.localeCompare(b))\n .forEach(key => {\n out[key] = sortObject(obj[key], noArraySort);\n });\n return out;\n }\n\n // everything else\n return obj;\n}\n\n\n/**\n * used to JSON.stringify() objects that contain a regex\n * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs!\n */\nexport function stringifyFilter(key: string, value: any) {\n if (value instanceof RegExp) {\n return value.toString();\n }\n return value;\n}\n\n/**\n * get a random string which can be used with couchdb\n * @link http://stackoverflow.com/a/1349426/3443137\n */\nexport function randomCouchString(length: number = 10): string {\n let text = '';\n const possible = 'abcdefghijklmnopqrstuvwxyz';\n\n for (let i = 0; i < length; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n }\n\n return text;\n}\n\n/**\n * A random string that is never inside of any storage\n */\nexport const RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX';\n\n\nexport function lastOfArray(ar: T[]): T | undefined {\n return ar[ar.length - 1];\n}\n\n/**\n * shuffle the given array\n */\nexport function shuffleArray(arr: T[]): T[] {\n return arr.sort(() => (Math.random() - 0.5));\n}\n\n/**\n * Split array with items into smaller arrays with items\n * @link https://stackoverflow.com/a/7273794/3443137\n */\nexport function batchArray(array: T[], batchSize: number): T[][] {\n array = array.slice(0);\n const ret: T[][] = [];\n while (array.length) {\n const batch = array.splice(0, batchSize);\n ret.push(batch);\n }\n return ret;\n}\n\n\n/**\n * @link https://stackoverflow.com/a/15996017\n */\nexport function removeOneFromArrayIfMatches(ar: T[], condition: (x: T) => boolean): T[] {\n ar = ar.slice();\n let i = ar.length;\n let done = false;\n while (i-- && !done) {\n if (condition(ar[i])) {\n done = true;\n ar.splice(i, 1);\n }\n }\n return ar;\n}\n\n\n/**\n * transforms the given adapter into a pouch-compatible object\n */\nexport function adapterObject(adapter: any): any {\n let adapterObj: any = {\n db: adapter\n };\n if (typeof adapter === 'string') {\n adapterObj = {\n adapter,\n db: undefined,\n };\n }\n return adapterObj;\n}\n\n\n/**\n * Deep clone a plain json object.\n * Does not work with recursive stuff\n * or non-plain-json.\n * IMPORANT: Performance of this is very important,\n * do not change it without running performance tests!\n *\n * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts\n */\nfunction deepClone(src: T | DeepReadonlyObject): T {\n if (!src) {\n return src;\n }\n if (src === null || typeof (src) !== 'object') {\n return src;\n }\n if (Array.isArray(src)) {\n const ret = new Array(src.length);\n let i = ret.length;\n while (i--) {\n ret[i] = deepClone(src[i]);\n }\n return ret as any;\n }\n const dest: any = {};\n // eslint-disable-next-line guard-for-in\n for (const key in src) {\n // TODO we should not be required to deep clone RegEx objects,\n // this must be fixed in RxDB.\n if (src[key] instanceof RegExp) {\n dest[key] = src[key];\n } else {\n dest[key] = deepClone(src[key]);\n }\n }\n return dest;\n}\nexport const clone = deepClone;\n\n/**\n * does a flat copy on the objects,\n * is about 3 times faster then using deepClone\n * @link https://jsperf.com/object-rest-spread-vs-clone/2\n */\nexport function flatClone(obj: T | DeepReadonlyObject): T {\n return Object.assign({}, obj) as any;\n}\n\n/**\n * @link https://stackoverflow.com/a/11509718/3443137\n */\nexport function firstPropertyNameOfObject(obj: any): string {\n return Object.keys(obj)[0];\n}\nexport function firstPropertyValueOfObject(obj: { [k: string]: T; }): T {\n const key = Object.keys(obj)[0];\n return obj[key];\n}\n\n/**\n * returns a flattened object\n * @link https://gist.github.com/penguinboy/762197\n */\nexport function flattenObject(ob: any) {\n const toReturn: any = {};\n\n for (const i in ob) {\n if (!ob.hasOwnProperty(i)) continue;\n\n if ((typeof ob[i]) === 'object') {\n const flatObject = flattenObject(ob[i]);\n for (const x in flatObject) {\n if (!flatObject.hasOwnProperty(x)) continue;\n\n toReturn[i + '.' + x] = flatObject[x];\n }\n } else {\n toReturn[i] = ob[i];\n }\n }\n return toReturn;\n}\n\n\nexport function parseRevision(revision: string): { height: number; hash: string; } {\n const split = revision.split('-');\n return {\n height: parseInt(split[0], 10),\n hash: split[1]\n };\n}\n\nexport function getHeightOfRevision(revision: string): number {\n return parseRevision(revision).height;\n}\n\n/**\n * Creates the next write revision for a given document.\n */\nexport function createRevision(\n hashFunction: HashFunction,\n docData: RxDocumentWriteData & {\n /**\n * Passing a revision is optional here,\n * because it is anyway not needed to calculate\n * the new revision.\n */\n _rev?: string;\n },\n previousDocData?: RxDocumentData\n): string {\n\n const previousRevision = previousDocData ? previousDocData._rev : null;\n const previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0;\n const newRevisionHeight = previousRevisionHeigth + 1;\n\n\n const docWithoutRev: any = Object.assign({}, docData, {\n _rev: undefined,\n _rev_tree: undefined,\n /**\n * All _meta properties MUST NOT be part of the\n * revision hash.\n * Plugins might temporarily store data in the _meta\n * field and strip it away when the document is replicated\n * or written to another storage.\n */\n _meta: undefined\n });\n\n /**\n * The revision height must be part of the hash\n * as the last parameter of the document data.\n * This is required to ensure we never ever create\n * two different document states that have the same revision\n * hash. Even writing the exact same document data\n * must have to result in a different hash so that\n * the replication can known if the state just looks equal\n * or if it is really exactly the equal state in data and time.\n */\n delete docWithoutRev._rev;\n docWithoutRev._rev = previousDocData ? newRevisionHeight : 1;\n\n const diggestString = JSON.stringify(docWithoutRev);\n\n const revisionHash = hashFunction(diggestString);\n return newRevisionHeight + '-' + revisionHash;\n}\n\n\n/**\n * Faster way to check the equalness of document lists\n * compared to doing a deep-equal.\n * Here we only check the ids and revisions.\n */\nexport function areRxDocumentArraysEqual(\n primaryPath: StringKeys>,\n ar1: RxDocumentData[],\n ar2: RxDocumentData[]\n): boolean {\n if (ar1.length !== ar2.length) {\n return false;\n }\n let i = 0;\n const len = ar1.length;\n while (i < len) {\n const row1 = ar1[i];\n const row2 = ar2[i];\n i++;\n\n if (\n row1._rev !== row2._rev ||\n row1[primaryPath] !== row2[primaryPath]\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * overwrites the getter with the actual value\n * Mostly used for caching stuff on the first run\n */\nexport function overwriteGetterForCaching(\n obj: any,\n getterName: string,\n value: ValueType\n): ValueType {\n Object.defineProperty(obj, getterName, {\n get: function () {\n return value;\n }\n });\n return value;\n}\n\n/**\n * returns true if the given name is likely a folder path\n */\nexport function isFolderPath(name: string) {\n // do not check, if foldername is given\n if (\n name.includes('/') || // unix\n name.includes('\\\\') // windows\n ) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function getFromMapOrThrow(map: Map | WeakMap, key: K): V {\n const val = map.get(key);\n if (typeof val === 'undefined') {\n throw new Error('missing value from map ' + key);\n }\n return val;\n}\n\nexport function getFromObjectOrThrow(\n obj: { [k: string]: V; },\n key: string\n): V {\n const val = obj[key];\n if (!val) {\n throw new Error('missing value from object ' + key);\n }\n return val;\n}\n\n/**\n * returns true if the supplied argument is either an Array or a Readonly>\n */\nexport function isMaybeReadonlyArray(x: any): x is MaybeReadonly {\n // While this looks strange, it's a workaround for an issue in TypeScript:\n // https://github.com/microsoft/TypeScript/issues/17002\n //\n // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array,\n // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`.\n // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while\n // still performing runtime type inspection.\n return Array.isArray(x);\n}\n\n\n/**\n * Use this in array.filter() to remove all empty slots\n * and have the correct typings afterwards.\n * @link https://stackoverflow.com/a/46700791/3443137\n */\nexport function arrayFilterNotEmpty(value: TValue | null | undefined): value is TValue {\n if (value === null || value === undefined) {\n return false;\n }\n return true;\n}\n\n\n/**\n * NO! We cannot just use btoa() and atob()\n * because they do not work correctly with binary data.\n * @link https://stackoverflow.com/q/30106476/3443137\n */\nimport { encode, decode } from 'js-base64';\n\n/**\n * atob() and btoa() do not work well with non ascii chars,\n * so we have to use these helper methods instead.\n * @link https://stackoverflow.com/a/30106551/3443137\n */\n// Encoding UTF8 -> base64\nexport function b64EncodeUnicode(str: string) {\n return encode(str);\n}\n\n// Decoding base64 -> UTF8\nexport function b64DecodeUnicode(str: string) {\n return decode(str);\n}\n\n/**\n * @link https://stackoverflow.com/a/9458996/3443137\n */\nexport function arrayBufferToBase64(buffer: ArrayBuffer) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n const len = bytes.byteLength;\n for (let i = 0; i < len; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n\n/**\n * This is an abstraction over the Blob/Buffer data structure.\n * We need this because it behaves different in different JavaScript runtimes.\n * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support\n * the Blob data structure which is also supported by the browsers.\n */\nexport const blobBufferUtil = {\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n createBlobBuffer(\n data: string,\n type: string\n ): BlobBuffer {\n const blobBuffer = new Blob([data], {\n type\n });\n return blobBuffer;\n },\n /**\n * depending if we are on node or browser,\n * we have to use Buffer(node) or Blob(browser)\n */\n async createBlobBufferFromBase64(\n base64String: string,\n type: string\n ): Promise {\n const base64Response = await fetch(`data:${type};base64,${base64String}`);\n const blob = await base64Response.blob();\n return blob;\n\n },\n isBlobBuffer(data: any): boolean {\n if (data instanceof Blob || (typeof Buffer !== 'undefined' && Buffer.isBuffer(data))) {\n return true;\n } else {\n return false;\n }\n },\n toString(blobBuffer: BlobBuffer | string): Promise {\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n if (typeof blobBuffer === 'string') {\n return Promise.resolve(blobBuffer);\n }\n\n return (blobBuffer as Blob).text();\n },\n async toBase64String(blobBuffer: BlobBuffer | string): Promise {\n if (typeof blobBuffer === 'string') {\n return blobBuffer;\n }\n\n /**\n * in the electron-renderer we have a typed array insteaf of a blob\n * so we have to transform it.\n * @link https://github.com/pubkey/rxdb/issues/1371\n */\n const blobBufferType = Object.prototype.toString.call(blobBuffer);\n if (blobBufferType === '[object Uint8Array]') {\n blobBuffer = new Blob([blobBuffer]);\n }\n\n const arrayBuffer = await fetch(URL.createObjectURL(blobBuffer as Blob)).then(res => res.arrayBuffer());\n return arrayBufferToBase64(arrayBuffer);\n },\n size(blobBuffer: BlobBuffer): number {\n return (blobBuffer as Blob).size;\n }\n};\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n\n/**\n * We use 1 as minimum so that the value is never falsy.\n * This const is used in several places because querying\n * with a value lower then the minimum could give false results.\n */\nexport const RX_META_LWT_MINIMUM = 1;\n\nexport function getDefaultRxDocumentMeta(): RxDocumentMeta {\n return {\n /**\n * Set this to 1 to not waste performance\n * while calling new Date()..\n * The storage wrappers will anyway update\n * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage()\n */\n lwt: RX_META_LWT_MINIMUM\n };\n}\n\n/**\n * Returns a revision that is not valid.\n * Use this to have correct typings\n * while the storage wrapper anyway will overwrite the revision.\n */\nexport function getDefaultRevision(): string {\n /**\n * Use a non-valid revision format,\n * to ensure that the RxStorage will throw\n * when the revision is not replaced downstream.\n */\n return '';\n}\n\n\nexport function getSortDocumentsByLastWriteTimeComparator(primaryPath: string) {\n return (a: RxDocumentData, b: RxDocumentData) => {\n if (a._meta.lwt === b._meta.lwt) {\n if ((b as any)[primaryPath] < (a as any)[primaryPath]) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return a._meta.lwt - b._meta.lwt;\n }\n };\n}\nexport function sortDocumentsByLastWriteTime(\n primaryPath: string,\n docs: RxDocumentData[]\n): RxDocumentData[] {\n return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath));\n}\n\n\n\n/**\n * To get specific nested path values from objects,\n * RxDB normally uses the 'object-path' npm module.\n * But when performance is really relevant, this is not fast enough.\n * Instead we use a monad that can prepare some stuff up front\n * and we can re-use the generated function.\n */\nexport type ObjectPathMonadFunction = (obj: T) => R;\nexport function objectPathMonad(objectPath: string): ObjectPathMonadFunction {\n const split = objectPath.split('.');\n\n /**\n * Performance shortcut,\n * if no nested path is used,\n * directly return the field of the object.\n */\n if (split.length === 1) {\n return (obj: T) => (obj as any)[objectPath];\n }\n\n\n return (obj: T) => {\n let currentVal: any = obj;\n let t = 0;\n while (t < split.length) {\n const subPath = split[t];\n currentVal = currentVal[subPath];\n if (typeof currentVal === 'undefined') {\n return currentVal;\n }\n t++;\n }\n return currentVal;\n };\n}\n\n\nexport function deepFreeze(o: T): T {\n Object.freeze(o);\n Object.getOwnPropertyNames(o).forEach(function (prop) {\n if (\n (o as any).hasOwnProperty(prop)\n &&\n (o as any)[prop] !== null\n &&\n (\n typeof (o as any)[prop] === 'object'\n ||\n typeof (o as any)[prop] === 'function'\n )\n &&\n !Object.isFrozen((o as any)[prop])\n ) {\n deepFreeze((o as any)[prop]);\n }\n });\n return o;\n}\n\n\n\nexport function errorToPlainJson(err: Error | TypeError | RxError | RxTypeError): PlainJsonError {\n const ret: PlainJsonError = {\n name: err.name,\n message: err.message,\n stack: err.stack,\n rxdb: (err as any).rxdb\n };\n return ret;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4oBA;AA9nBA;AACA;AACA;AACA;AACA;AACO,SAASA,aAAa,CACzBC,SAAiB,EACZ;EACL,IAAMC,QAAQ,GAAGD,SAAS,CAACE,KAAK,CAAC,GAAG,CAAC;EACrC,IAAIC,UAAU,GAAG,MAAM;EACvBF,QAAQ,CAACG,OAAO,CAAC,UAAAC,IAAI,EAAI;IACrBF,UAAU,IAAIG,OAAO,CAACD,IAAI,CAAC;EAC/B,CAAC,CAAC;EACFF,UAAU,IAAI,QAAQ;EACtB,OAAO,IAAII,KAAK,iLAGGJ,UAAU,8BAAyBH,SAAS,oCACzCG,UAAU,kBAE/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AQ,CAAEJ,CAAC,CAASG,IAAI,CAAC,CAAC,EACpC;MACEJ,UAAU,CAAEC,CAAC,CAASG,IAAI,CAAC,CAAC;IAChC;EACJ,CAAC,CAAC;EACF,OAAOH,CAAC;AACZ;AAIO,SAASK,gBAAgB,CAACC,GAA8C,EAAkB;EAC7F,IAAMtM,GAAmB,GAAG;IACxBuI,IAAI,EAAE+D,GAAG,CAAC/D,IAAI;IACdgE,OAAO,EAAED,GAAG,CAACC,OAAO;IACpBC,KAAK,EAAEF,GAAG,CAACE,KAAK;IAChBC,IAAI,EAAGH,GAAG,CAASG;EACvB,CAAC;EACD,OAAOzM,GAAG;AACd"} \ No newline at end of file diff --git a/dist/rxdb.browserify.js b/dist/rxdb.browserify.js index 574c64e081e..5a516d81710 100644 --- a/dist/rxdb.browserify.js +++ b/dist/rxdb.browserify.js @@ -3,7 +3,6 @@ require("@babel/polyfill"); var RxDB = _interopRequireWildcard(require("./index.js")); -var RxDbPouchPlugin = _interopRequireWildcard(require("./plugins/pouchdb/index.js")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** @@ -12,11 +11,9 @@ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && * and used via window.RxDB */ -RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-idb')); -RxDbPouchPlugin.addPouchPlugin(require('pouchdb-adapter-http')); window['RxDB'] = RxDB; -},{"./index.js":7,"./plugins/pouchdb/index.js":13,"@babel/polyfill":45,"pouchdb-adapter-http":424,"pouchdb-adapter-idb":425}],2:[function(require,module,exports){ +},{"./index.js":8,"@babel/polyfill":50}],2:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -130,7 +127,7 @@ function createChangeEventBuffer(collection) { return new ChangeEventBuffer(collection); } -},{"rxjs/operators":683}],3:[function(require,module,exports){ +},{"rxjs/operators":648}],3:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -142,7 +139,7 @@ exports.getStartIndexStringFromLowerBound = getStartIndexStringFromLowerBound; exports.getStartIndexStringFromUpperBound = getStartIndexStringFromUpperBound; exports.getStringLengthOfIndexNumber = getStringLengthOfIndexNumber; var _rxSchemaHelper = require("./rx-schema-helper"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _queryPlanner = require("./query-planner"); /** * For some RxStorage implementations, @@ -183,7 +180,7 @@ function getIndexableStringMonad(schema, index) { schemaPart: schemaPart, parsedLengths: parsedLengths, hasComplexPath: fieldName.includes('.'), - getValueFn: (0, _util.objectPathMonad)(fieldName) + getValueFn: (0, _utils.objectPathMonad)(fieldName) }; }); var ret = function ret(docData) { @@ -201,7 +198,7 @@ function getIndexableStringMonad(schema, index) { var boolToStr = fieldValue ? '1' : '0'; str += boolToStr; } else { - var parsedLengths = (0, _util.ensureNotFalsy)(props.parsedLengths); + var parsedLengths = (0, _utils.ensureNotFalsy)(props.parsedLengths); if (!fieldValue) { fieldValue = 0; } @@ -246,7 +243,7 @@ function getStartIndexStringFromLowerBound(schema, index, lowerBound, inclusiveS var type = schemaPart.type; switch (type) { case 'string': - var maxLength = (0, _util.ensureNotFalsy)(schemaPart.maxLength); + var maxLength = (0, _utils.ensureNotFalsy)(schemaPart.maxLength); if (typeof bound === 'string') { str += bound.padEnd(maxLength, ' '); } else { @@ -286,7 +283,7 @@ function getStartIndexStringFromUpperBound(schema, index, upperBound, inclusiveE var type = schemaPart.type; switch (type) { case 'string': - var maxLength = (0, _util.ensureNotFalsy)(schemaPart.maxLength); + var maxLength = (0, _utils.ensureNotFalsy)(schemaPart.maxLength); if (typeof bound === 'string') { str += bound.padEnd(maxLength, inclusiveEnd ? _queryPlanner.INDEX_MAX : ' '); } else { @@ -318,33 +315,137 @@ function getStartIndexStringFromUpperBound(schema, index, upperBound, inclusiveE return str; } -},{"./query-planner":20,"./rx-schema-helper":38,"./util":44}],4:[function(require,module,exports){ +},{"./plugins/utils":12,"./query-planner":26,"./rx-schema-helper":44}],4:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.DocCache = void 0; -var DocCache = /*#__PURE__*/function () { - function DocCache() { - this._map = new Map(); - this._map = new Map(); +exports.DocumentCache = void 0; +var _utils = require("./plugins/utils"); +var _overwritable = require("./overwritable"); +var _rxChangeEvent = require("./rx-change-event"); +/** + * The DocumentCache stores RxDocument objects + * by their primary key and revision. + * This is useful on client side applications where + * it is not known how much memory can be used, so + * we de-duplicate RxDocument states to save memory. + * To not fill up the memory with old document states, the DocumentCache + * only contains weak references to the RxDocuments themself. + * @link https://caniuse.com/?search=weakref + */ +var DocumentCache = /*#__PURE__*/function () { + /** + * Some JavaScript runtimes like QuickJS, + * so not have a FinalizationRegistry or WeakRef. + * Therefore we need a workaround which might waste a lot of memory, + * but at least works. + */ + + function DocumentCache(primaryPath, changes$, + /** + * A method that can create a RxDocument by the given document data. + */ + documentCreator) { + var _this = this; + this.cacheItemByDocId = new Map(); + this.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (docMeta) { + var docId = docMeta.docId; + var cacheItem = _this.cacheItemByDocId.get(docId); + if (cacheItem) { + cacheItem.documentByRevisionHeight["delete"](docMeta.revisionHeight); + if (cacheItem.documentByRevisionHeight.size === 0) { + /** + * No state of the document is cached anymore, + * so we can clean up. + */ + _this.cacheItemByDocId["delete"](docId); + } + } + }) : undefined; + this.primaryPath = primaryPath; + this.changes$ = changes$; + this.documentCreator = documentCreator; + changes$.subscribe(function (changeEvent) { + var docId = changeEvent.documentId; + var cacheItem = _this.cacheItemByDocId.get(docId); + if (cacheItem) { + var documentData = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + cacheItem.latestDoc = documentData; + } + }); } - var _proto = DocCache.prototype; - _proto.get = function get(id) { - return this._map.get(id); - }; - _proto.set = function set(id, obj) { - return this._map.set(id, obj); + + /** + * Get the RxDocument from the cache + * and create a new one if not exits before. + */ + var _proto = DocumentCache.prototype; + _proto.getCachedRxDocument = function getCachedRxDocument(docData) { + var docId = docData[this.primaryPath]; + var revisionHeight = (0, _utils.parseRevision)(docData._rev).height; + var cacheItem = (0, _utils.getFromMapOrFill)(this.cacheItemByDocId, docId, function () { + return getNewCacheItem(docData); + }); + var cachedRxDocumentWeakRef = cacheItem.documentByRevisionHeight.get(revisionHeight); + var cachedRxDocument = cachedRxDocumentWeakRef ? cachedRxDocumentWeakRef.deref() : undefined; + if (!cachedRxDocument) { + docData = _overwritable.overwritable.deepFreezeWhenDevMode(docData); + cachedRxDocument = this.documentCreator(docData); + cacheItem.documentByRevisionHeight.set(revisionHeight, createWeakRefWithFallback(cachedRxDocument)); + if (this.registry) { + this.registry.register(cachedRxDocument, { + docId: docId, + revisionHeight: revisionHeight + }); + } + } + return cachedRxDocument; + } + + /** + * Throws if not exists + */; + _proto.getLatestDocumentData = function getLatestDocumentData(docId) { + var cacheItem = (0, _utils.getFromMapOrThrow)(this.cacheItemByDocId, docId); + return cacheItem.latestDoc; }; - _proto["delete"] = function _delete(id) { - return this._map["delete"](id); + _proto.getLatestDocumentDataIfExists = function getLatestDocumentDataIfExists(docId) { + var cacheItem = this.cacheItemByDocId.get(docId); + if (cacheItem) { + return cacheItem.latestDoc; + } }; - return DocCache; + return DocumentCache; }(); -exports.DocCache = DocCache; +exports.DocumentCache = DocumentCache; +function getNewCacheItem(docData) { + return { + documentByRevisionHeight: new Map(), + latestDoc: docData + }; +} + +/** + * Fallback for JavaScript runtimes that do not support WeakRef. + * The fallback will keep the items in cache forever, + * but at least works. + */ +var HAS_WEAK_REF = typeof WeakRef === 'function'; +function createWeakRefWithFallback(obj) { + if (HAS_WEAK_REF) { + return new WeakRef(obj); + } else { + return { + deref: function deref() { + return obj; + } + }; + } +} -},{}],5:[function(require,module,exports){ +},{"./overwritable":9,"./plugins/utils":12,"./rx-change-event":34}],5:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -356,7 +457,7 @@ exports.getQueryParams = getQueryParams; exports.getSortFieldsOfQuery = getSortFieldsOfQuery; var _eventReduceJs = require("event-reduce-js"); var _rxChangeEvent = require("./rx-change-event"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxQueryHelper = require("./rx-query-helper"); function getSortFieldsOfQuery(primaryKey, query) { if (!query.sort || query.sort.length === 0) { @@ -373,7 +474,7 @@ function getQueryParams(rxQuery) { if (!RXQUERY_QUERY_PARAMS_CACHE.has(rxQuery)) { var collection = rxQuery.collection; var preparedQuery = rxQuery.getPreparedQuery(); - var normalizedMangoQuery = (0, _rxQueryHelper.normalizeMangoQuery)(collection.storageInstance.schema, (0, _util.clone)(rxQuery.mangoQuery)); + var normalizedMangoQuery = (0, _rxQueryHelper.normalizeMangoQuery)(collection.storageInstance.schema, (0, _utils.clone)(rxQuery.mangoQuery)); var primaryKey = collection.schema.primaryPath; /** @@ -425,12 +526,12 @@ function calculateNewResults(rxQuery, rxChangeEvents) { }; } var queryParams = getQueryParams(rxQuery); - var previousResults = (0, _util.ensureNotFalsy)(rxQuery._result).docsData.slice(0); - var previousResultsMap = (0, _util.ensureNotFalsy)(rxQuery._result).docsDataMap; + var previousResults = (0, _utils.ensureNotFalsy)(rxQuery._result).docsData.slice(0); + var previousResultsMap = (0, _utils.ensureNotFalsy)(rxQuery._result).docsDataMap; var changed = false; var eventReduceEvents = rxChangeEvents.map(function (cE) { return (0, _rxChangeEvent.rxChangeEventToEventReduceChangeEvent)(cE); - }).filter(_util.arrayFilterNotEmpty); + }).filter(_utils.arrayFilterNotEmpty); var foundNonOptimizeable = eventReduceEvents.find(function (eventReduceEvent) { var stateResolveFunctionInput = { queryParams: queryParams, @@ -460,7 +561,7 @@ function calculateNewResults(rxQuery, rxChangeEvents) { } } -},{"./rx-change-event":28,"./rx-query-helper":36,"./util":44,"event-reduce-js":406}],6:[function(require,module,exports){ +},{"./plugins/utils":12,"./rx-change-event":34,"./rx-query-helper":42,"event-reduce-js":412}],6:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -582,6 +683,282 @@ function _clearHook(type, fun) { },{}],7:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.IncrementalWriteQueue = void 0; +exports.findNewestOfDocumentStates = findNewestOfDocumentStates; +exports.modifierFromPublicToInternal = modifierFromPublicToInternal; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _rxError = require("./rx-error"); +var _utils = require("./plugins/utils"); +function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/** + * The incremental write queue + * batches up all incremental writes to a collection + * so that performance can be improved by: + * - Running only one write even when there are multiple modifications to the same document. + * - Run all writes ins a single bulkWrite() call even when there are writes to many documents. + */ +var IncrementalWriteQueue = /*#__PURE__*/function () { + function IncrementalWriteQueue(storageInstance, primaryPath, + // can be used to run hooks etc. + preWrite, postWrite) { + this.queueByDocId = new Map(); + this.isRunning = false; + this.storageInstance = storageInstance; + this.primaryPath = primaryPath; + this.preWrite = preWrite; + this.postWrite = postWrite; + } + var _proto = IncrementalWriteQueue.prototype; + _proto.addWrite = function addWrite(lastKnownDocumentState, modifier) { + var _this = this; + var docId = lastKnownDocumentState[this.primaryPath]; + var ar = (0, _utils.getFromMapOrFill)(this.queueByDocId, docId, function () { + return []; + }); + var ret = new Promise(function (resolve, reject) { + var item = { + lastKnownDocumentState: lastKnownDocumentState, + modifier: modifier, + resolve: resolve, + reject: reject + }; + (0, _utils.ensureNotFalsy)(ar).push(item); + _this.triggerRun(); + }); + return ret; + }; + _proto.triggerRun = /*#__PURE__*/function () { + var _triggerRun = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var _this2 = this; + var writeRows, itemsById, writeResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(this.isRunning === true || this.queueByDocId.size === 0)) { + _context2.next = 2; + break; + } + return _context2.abrupt("return"); + case 2: + this.isRunning = true; + writeRows = []; + /** + * 'take over' so that while the async functions runs, + * new incremental updates could be added from the outside. + */ + itemsById = this.queueByDocId; + this.queueByDocId = new Map(); + _context2.next = 8; + return Promise.all(Array.from(itemsById.entries()).map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_ref) { + var _docId, items, oldData, newData, _iterator, _step, item; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _docId = _ref[0], items = _ref[1]; + oldData = findNewestOfDocumentStates(items.map(function (i) { + return i.lastKnownDocumentState; + })); + newData = oldData; + _iterator = _createForOfIteratorHelperLoose(items); + case 4: + if ((_step = _iterator()).done) { + _context.next = 19; + break; + } + item = _step.value; + _context.prev = 6; + _context.next = 9; + return item.modifier( + /** + * We have to clone() each time because the modifier + * might throw while it already changed some properties + * of the document. + */ + (0, _utils.clone)(newData)); + case 9: + newData = _context.sent; + _context.next = 17; + break; + case 12: + _context.prev = 12; + _context.t0 = _context["catch"](6); + item.reject(_context.t0); + item.reject = function () {}; + item.resolve = function () {}; + case 17: + _context.next = 4; + break; + case 19: + _context.prev = 19; + _context.next = 22; + return _this2.preWrite(newData, oldData); + case 22: + _context.next = 28; + break; + case 24: + _context.prev = 24; + _context.t1 = _context["catch"](19); + /** + * If the before-hooks fail, + * we reject all of the writes because it is + * not possible to determine which one is to blame. + */ + items.forEach(function (item) { + return item.reject(_context.t1); + }); + return _context.abrupt("return"); + case 28: + writeRows.push({ + previous: oldData, + document: newData + }); + case 29: + case "end": + return _context.stop(); + } + }, _callee, null, [[6, 12], [19, 24]]); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); + case 8: + if (!(writeRows.length > 0)) { + _context2.next = 14; + break; + } + _context2.next = 11; + return this.storageInstance.bulkWrite(writeRows, 'incremental-write'); + case 11: + _context2.t0 = _context2.sent; + _context2.next = 15; + break; + case 14: + _context2.t0 = { + error: {}, + success: {} + }; + case 15: + writeResult = _context2.t0; + _context2.next = 18; + return Promise.all(Array.from(Object.entries(writeResult.success)).map(function (_ref3) { + var docId = _ref3[0], + result = _ref3[1]; + _this2.postWrite(result); + var items = (0, _utils.getFromMapOrThrow)(itemsById, docId); + items.forEach(function (item) { + return item.resolve(result); + }); + })); + case 18: + // process errors + Array.from(Object.entries(writeResult.error)).forEach(function (_ref4) { + var docId = _ref4[0], + error = _ref4[1]; + var items = (0, _utils.getFromMapOrThrow)(itemsById, docId); + var isConflict = (0, _rxError.isBulkWriteConflictError)(error); + if (isConflict) { + // had conflict -> retry afterwards + var ar = (0, _utils.getFromMapOrFill)(_this2.queueByDocId, docId, function () { + return []; + }); + /** + * Add the items back to this.queueByDocId + * by maintaining the original order. + */ + items.reverse().forEach(function (item) { + item.lastKnownDocumentState = (0, _utils.ensureNotFalsy)(isConflict.documentInDb); + (0, _utils.ensureNotFalsy)(ar).unshift(item); + }); + } else { + // other error -> must be thrown + var rxError = (0, _rxError.rxStorageWriteErrorToRxError)(error); + items.forEach(function (item) { + return item.reject(rxError); + }); + } + }); + this.isRunning = false; + + /** + * Always trigger another run + * because in between there might be new items + * been added to the queue. + */ + return _context2.abrupt("return", this.triggerRun()); + case 21: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function triggerRun() { + return _triggerRun.apply(this, arguments); + } + return triggerRun; + }(); + return IncrementalWriteQueue; +}(); +exports.IncrementalWriteQueue = IncrementalWriteQueue; +function modifierFromPublicToInternal(publicModifier) { + var ret = /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(docData) { + var withoutMeta, modified, reattachedMeta; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + withoutMeta = (0, _utils.stripMetaDataFromDocument)(docData); + withoutMeta._deleted = docData._deleted; + _context3.next = 4; + return publicModifier(withoutMeta); + case 4: + modified = _context3.sent; + reattachedMeta = Object.assign({}, modified, { + _meta: docData._meta, + _attachments: docData._attachments, + _rev: docData._rev, + _deleted: typeof modified._deleted !== 'undefined' ? modified._deleted : docData._deleted + }); + if (typeof reattachedMeta._deleted === 'undefined') { + reattachedMeta._deleted = false; + } + return _context3.abrupt("return", reattachedMeta); + case 8: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return function ret(_x2) { + return _ref5.apply(this, arguments); + }; + }(); + return ret; +} +function findNewestOfDocumentStates(docs) { + var newest = docs[0]; + var newestRevisionHeight = (0, _utils.parseRevision)(newest._rev).height; + docs.forEach(function (doc) { + var height = (0, _utils.parseRevision)(doc._rev).height; + if (height > newestRevisionHeight) { + newest = doc; + newestRevisionHeight = height; + } + }); + return newest; +} + +},{"./plugins/utils":12,"./rx-error":41,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66}],8:[function(require,module,exports){ +"use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); @@ -887,33 +1264,33 @@ Object.keys(_pluginHelpers).forEach(function (key) { } }); }); -var _hooks = require("./hooks"); -var _queryCache = require("./query-cache"); -Object.keys(_queryCache).forEach(function (key) { +var _utils = require("./plugins/utils"); +Object.keys(_utils).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _queryCache[key]) return; + if (key in exports && exports[key] === _utils[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { - return _queryCache[key]; + return _utils[key]; } }); }); -var _util = require("./util"); -Object.keys(_util).forEach(function (key) { +var _hooks = require("./hooks"); +var _queryCache = require("./query-cache"); +Object.keys(_queryCache).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _util[key]) return; + if (key in exports && exports[key] === _queryCache[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { - return _util[key]; + return _queryCache[key]; } }); }); -},{"./custom-index":3,"./hooks":6,"./overwritable":8,"./plugin":10,"./plugin-helpers":9,"./query-cache":19,"./query-planner":20,"./replication-protocol/index":25,"./rx-change-event":28,"./rx-collection":30,"./rx-collection-helper":29,"./rx-database":32,"./rx-database-internal-store":31,"./rx-document":34,"./rx-document-prototype-merge":33,"./rx-error":35,"./rx-query":37,"./rx-query-helper":36,"./rx-schema":39,"./rx-schema-helper":38,"./rx-storage-helper":40,"./rx-storage-multiinstance":41,"./types/modules/mocha.parallel.d":42,"./types/modules/modifiyjs.d":43,"./util":44}],8:[function(require,module,exports){ +},{"./custom-index":3,"./hooks":6,"./overwritable":9,"./plugin":11,"./plugin-helpers":10,"./plugins/utils":12,"./query-cache":25,"./query-planner":26,"./replication-protocol/index":31,"./rx-change-event":34,"./rx-collection":36,"./rx-collection-helper":35,"./rx-database":38,"./rx-database-internal-store":37,"./rx-document":40,"./rx-document-prototype-merge":39,"./rx-error":41,"./rx-query":43,"./rx-query-helper":42,"./rx-schema":45,"./rx-schema-helper":44,"./rx-storage-helper":46,"./rx-storage-multiinstance":47,"./types/modules/mocha.parallel.d":48,"./types/modules/modifiyjs.d":49}],9:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -954,16 +1331,20 @@ var overwritable = { }; exports.overwritable = overwritable; -},{}],9:[function(require,module,exports){ +},{}],10:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapRxStorageInstance = wrapRxStorageInstance; exports.wrappedValidateStorageFactory = wrappedValidateStorageFactory; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _rxSchemaHelper = require("./rx-schema-helper"); +var _utils = require("./plugins/utils"); /** * cache the validators by the schema-hash * so we can reuse them when multiple collections have the same schema @@ -987,47 +1368,83 @@ validatorKey) { if (!VALIDATOR_CACHE_BY_VALIDATOR_KEY.has(validatorKey)) { VALIDATOR_CACHE_BY_VALIDATOR_KEY.set(validatorKey, new Map()); } - var VALIDATOR_CACHE = (0, _util.getFromMapOrThrow)(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey); + var VALIDATOR_CACHE = (0, _utils.getFromMapOrThrow)(VALIDATOR_CACHE_BY_VALIDATOR_KEY, validatorKey); function initValidator(schema) { - var hash = (0, _util.fastUnsecureHash)(JSON.stringify(schema)); + var hash = (0, _utils.fastUnsecureHash)(JSON.stringify(schema)); if (!VALIDATOR_CACHE.has(hash)) { var validator = getValidator(schema); VALIDATOR_CACHE.set(hash, validator); return validator; } - return (0, _util.getFromMapOrThrow)(VALIDATOR_CACHE, hash); + return (0, _utils.getFromMapOrThrow)(VALIDATOR_CACHE, hash); } return function (args) { return Object.assign({}, args.storage, { - createStorageInstance: function createStorageInstance(params) { - try { - return Promise.resolve(args.storage.createStorageInstance(params)).then(function (instance) { - /** - * Lazy initialize the validator - * to save initial page load performance. - * Some libraries take really long to initialize the validator - * from the schema. - */ - var validatorCached; - (0, _util.requestIdleCallbackIfAvailable)(function () { - return validatorCached = initValidator(params.schema); - }); - var oldBulkWrite = instance.bulkWrite.bind(instance); - instance.bulkWrite = function (documentWrites, context) { - if (!validatorCached) { - validatorCached = initValidator(params.schema); - } - documentWrites.forEach(function (row) { - validatorCached(row.document); - }); - return oldBulkWrite(documentWrites, context); - }; - return instance; - }); - } catch (e) { - return Promise.reject(e); + createStorageInstance: function () { + var _createStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(params) { + var instance, primaryPath, validatorCached, oldBulkWrite; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return args.storage.createStorageInstance(params); + case 2: + instance = _context.sent; + primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(params.schema.primaryKey); + /** + * Lazy initialize the validator + * to save initial page load performance. + * Some libraries take really long to initialize the validator + * from the schema. + */ + (0, _utils.requestIdleCallbackIfAvailable)(function () { + return validatorCached = initValidator(params.schema); + }); + oldBulkWrite = instance.bulkWrite.bind(instance); + instance.bulkWrite = function (documentWrites, context) { + if (!validatorCached) { + validatorCached = initValidator(params.schema); + } + var errors = []; + var continueWrites = []; + documentWrites.forEach(function (row) { + var documentId = row.document[primaryPath]; + var validationErrors = validatorCached(row.document); + if (validationErrors.length > 0) { + errors.push({ + status: 422, + isError: true, + documentId: documentId, + writeRow: row, + validationErrors: validationErrors + }); + } else { + continueWrites.push(row); + } + }); + var writePromise = continueWrites.length > 0 ? oldBulkWrite(continueWrites, context) : Promise.resolve({ + error: {}, + success: {} + }); + return writePromise.then(function (writeResult) { + errors.forEach(function (validationError) { + writeResult.error[validationError.documentId] = validationError; + }); + return writeResult; + }); + }; + return _context.abrupt("return", instance); + case 8: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createStorageInstance(_x) { + return _createStorageInstance.apply(this, arguments); } - } + return createStorageInstance; + }() }); }; } @@ -1037,250 +1454,413 @@ validatorKey) { * data of that storage instance. */ function wrapRxStorageInstance(instance, modifyToStorage, modifyFromStorage) { - var errorFromStorage = function errorFromStorage(error) { - try { - var _temp4 = function _temp4() { - function _temp2() { - return Promise.resolve(fromStorage(ret.writeRow.document)).then(function (_fromStorage4) { - ret.writeRow.document = _fromStorage4; - return ret; - }); - } - var _temp = function () { - if (ret.writeRow.previous) { - return Promise.resolve(fromStorage(ret.writeRow.previous)).then(function (_fromStorage3) { - ret.writeRow.previous = _fromStorage3; - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }; - var ret = (0, _util.flatClone)(error); - ret.writeRow = (0, _util.flatClone)(ret.writeRow); - var _temp3 = function () { - if (ret.documentInDb) { - return Promise.resolve(fromStorage(ret.documentInDb)).then(function (_fromStorage2) { - ret.documentInDb = _fromStorage2; - }); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3)); - } catch (e) { - return Promise.reject(e); - } - }; - var fromStorage = function fromStorage(docData) { - try { - if (!docData) { - return Promise.resolve(docData); - } - return Promise.resolve(modifyFromStorage(docData)); - } catch (e) { - return Promise.reject(e); - } - }; - var toStorage = function toStorage(docData) { - try { - if (!docData) { - return Promise.resolve(docData); - } - return Promise.resolve(modifyToStorage(docData)); - } catch (e) { - return Promise.reject(e); - } - }; var modifyAttachmentFromStorage = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function (v) { return v; }; - var oldBulkWrite = instance.bulkWrite.bind(instance); - instance.bulkWrite = function (documentWrites, context) { - try { - var useRows = []; - return Promise.resolve(Promise.all(documentWrites.map(function (row) { - try { - return Promise.resolve(Promise.all([row.previous ? toStorage(row.previous) : undefined, toStorage(row.document)])).then(function (_ref) { - var previous = _ref[0], - document = _ref[1]; - useRows.push({ - previous: previous, - document: document - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return Promise.resolve(oldBulkWrite(useRows, context)).then(function (writeResult) { - var ret = { - success: {}, - error: {} - }; - var promises = []; - Object.entries(writeResult.success).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - promises.push(fromStorage(v).then(function (v2) { - return ret.success[k] = v2; - })); - }); - Object.entries(writeResult.error).forEach(function (_ref3) { - var k = _ref3[0], - error = _ref3[1]; - promises.push(errorFromStorage(error).then(function (err) { - return ret.error[k] = err; - })); - }); - return Promise.resolve(Promise.all(promises)).then(function () { - return ret; - }); - }); + function toStorage(_x2) { + return _toStorage.apply(this, arguments); + } + function _toStorage() { + _toStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(docData) { + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + if (docData) { + _context11.next = 2; + break; + } + return _context11.abrupt("return", docData); + case 2: + _context11.next = 4; + return modifyToStorage(docData); + case 4: + return _context11.abrupt("return", _context11.sent); + case 5: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + return _toStorage.apply(this, arguments); + } + function fromStorage(_x3) { + return _fromStorage.apply(this, arguments); + } + function _fromStorage() { + _fromStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(docData) { + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + if (docData) { + _context12.next = 2; + break; + } + return _context12.abrupt("return", docData); + case 2: + _context12.next = 4; + return modifyFromStorage(docData); + case 4: + return _context12.abrupt("return", _context12.sent); + case 5: + case "end": + return _context12.stop(); + } + }, _callee12); + })); + return _fromStorage.apply(this, arguments); + } + function errorFromStorage(_x4) { + return _errorFromStorage.apply(this, arguments); + } + function _errorFromStorage() { + _errorFromStorage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee13(error) { + var ret; + return _regenerator["default"].wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + ret = (0, _utils.flatClone)(error); + ret.writeRow = (0, _utils.flatClone)(ret.writeRow); + if (!ret.documentInDb) { + _context13.next = 6; + break; + } + _context13.next = 5; + return fromStorage(ret.documentInDb); + case 5: + ret.documentInDb = _context13.sent; + case 6: + if (!ret.writeRow.previous) { + _context13.next = 10; + break; + } + _context13.next = 9; + return fromStorage(ret.writeRow.previous); + case 9: + ret.writeRow.previous = _context13.sent; + case 10: + _context13.next = 12; + return fromStorage(ret.writeRow.document); + case 12: + ret.writeRow.document = _context13.sent; + return _context13.abrupt("return", ret); + case 14: + case "end": + return _context13.stop(); + } + }, _callee13); + })); + return _errorFromStorage.apply(this, arguments); + } + var wrappedInstance = { + databaseName: instance.databaseName, + internals: instance.internals, + cleanup: instance.cleanup.bind(instance), + options: instance.options, + close: instance.close.bind(instance), + schema: instance.schema, + collectionName: instance.collectionName, + count: instance.count.bind(instance), + remove: instance.remove.bind(instance), + originalStorageInstance: instance, + bulkWrite: function () { + var _bulkWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(documentWrites, context) { + var useRows, writeResult, ret, promises; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + useRows = []; + _context3.next = 3; + return Promise.all(documentWrites.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(row) { + var _yield$Promise$all, previous, document; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all([row.previous ? toStorage(row.previous) : undefined, toStorage(row.document)]); + case 2: + _yield$Promise$all = _context2.sent; + previous = _yield$Promise$all[0]; + document = _yield$Promise$all[1]; + useRows.push({ + previous: previous, + document: document + }); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x7) { + return _ref.apply(this, arguments); + }; + }())); + case 3: + _context3.next = 5; + return instance.bulkWrite(useRows, context); + case 5: + writeResult = _context3.sent; + ret = { + success: {}, + error: {} + }; + promises = []; + Object.entries(writeResult.success).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; + promises.push(fromStorage(v).then(function (v2) { + return ret.success[k] = v2; + })); + }); + Object.entries(writeResult.error).forEach(function (_ref3) { + var k = _ref3[0], + error = _ref3[1]; + promises.push(errorFromStorage(error).then(function (err) { + return ret.error[k] = err; + })); + }); + _context3.next = 12; + return Promise.all(promises); + case 12: + return _context3.abrupt("return", ret); + case 13: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + function bulkWrite(_x5, _x6) { + return _bulkWrite.apply(this, arguments); + } + return bulkWrite; + }(), + query: function query(preparedQuery) { + return instance.query(preparedQuery).then(function (queryResult) { + return Promise.all(queryResult.documents.map(function (doc) { + return fromStorage(doc); + })); + }).then(function (documents) { + return { + documents: documents + }; }); - } catch (e) { - return Promise.reject(e); - } - }; - var oldQuery = instance.query.bind(instance); - instance.query = function (preparedQuery) { - return oldQuery(preparedQuery).then(function (queryResult) { - return Promise.all(queryResult.documents.map(function (doc) { - return fromStorage(doc); + }, + getAttachmentData: function () { + var _getAttachmentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(documentId, attachmentId) { + var data; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return instance.getAttachmentData(documentId, attachmentId); + case 2: + data = _context4.sent; + _context4.next = 5; + return modifyAttachmentFromStorage(data); + case 5: + data = _context4.sent; + return _context4.abrupt("return", data); + case 7: + case "end": + return _context4.stop(); + } + }, _callee4); })); - }).then(function (documents) { - return { - documents: documents + function getAttachmentData(_x8, _x9) { + return _getAttachmentData.apply(this, arguments); + } + return getAttachmentData; + }(), + findDocumentsById: function findDocumentsById(ids, deleted) { + return instance.findDocumentsById(ids, deleted).then( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(findResult) { + var ret; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + ret = {}; + _context6.next = 3; + return Promise.all(Object.entries(findResult).map( /*#__PURE__*/function () { + var _ref6 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_ref5) { + var key, doc; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + key = _ref5[0], doc = _ref5[1]; + _context5.next = 3; + return fromStorage(doc); + case 3: + ret[key] = _context5.sent; + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x11) { + return _ref6.apply(this, arguments); + }; + }())); + case 3: + return _context6.abrupt("return", ret); + case 4: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return function (_x10) { + return _ref4.apply(this, arguments); + }; + }()); + }, + getChangedDocumentsSince: function getChangedDocumentsSince(limit, checkpoint) { + return instance.getChangedDocumentsSince(limit, checkpoint).then( /*#__PURE__*/function () { + var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(result) { + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.t0 = result.checkpoint; + _context7.next = 3; + return Promise.all(result.documents.map(function (d) { + return fromStorage(d); + })); + case 3: + _context7.t1 = _context7.sent; + return _context7.abrupt("return", { + checkpoint: _context7.t0, + documents: _context7.t1 + }); + case 5: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return function (_x12) { + return _ref7.apply(this, arguments); + }; + }()); + }, + changeStream: function changeStream() { + return instance.changeStream().pipe((0, _operators.mergeMap)( /*#__PURE__*/function () { + var _ref8 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(eventBulk) { + var useEvents, ret; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return Promise.all(eventBulk.events.map( /*#__PURE__*/function () { + var _ref9 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(event) { + var _yield$Promise$all2, documentData, previousDocumentData, ev; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return Promise.all([fromStorage(event.documentData), fromStorage(event.previousDocumentData)]); + case 2: + _yield$Promise$all2 = _context8.sent; + documentData = _yield$Promise$all2[0]; + previousDocumentData = _yield$Promise$all2[1]; + ev = { + operation: event.operation, + eventId: event.eventId, + documentId: event.documentId, + endTime: event.endTime, + startTime: event.startTime, + documentData: documentData, + previousDocumentData: previousDocumentData, + isLocal: false + }; + return _context8.abrupt("return", ev); + case 7: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + return function (_x14) { + return _ref9.apply(this, arguments); + }; + }())); + case 2: + useEvents = _context9.sent; + ret = { + id: eventBulk.id, + events: useEvents, + checkpoint: eventBulk.checkpoint, + context: eventBulk.context + }; + return _context9.abrupt("return", ret); + case 5: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + return function (_x13) { + return _ref8.apply(this, arguments); + }; + }())); + }, + conflictResultionTasks: function conflictResultionTasks() { + return instance.conflictResultionTasks().pipe((0, _operators.mergeMap)( /*#__PURE__*/function () { + var _ref10 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(task) { + var assumedMasterState, newDocumentState, realMasterState; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return fromStorage(task.input.assumedMasterState); + case 2: + assumedMasterState = _context10.sent; + _context10.next = 5; + return fromStorage(task.input.newDocumentState); + case 5: + newDocumentState = _context10.sent; + _context10.next = 8; + return fromStorage(task.input.realMasterState); + case 8: + realMasterState = _context10.sent; + return _context10.abrupt("return", { + id: task.id, + context: task.context, + input: { + assumedMasterState: assumedMasterState, + realMasterState: realMasterState, + newDocumentState: newDocumentState + } + }); + case 10: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + return function (_x15) { + return _ref10.apply(this, arguments); + }; + }())); + }, + resolveConflictResultionTask: function resolveConflictResultionTask(taskSolution) { + if (taskSolution.output.isEqual) { + return instance.resolveConflictResultionTask(taskSolution); + } + var useSolution = { + id: taskSolution.id, + output: { + isEqual: false, + documentData: taskSolution.output.documentData + } }; - }); - }; - var oldGetAttachmentData = instance.getAttachmentData.bind(instance); - instance.getAttachmentData = function (documentId, attachmentId) { - try { - return Promise.resolve(oldGetAttachmentData(documentId, attachmentId)).then(function (data) { - return Promise.resolve(modifyAttachmentFromStorage(data)).then(function (_modifyAttachmentFrom) { - data = _modifyAttachmentFrom; - return data; - }); - }); - } catch (e) { - return Promise.reject(e); + return instance.resolveConflictResultionTask(useSolution); } }; - var oldFindDocumentsById = instance.findDocumentsById.bind(instance); - instance.findDocumentsById = function (ids, deleted) { - return oldFindDocumentsById(ids, deleted).then(function (findResult) { - try { - var ret = {}; - return Promise.resolve(Promise.all(Object.entries(findResult).map(function (_ref4) { - var key = _ref4[0], - doc = _ref4[1]; - return Promise.resolve(fromStorage(doc)).then(function (_fromStorage) { - ret[key] = _fromStorage; - }); - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }); - }; - var oldGetChangedDocumentsSince = instance.getChangedDocumentsSince.bind(instance); - instance.getChangedDocumentsSince = function (limit, checkpoint) { - return oldGetChangedDocumentsSince(limit, checkpoint).then(function (result) { - try { - var _result$checkpoint = result.checkpoint; - return Promise.resolve(Promise.all(result.documents.map(function (d) { - return fromStorage(d); - }))).then(function (_Promise$all) { - return { - checkpoint: _result$checkpoint, - documents: _Promise$all - }; - }); - } catch (e) { - return Promise.reject(e); - } - }); - }; - var oldChangeStream = instance.changeStream.bind(instance); - instance.changeStream = function () { - return oldChangeStream().pipe((0, _operators.mergeMap)(function (eventBulk) { - try { - return Promise.resolve(Promise.all(eventBulk.events.map(function (event) { - try { - return Promise.resolve(Promise.all([fromStorage(event.documentData), fromStorage(event.previousDocumentData)])).then(function (_ref5) { - var documentData = _ref5[0], - previousDocumentData = _ref5[1]; - var ev = { - operation: event.operation, - eventId: event.eventId, - documentId: event.documentId, - endTime: event.endTime, - startTime: event.startTime, - documentData: documentData, - previousDocumentData: previousDocumentData, - isLocal: false - }; - return ev; - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function (useEvents) { - var ret = { - id: eventBulk.id, - events: useEvents, - checkpoint: eventBulk.checkpoint, - context: eventBulk.context - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - })); - }; - var oldConflictResultionTasks = instance.conflictResultionTasks.bind(instance); - instance.conflictResultionTasks = function () { - return oldConflictResultionTasks().pipe((0, _operators.mergeMap)(function (task) { - try { - return Promise.resolve(fromStorage(task.input.assumedMasterState)).then(function (assumedMasterState) { - return Promise.resolve(fromStorage(task.input.newDocumentState)).then(function (newDocumentState) { - return Promise.resolve(fromStorage(task.input.realMasterState)).then(function (realMasterState) { - return { - id: task.id, - context: task.context, - input: { - assumedMasterState: assumedMasterState, - realMasterState: realMasterState, - newDocumentState: newDocumentState - } - }; - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })); - }; - var oldResolveConflictResultionTask = instance.resolveConflictResultionTask.bind(instance); - instance.resolveConflictResultionTask = function (taskSolution) { - if (taskSolution.output.isEqual) { - return oldResolveConflictResultionTask(taskSolution); - } - var useSolution = { - id: taskSolution.id, - output: { - isEqual: false, - documentData: taskSolution.output.documentData - } - }; - return oldResolveConflictResultionTask(useSolution); - }; - return instance; + return wrappedInstance; } -},{"./util":44,"rxjs/operators":683}],10:[function(require,module,exports){ +},{"./plugins/utils":12,"./rx-schema-helper":44,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"rxjs/operators":648}],11:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -1340,9 +1920,8 @@ function addRxPlugin(plugin) { } /** - * Since version 10.0.0 we decoupled pouchdb from - * the rxdb core. Therefore pouchdb plugins must be added - * with the addPouchPlugin() method of the pouchdb plugin. + * To identify broken configurations, + * we only allow RxDB plugins to be passed into addRxPlugin(). */ if (!plugin.rxdb) { throw (0, _rxError.newRxTypeError)('PL1', { @@ -1380,2437 +1959,1256 @@ function addRxPlugin(plugin) { } } -},{"./hooks":6,"./overwritable":8,"./rx-collection":30,"./rx-database":32,"./rx-document":34,"./rx-error":35,"./rx-query":37,"./rx-schema":39}],11:[function(require,module,exports){ +},{"./hooks":6,"./overwritable":9,"./rx-collection":36,"./rx-database":38,"./rx-document":40,"./rx-error":41,"./rx-query":43,"./rx-schema":45}],12:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.POUCHDB_LOCATION = void 0; -exports.checkAdapter = checkAdapter; -var _pouchDb = require("./pouch-db"); -var _util = require("../../util"); -/** - * this plugin adds the checkAdapter-function to rxdb - * you can use it to check if the given adapter is working in the current environment - */ - -/** - * The same pouchdb-location is used on each run - * To ensure when this is run multiple times, - * there will not be many created databases - */ -var POUCHDB_LOCATION = 'rxdb-adapter-check'; -exports.POUCHDB_LOCATION = POUCHDB_LOCATION; -function checkAdapter(adapter) { - // id of the document which is stored and removed to ensure everything works - var _id = POUCHDB_LOCATION + '-' + (0, _util.randomCouchString)(12); - var pouch; - try { - pouch = new _pouchDb.PouchDB(POUCHDB_LOCATION, (0, _util.adapterObject)(adapter), { - auto_compaction: true, - revs_limit: 1 - }); - } catch (err) { - return _util.PROMISE_RESOLVE_FALSE; - } - var recoveredDoc; - return pouch.info() // ensure that we wait until db is usable - // ensure write works - .then(function () { - return pouch.put({ - _id: _id, - value: { - ok: true, - time: (0, _util.now)() - } - }); - }) - // ensure read works - .then(function () { - return pouch.get(_id); - }).then(function (doc) { - return recoveredDoc = doc; - }) - // ensure remove works - .then(function () { - return pouch.remove(recoveredDoc); - }).then(function () { - return true; - }).then(function () { - if (recoveredDoc && recoveredDoc.value && recoveredDoc.value.ok) return true;else return false; - })["catch"](function () { - return false; +var _utilsArray = require("./utils-array"); +Object.keys(_utilsArray).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsArray[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsArray[key]; + } }); +}); +var _utilsBlobBuffer = require("./utils-blob-buffer"); +Object.keys(_utilsBlobBuffer).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsBlobBuffer[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsBlobBuffer[key]; + } + }); +}); +var _utilsBase = require("./utils-base64"); +Object.keys(_utilsBase).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsBase[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsBase[key]; + } + }); +}); +var _utilsRevision = require("./utils-revision"); +Object.keys(_utilsRevision).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsRevision[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsRevision[key]; + } + }); +}); +var _utilsDocument = require("./utils-document"); +Object.keys(_utilsDocument).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsDocument[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsDocument[key]; + } + }); +}); +var _utilsHash = require("./utils-hash"); +Object.keys(_utilsHash).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsHash[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsHash[key]; + } + }); +}); +var _utilsPromise = require("./utils-promise"); +Object.keys(_utilsPromise).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsPromise[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsPromise[key]; + } + }); +}); +var _utilsString = require("./utils-string"); +Object.keys(_utilsString).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsString[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsString[key]; + } + }); +}); +var _utilsObject = require("./utils-object"); +Object.keys(_utilsObject).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsObject[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsObject[key]; + } + }); +}); +var _utilsError = require("./utils-error"); +Object.keys(_utilsError).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsError[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsError[key]; + } + }); +}); +var _utilsTime = require("./utils-time"); +Object.keys(_utilsTime).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsTime[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsTime[key]; + } + }); +}); +var _utilsOther = require("./utils-other"); +Object.keys(_utilsOther).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _utilsOther[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utilsOther[key]; + } + }); +}); - /** - * NOTICE: - * Do not remove the pouchdb-instance after the test - * The problem is that when this function is call in parallel, - * for example when you restore the tabs from a browser-session and open - * the same website multiple times at the same time, - * calling destroy would possibly crash the other call - */ -} - -},{"../../util":44,"./pouch-db":14}],12:[function(require,module,exports){ +},{"./utils-array":13,"./utils-base64":14,"./utils-blob-buffer":15,"./utils-document":16,"./utils-error":17,"./utils-hash":18,"./utils-object":19,"./utils-other":20,"./utils-promise":21,"./utils-revision":22,"./utils-string":23,"./utils-time":24}],13:[function(require,module,exports){ "use strict"; -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.EVENT_EMITTER_BY_POUCH_INSTANCE = void 0; -exports.addCustomEventsPluginToPouch = addCustomEventsPluginToPouch; -exports.changeEventToNormal = changeEventToNormal; -exports.eventEmitDataToStorageEvents = void 0; -exports.getCustomEventEmitterByPouch = getCustomEventEmitterByPouch; -var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); -var _rxjs = require("rxjs"); -var _util = require("../../util"); -var _rxError = require("../../rx-error"); -var _pouchdbHelper = require("./pouchdb-helper"); -/* - * Instead of listening to pouch.changes, - * we overwrite pouchdbs bulkDocs() - * and create our own event stream, this will work more reliable - * and has less strange behaviors. - * Also we can better define what data we need for our events. - * @link http://jsbin.com/pagebi/1/edit?js,output - * @link https://github.com/pubkey/rxdb/blob/1f4115b69bdacbb853af9c637d70f5f184d4e474/src/rx-storage-pouchdb.ts#L273 - * @link https://hasura.io/blog/couchdb-style-conflict-resolution-rxdb-hasura/ +exports.arrayFilterNotEmpty = arrayFilterNotEmpty; +exports.batchArray = batchArray; +exports.isMaybeReadonlyArray = isMaybeReadonlyArray; +exports.lastOfArray = lastOfArray; +exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; +exports.shuffleArray = shuffleArray; +exports.toArray = toArray; +function lastOfArray(ar) { + return ar[ar.length - 1]; +} + +/** + * shuffle the given array */ -var eventEmitDataToStorageEvents = function eventEmitDataToStorageEvents(pouchDBInstance, primaryPath, emitData) { - try { - var ret = []; - var _temp7 = function () { - if (!emitData.writeOptions.custom && emitData.writeOptions.hasOwnProperty('new_edits') && emitData.writeOptions.new_edits === false) { - return Promise.resolve(Promise.all(emitData.writeDocs.map(function (writeDoc) { - try { - var id = writeDoc._id; - writeDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(primaryPath, writeDoc); - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeDoc._attachments)).then(function (_writeAttachmentsToAt) { - writeDoc._attachments = _writeAttachmentsToAt; - var previousDoc = emitData.previousDocs.get(id); - if (previousDoc) { - previousDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(primaryPath, previousDoc); - } - if (previousDoc) { - var parsedRevPrevious = (0, _util.parseRevision)(previousDoc._rev); - var parsedRevNew = (0, _util.parseRevision)(writeDoc._rev); - if (parsedRevPrevious.height > parsedRevNew.height || - /** - * If the revision height is equal, - * we determine the higher hash as winner. - */ +function shuffleArray(arr) { + return arr.sort(function () { + return Math.random() - 0.5; + }); +} +function toArray(input) { + return Array.isArray(input) ? input.slice(0) : [input]; +} - parsedRevPrevious.height === parsedRevNew.height && parsedRevPrevious.hash > parsedRevNew.hash) { - /** - * The newly added document was not the latest revision - * so we drop the write. - * With plain PouchDB it makes sense to store conflicting branches of the document - * but RxDB assumes that the conflict is resolved directly. - */ - return; - } - } - if (!previousDoc && writeDoc._deleted) { - // deleted document was added as revision - return; - } - if (previousDoc && previousDoc._deleted && writeDoc._deleted) { - // delete document was deleted again - return; - } - var event; - if ((!previousDoc || previousDoc._deleted) && !writeDoc._deleted) { - // was insert - event = { - operation: 'INSERT', - doc: writeDoc, - id: id, - previous: null - }; - } else if (writeDoc._deleted && previousDoc && !previousDoc._deleted) { - // was delete - previousDoc._rev = writeDoc._rev; - event = { - operation: 'DELETE', - doc: writeDoc, - id: id, - previous: previousDoc - }; - } else if (previousDoc) { - // was update - event = { - operation: 'UPDATE', - doc: writeDoc, - id: id, - previous: previousDoc - }; - } else { - throw (0, _rxError.newRxError)('SNH', { - args: { - writeDoc: writeDoc - } - }); - } - var changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event, emitData.startTime, emitData.endTime); - ret.push(changeEvent); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); // eslint-disable-next-line brace-style - } else { - var _temp8 = function () { - if (!emitData.writeOptions.custom || emitData.writeOptions.custom && !emitData.writeOptions.custom.writeRowById) { - var writeDocsById = new Map(); - emitData.writeDocs.forEach(function (writeDoc) { - return writeDocsById.set(writeDoc._id, writeDoc); - }); - return Promise.resolve(Promise.all(emitData.writeResult.map(function (resultRow) { - try { - var id = resultRow.id; - if (id.startsWith(_pouchdbHelper.POUCHDB_DESIGN_PREFIX) || id.startsWith(_pouchdbHelper.POUCHDB_LOCAL_PREFIX)) { - return Promise.resolve(); - } - var writeDoc = (0, _util.getFromMapOrThrow)(writeDocsById, resultRow.id); - writeDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(primaryPath, writeDoc); - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeDoc._attachments)).then(function (_writeAttachmentsToAt2) { - writeDoc._attachments = _writeAttachmentsToAt2; - writeDoc = (0, _util.flatClone)(writeDoc); - writeDoc._rev = resultRow.rev; - var event = (0, _pouchdbHelper.pouchChangeRowToChangeEvent)(primaryPath, writeDoc); - var changeEvent = changeEventToNormal(pouchDBInstance, primaryPath, event); - ret.push(changeEvent); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } else { - var writeMap = emitData.writeOptions.custom.writeRowById; - return Promise.resolve(Promise.all(emitData.writeResult.map(function (resultRow) { - try { - if (resultRow.error) { - return Promise.resolve(); - } - var id = resultRow.id; - var writeRow = (0, _util.getFromMapOrThrow)(writeMap, id); - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeRow.document._attachments)).then(function (attachments) { - function _temp11() { - if (writeRow.document._deleted && (!writeRow.previous || writeRow.previous._deleted)) {} else { - var changeEvent = changeEventToNormal(pouchDBInstance, (0, _util.ensureNotFalsy)(emitData.writeOptions.custom).primaryPath, event, emitData.startTime, emitData.endTime); - ret.push(changeEvent); - } - } - var newDoc = Object.assign({}, writeRow.document, { - _attachments: attachments, - _rev: resultRow.rev - }); - var event; - var _temp10 = function () { - if (!writeRow.previous || writeRow.previous._deleted) { - // was insert - event = { - operation: 'INSERT', - doc: newDoc, - id: id, - previous: null - }; - } else { - var _temp12 = function () { - if (writeRow.document._deleted) { - // was delete - // we need to add the new revision to the previous doc - // so that the eventkey is calculated correctly. - // Is this a hack? idk. - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeRow.previous._attachments)).then(function (attachmentsInner) { - var previousDoc = Object.assign({}, writeRow.previous, { - _attachments: attachmentsInner - }); - event = { - operation: 'DELETE', - doc: writeRow.document, - id: resultRow.id, - previous: previousDoc - }; - }); - } else { - // was update - event = { - operation: 'UPDATE', - doc: newDoc, - id: resultRow.id, - previous: writeRow.previous - }; - } - }(); - if (_temp12 && _temp12.then) return _temp12.then(function () {}); - } - }(); - return _temp10 && _temp10.then ? _temp10.then(_temp11) : _temp11(_temp10); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - } - }(); - if (_temp8 && _temp8.then) return _temp8.then(function () {}); - } - }(); - return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(function () { - return ret; - }) : ret); - } catch (e) { - return Promise.reject(e); - } -}; -exports.eventEmitDataToStorageEvents = eventEmitDataToStorageEvents; -// ensure only added once -var addedToPouch = false; -var EVENT_EMITTER_BY_POUCH_INSTANCE = new Map(); -exports.EVENT_EMITTER_BY_POUCH_INSTANCE = EVENT_EMITTER_BY_POUCH_INSTANCE; -function getCustomEventEmitterByPouch(pouch) { - var key = [pouch.__opts.name, pouch.adapter].join('|'); - var emitter = EVENT_EMITTER_BY_POUCH_INSTANCE.get(key); - if (!emitter) { - emitter = { - subject: new _rxjs.Subject() - }; - EVENT_EMITTER_BY_POUCH_INSTANCE.set(key, emitter); +/** + * Split array with items into smaller arrays with items + * @link https://stackoverflow.com/a/7273794/3443137 + */ +function batchArray(array, batchSize) { + array = array.slice(0); + var ret = []; + while (array.length) { + var batch = array.splice(0, batchSize); + ret.push(batch); } - return emitter; + return ret; } /** - * Counter, used to debug stuff. + * @link https://stackoverflow.com/a/15996017 */ -var i = 0; +function removeOneFromArrayIfMatches(ar, condition) { + ar = ar.slice(); + var i = ar.length; + var done = false; + while (i-- && !done) { + if (condition(ar[i])) { + done = true; + ar.splice(i, 1); + } + } + return ar; +} /** - * Because we cannot force pouchdb to await bulkDocs runs - * inside of a transaction, like done with the other RxStorage implementations, - * we have to ensure the calls to bulkDocs() do not run in parallel. - * - * TODO this is somehow a hack. Instead of doing that, inspect how - * PouchDB runs bulkDocs internally and adapt that transaction handling. + * returns true if the supplied argument is either an Array or a Readonly> */ -var BULK_DOC_RUN_QUEUE = new WeakMap(); +function isMaybeReadonlyArray(x) { + // While this looks strange, it's a workaround for an issue in TypeScript: + // https://github.com/microsoft/TypeScript/issues/17002 + // + // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array, + // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`. + // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while + // still performing runtime type inspection. + return Array.isArray(x); +} /** - * PouchDB is like a minefield, - * where stuff randomly does not work dependent on some conditions. - * So instead of doing plain writes, - * we hack into the bulkDocs() function - * and adjust the behavior accordingly. + * Use this in array.filter() to remove all empty slots + * and have the correct typings afterwards. + * @link https://stackoverflow.com/a/46700791/3443137 */ -function addCustomEventsPluginToPouch() { - if (addedToPouch) { - return; +function arrayFilterNotEmpty(value) { + if (value === null || value === undefined) { + return false; } - addedToPouch = true; - var oldBulkDocs = _pouchdbCore["default"].prototype.bulkDocs; + return true; +} - /** - * Ensure we do not run bulkDocs() in parallel on the same PouchDB instance. - */ - var newBulkDocs = function newBulkDocs(body, options, callback) { - var _this = this; - /** - * Normalize inputs - * because there are many ways to call pouchdb.bulkDocs() - */ - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } - - /** - * PouchDB internal requests - * must still be handled normally - * to decrease the likelyness of bugs. - */ - var internalPouches = ['_replicator', '_users', 'pouch__all_dbs__']; - if (internalPouches.includes(this.name) || this.name.includes('-mrview-')) { - return oldBulkDocs.call(this, body, options, function (err, result) { - if (err) { - if (callback) { - callback(err, null); - } - } else { - if (callback) { - callback(null, result); - } - } - }); - } - var queue = BULK_DOC_RUN_QUEUE.get(this); - if (!queue) { - queue = _util.PROMISE_RESOLVE_VOID; - } - queue = queue.then(function () { - try { - return Promise.resolve(newBulkDocsInner.bind(_this)(body, options, callback)); - } catch (e) { - return Promise.reject(e); - } - }); - BULK_DOC_RUN_QUEUE.set(this, queue); - return queue; - }; - var newBulkDocsInner = function newBulkDocsInner(body, options, callback) { - try { - var _temp3 = function _temp3() { - /** - * Custom handling if the call came from RxDB (options.custom is set). - */ - var usePouchResult = []; - var hasNonErrorWrite = false; - if (options.custom && options.hasOwnProperty('new_edits') && options.new_edits === false) { - /** - * Reset the write docs array, - * because we only write non-conflicting documents. - */ - docs = []; - var writeRowById = options.custom.writeRowById; - var insertDocsById = options.custom.insertDocsById; - Array.from(writeRowById.entries()).forEach(function (_ref) { - var id = _ref[0], - writeRow = _ref[1]; - var previousRev = writeRow.previous ? writeRow.previous._rev : null; - var newRev = (0, _util.parseRevision)(writeRow.document._rev); - var docInDb = previousDocsInDb.get(id); - var docInDbRev = docInDb ? docInDb._rev : null; - if (docInDbRev !== previousRev) { - // we have a conflict - usePouchResult.push({ - error: true, - id: id, - status: 409 - }); - } else { - var useRevisions = { - start: newRev.height, - ids: docInDb ? docInDb._revisions.ids.slice(0) : [] - }; - useRevisions.ids.unshift(newRev.hash); - var useNewRev = useRevisions.start + '-' + newRev.hash; - hasNonErrorWrite = true; - var writeToPouchDocData = Object.assign({}, insertDocsById.get(id), { - _revisions: useRevisions, - _rev: useNewRev - }); - docs.push(writeToPouchDocData); - usePouchResult.push({ - ok: true, - id: id, - rev: writeRow.document._rev - }); - } - }); - - /** - * Optimization shortcut, - * if all document writes were conflict errors, - * we can skip directly. - */ - if (!hasNonErrorWrite) { - return usePouchResult; - } - } - - /** - * pouchdb calls this function again with transformed input. - * This would lead to duplicate events. So we marks the deeper calls via the options - * parameter and do not emit events if it is set. - */ - var deeperOptions = (0, _util.flatClone)(options); - deeperOptions.isDeeper = true; - var callReturn; - var callPromise = new Promise(function (res, rej) { - /** - * The emitted EventBulk from the write to the pouchdb, needs to contain a checkpoint field. - * Because PouchDB works on sequence number to sort changes, - * we have to fetch the latest sequence number out of the events because it - * is not possible to that that from pouch.bulkDocs(). - */ - var docIds = new Set(docs.map(function (d) { - return d._id; - })); - var heighestSequence = 0; - var changesSub; - var heighestSequencePromise = new Promise(function (res2) { - changesSub = _this2.changes({ - since: 'now', - live: true, - include_docs: true - }).on('change', function (change) { - var docId = change.id; - if (docIds.has(docId)) { - docIds["delete"](docId); - if (heighestSequence < change.seq) { - heighestSequence = change.seq; - } - if (docIds.size === 0) { - changesSub.cancel(); - res2(heighestSequence); - } - } - }); - }); - - /** - * We cannot send the custom here, - * because when a migration between different major RxDB versions is done, - * multiple versions of the RxDB PouchDB RxStorage might have added their - * custom method via PouchDBCore.plugin() - */ - var useOptsForOldBulkDocs = (0, _util.flatClone)(deeperOptions); - delete useOptsForOldBulkDocs.custom; - callReturn = oldBulkDocs.call(_this2, docs, useOptsForOldBulkDocs, function (err, result) { - if (err) { - if (callback) { - callback(err); - } else { - rej(err); - } - } else { - return function () { - try { - var _temp5 = function _temp5() { - result.forEach(function (row) { - usePouchResult.push(row); - }); - - /** - * For calls that came from RxDB, - * we have to ensure that the events are emitted - * before the actual call resolves. - */ - var eventsPromise = _util.PROMISE_RESOLVE_VOID; - if (!options.isDeeper) { - var endTime = (0, _util.now)(); - var emitData = { - emitId: runId, - writeDocs: docs, - writeOptions: options, - writeResult: usePouchResult, - previousDocs: previousDocsInDb, - startTime: startTime, - endTime: endTime - }; - eventsPromise = eventEmitDataToStorageEvents(_this2, '_id', emitData).then(function (events) { - var eventBulk = { - id: (0, _util.randomCouchString)(10), - events: events, - checkpoint: { - sequence: heighestSequenceInner - }, - context: options.custom ? options.custom.context : 'pouchdb-internal' - }; - var emitter = getCustomEventEmitterByPouch(_this2); - emitter.subject.next(eventBulk); - }); - } - if (callback) { - callback(null, usePouchResult); - } else { - return eventsPromise.then(function () { - res(usePouchResult); - return usePouchResult; - }); - } - }; - var hasError = result.find(function (row) { - return row.error; - }); - var heighestSequenceInner = -1; - var _temp4 = function () { - if (!hasError) { - return Promise.resolve(heighestSequencePromise).then(function (_heighestSequenceProm) { - heighestSequenceInner = _heighestSequenceProm; - }); - } else { - changesSub.cancel(); - } - }(); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }(); - } - }); - }); - return options.custom ? callPromise : callReturn; - }; - var _this2 = this; - var startTime = (0, _util.now)(); - var runId = i++; - - /** - * Normalize inputs - * because there are many ways to call pouchdb.bulkDocs() - */ - if (typeof options === 'function') { - callback = options; - options = {}; - } - if (!options) { - options = {}; - } - var docs; - if (Array.isArray(body)) { - docs = body; - } else if (body === undefined) { - docs = []; - } else { - docs = body.docs; - if (body.hasOwnProperty('new_edits')) { - options.new_edits = body.new_edits; - } - } - - // throw if no docs given, because RxDB should never make such a call. - if (docs.length === 0) { - throw (0, _rxError.newRxError)('SNH', { - args: { - body: body, - options: options - } - }); - } - - /** - * If new_edits=false we have to first find the current state - * of the document and can later check if the state was changed - * because a new revision was written and we have to emit an event. - */ - var previousDocsInDb = options.custom ? options.custom.previousDocsInDb : new Map(); - var _temp2 = function () { - if (options.hasOwnProperty('new_edits') && options.new_edits === false) { - return Promise.resolve(_this2.bulkGet({ - docs: docs.map(function (doc) { - return { - id: doc._id - }; - }), - revs: true, - latest: true - })).then(function (viaBulkGet) { - /** - * bulkGet() does not return deleted documents, - * so we must refetch them via allDocs() afterwards. - */ - var mustRefetchBecauseDeleted = []; - viaBulkGet.results.forEach(function (resultRow) { - var firstDoc = resultRow.docs[0]; - if (firstDoc.ok) { - previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok); - } else { - if (firstDoc.error && firstDoc.error.reason === 'deleted') { - mustRefetchBecauseDeleted.push(resultRow.id); - } - } - }); - var _temp = function () { - if (mustRefetchBecauseDeleted.length > 0) { - return Promise.resolve(_this2.allDocs({ - keys: mustRefetchBecauseDeleted, - include_docs: true, - conflicts: true - })).then(function (deletedDocsViaAllDocs) { - var idsWithRevs = []; - deletedDocsViaAllDocs.rows.forEach(function (row) { - idsWithRevs.push({ - id: row.id, - rev: row.value.rev - }); - }); - return Promise.resolve(_this2.bulkGet({ - docs: idsWithRevs, - revs: true, - latest: true - })).then(function (deletedDocsViaBulkGetWithRev) { - deletedDocsViaBulkGetWithRev.results.forEach(function (resultRow) { - var firstDoc = resultRow.docs[0]; - if (firstDoc.ok) { - previousDocsInDb.set(firstDoc.ok._id, firstDoc.ok); - } else { - throw (0, _rxError.newRxError)('SNH', { - args: { - deletedDocsViaBulkGetWithRev: deletedDocsViaBulkGetWithRev, - resultRow: resultRow - } - }); - } - }); - }); - }); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2)); - } catch (e) { - return Promise.reject(e); - } - }; - _pouchdbCore["default"].plugin({ - bulkDocs: newBulkDocs - }); -} -function changeEventToNormal(pouchDBInstance, primaryPath, change, startTime, endTime) { - var doc = change.operation === 'DELETE' ? change.previous : change.doc; - var primary = doc[primaryPath]; - var storageChangeEvent = { - eventId: (0, _pouchdbHelper.getEventKey)(pouchDBInstance, primary, change), - documentId: primary, - documentData: change.doc, - previousDocumentData: change.previous, - operation: change.operation, - startTime: startTime, - endTime: endTime - }; - return storageChangeEvent; -} - -},{"../../rx-error":35,"../../util":44,"./pouchdb-helper":16,"@babel/runtime/helpers/interopRequireDefault":51,"pouchdb-core":431,"rxjs":458}],13:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _pouchDb = require("./pouch-db"); -Object.keys(_pouchDb).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _pouchDb[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _pouchDb[key]; - } - }); -}); -var _rxStoragePouchdb = require("./rx-storage-pouchdb"); -Object.keys(_rxStoragePouchdb).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _rxStoragePouchdb[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _rxStoragePouchdb[key]; - } - }); -}); -var _adapterCheck = require("./adapter-check"); -Object.keys(_adapterCheck).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _adapterCheck[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _adapterCheck[key]; - } - }); -}); -var _customEventsPlugin = require("./custom-events-plugin"); -Object.keys(_customEventsPlugin).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _customEventsPlugin[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _customEventsPlugin[key]; - } - }); -}); -var _pouchdbHelper = require("./pouchdb-helper"); -Object.keys(_pouchdbHelper).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _pouchdbHelper[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _pouchdbHelper[key]; - } - }); -}); -var _pouchStatics = require("./pouch-statics"); -Object.keys(_pouchStatics).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _pouchStatics[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _pouchStatics[key]; - } - }); -}); -var _rxStorageInstancePouch = require("./rx-storage-instance-pouch"); -Object.keys(_rxStorageInstancePouch).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _rxStorageInstancePouch[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _rxStorageInstancePouch[key]; - } - }); -}); - -},{"./adapter-check":11,"./custom-events-plugin":12,"./pouch-db":14,"./pouch-statics":15,"./pouchdb-helper":16,"./rx-storage-instance-pouch":17,"./rx-storage-pouchdb":18}],14:[function(require,module,exports){ +},{}],14:[function(require,module,exports){ "use strict"; -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.PouchDB = void 0; -exports.addPouchPlugin = addPouchPlugin; -exports.isInstanceOf = isInstanceOf; -exports.isLevelDown = isLevelDown; -var _pouchdbCore = _interopRequireDefault(require("pouchdb-core")); -var _rxError = require("../../rx-error"); +exports.arrayBufferToBase64 = arrayBufferToBase64; +exports.b64DecodeUnicode = b64DecodeUnicode; +exports.b64EncodeUnicode = b64EncodeUnicode; +var _jsBase = require("js-base64"); /** - * this handles the pouchdb-instance - * to easy add modules and manipulate things - * Adapters can be found here: - * @link https://github.com/pouchdb/pouchdb/tree/master/packages/node_modules + * NO! We cannot just use btoa() and atob() + * because they do not work correctly with binary data. + * @link https://stackoverflow.com/q/30106476/3443137 */ -/* -// comment in to debug -const pouchdbDebug = require('pouchdb-debug'); -PouchDB.plugin(pouchdbDebug); -PouchDB.debug.enable('*'); -*/ - /** - * check if the given module is a leveldown-adapter - * throws if not + * atob() and btoa() do not work well with non ascii chars, + * so we have to use these helper methods instead. + * @link https://stackoverflow.com/a/30106551/3443137 */ -function isLevelDown(adapter) { - if (!adapter || typeof adapter.super_ !== 'function') { - throw (0, _rxError.newRxError)('UT4', { - adapter: adapter - }); - } -} -function isInstanceOf(obj) { - return obj instanceof _pouchdbCore["default"]; +// Encoding UTF8 -> base64 +function b64EncodeUnicode(str) { + return (0, _jsBase.encode)(str); } -/** - * Adding a PouchDB plugin multiple times, - * can sometimes error. So we have to check if the plugin - * was added before. - */ -var ADDED_POUCH_PLUGINS = new Set(); +// Decoding base64 -> UTF8 +function b64DecodeUnicode(str) { + return (0, _jsBase.decode)(str); +} /** - * Add a pouchdb plugin to the pouchdb library. - * @deprecated PouchDB RxStorage is deprecated, see - * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated + * @link https://stackoverflow.com/a/9458996/3443137 */ -function addPouchPlugin(plugin) { - if (plugin.rxdb) { - throw (0, _rxError.newRxTypeError)('PL2', { - plugin: plugin - }); - } - /** - * Pouchdb has confusing typings and modules. - * So we monkeypatch the plugin to use the default property - * when it was imported or packaged this way. - */ - if (typeof plugin === 'object' && plugin["default"]) { - plugin = plugin["default"]; - } - if (!ADDED_POUCH_PLUGINS.has(plugin)) { - ADDED_POUCH_PLUGINS.add(plugin); - _pouchdbCore["default"].plugin(plugin); +function arrayBufferToBase64(buffer) { + var binary = ''; + var bytes = new Uint8Array(buffer); + var len = bytes.byteLength; + for (var i = 0; i < len; i++) { + binary += String.fromCharCode(bytes[i]); } + return btoa(binary); } -var PouchDB = _pouchdbCore["default"]; -exports.PouchDB = PouchDB; -},{"../../rx-error":35,"@babel/runtime/helpers/interopRequireDefault":51,"pouchdb-core":431}],15:[function(require,module,exports){ +},{"js-base64":418}],15:[function(require,module,exports){ +(function (Buffer){(function (){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.RxStoragePouchStatics = void 0; -exports.preparePouchDbQuery = preparePouchDbQuery; -var _pouchdbSelectorCore = require("pouchdb-selector-core"); -var _rxError = require("../../rx-error"); -var _pouchdbHelper = require("./pouchdb-helper"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _overwritable = require("../../overwritable"); -var _util = require("../../util"); -var RxStoragePouchStatics = { - getSortComparator: function getSortComparator(schema, query) { - var _ref; - var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var sortOptions = query.sort ? query.sort : [(_ref = {}, _ref[primaryPath] = 'asc', _ref)]; - var selector = query.selector ? query.selector : {}; - var inMemoryFields = Object.keys(selector).filter(function (key) { - return !key.startsWith('$'); - }); - var fun = function fun(a, b) { - /** - * Sorting on two documents with the same primary is not allowed - * because it might end up in a non-deterministic result. - */ - if (a[primaryPath] === b[primaryPath]) { - throw (0, _rxError.newRxError)('SNH', { - args: { - a: a, - b: b - }, - primaryPath: primaryPath - }); - } - - // TODO use createFieldSorter - // TODO make a performance test - var rows = [a, b].map(function (doc) { - return { - doc: (0, _pouchdbHelper.pouchSwapPrimaryToId)(primaryPath, doc) - }; - }); - var sortedRows = (0, _pouchdbSelectorCore.filterInMemoryFields)(rows, { - selector: {}, - sort: sortOptions - }, inMemoryFields); - if (sortedRows.length !== 2) { - throw (0, _rxError.newRxError)('SNH', { - query: query, - primaryPath: primaryPath, - args: { - rows: rows, - sortedRows: sortedRows - } - }); - } - if (sortedRows[0].doc._id === rows[0].doc._id) { - return -1; - } else { - return 1; - } - }; - return fun; - }, +exports.blobBufferUtil = void 0; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utilsBase = require("./utils-base64"); +/** + * This is an abstraction over the Blob/Buffer data structure. + * We need this because it behaves different in different JavaScript runtimes. + * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support + * the Blob data structure which is also supported by the browsers. + */ +var blobBufferUtil = { /** - * @link https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-selector-core/src/matches-selector.js + * depending if we are on node or browser, + * we have to use Buffer(node) or Blob(browser) */ - getQueryMatcher: function getQueryMatcher(schema, query) { - var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var selector = query.selector ? query.selector : {}; - var massagedSelector = (0, _pouchdbSelectorCore.massageSelector)(selector); - var fun = function fun(doc) { - if (doc._deleted) { - return false; - } - var cloned = (0, _pouchdbHelper.pouchSwapPrimaryToId)(primaryPath, doc); - var row = { - doc: cloned - }; - var rowsMatched = (0, _pouchdbSelectorCore.filterInMemoryFields)([row], { - selector: massagedSelector - }, Object.keys(selector)); - var ret = rowsMatched && rowsMatched.length === 1; - return ret; - }; - return fun; + createBlobBuffer: function createBlobBuffer(data, type) { + var blobBuffer = new Blob([data], { + type: type + }); + return blobBuffer; }, /** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb + * depending if we are on node or browser, + * we have to use Buffer(node) or Blob(browser) */ - prepareQuery: function prepareQuery(schema, mutateableQuery) { - return preparePouchDbQuery(schema, mutateableQuery); + createBlobBufferFromBase64: function () { + var _createBlobBufferFromBase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(base64String, type) { + var base64Response, blob; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return fetch("data:" + type + ";base64," + base64String); + case 2: + base64Response = _context.sent; + _context.next = 5; + return base64Response.blob(); + case 5: + blob = _context.sent; + return _context.abrupt("return", blob); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); + function createBlobBufferFromBase64(_x, _x2) { + return _createBlobBufferFromBase.apply(this, arguments); + } + return createBlobBufferFromBase64; + }(), + isBlobBuffer: function isBlobBuffer(data) { + if (data instanceof Blob || typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) { + return true; + } else { + return false; + } }, - checkpointSchema: _pouchdbHelper.POUCHDB_CHECKPOINT_SCHEMA -}; - -/** - * pouchdb has many bugs and strange behaviors - * this functions takes a normal mango query - * and transforms it to one that fits for pouchdb - */ -exports.RxStoragePouchStatics = RxStoragePouchStatics; -function preparePouchDbQuery(schema, mutateableQuery) { - var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var query = (0, _util.flatClone)(mutateableQuery); - if (query.selector) { - query.selector = (0, _util.flatClone)(query.selector); - } - - /** - * because sort won't work on unused keys we have to workaround - * so we add the key to the selector if necessary - * @link https://github.com/nolanlawson/pouchdb-find/issues/204 - */ - if (query.sort) { - query.sort.forEach(function (sortPart) { - var key = Object.keys(sortPart)[0]; - var comparisonOperators = ['$gt', '$gte', '$lt', '$lte', '$eq']; - var keyUsed = query.selector && query.selector[key] && Object.keys(query.selector[key]).some(function (op) { - return comparisonOperators.includes(op); - }); - if (!keyUsed) { - var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(schema, key); - if (!schemaObj) { - throw (0, _rxError.newRxError)('QU5', { - query: query, - key: key, - schema: schema - }); - } - if (!query.selector) { - query.selector = {}; - } - if (!query.selector[key]) { - query.selector[key] = {}; - } - switch (schemaObj.type) { - case 'number': - case 'integer': - // TODO change back to -Infinity when issue resolved - // @link https://github.com/pouchdb/pouchdb/issues/6454 - // -Infinity does not work since pouchdb 6.2.0 - query.selector[key].$gt = -9999999999999999999999999999; - break; - case 'string': + toString: function toString(blobBuffer) { + /** + * in the electron-renderer we have a typed array insteaf of a blob + * so we have to transform it. + * @link https://github.com/pubkey/rxdb/issues/1371 + */ + var blobBufferType = Object.prototype.toString.call(blobBuffer); + if (blobBufferType === '[object Uint8Array]') { + blobBuffer = new Blob([blobBuffer]); + } + if (typeof blobBuffer === 'string') { + return Promise.resolve(blobBuffer); + } + return blobBuffer.text(); + }, + toBase64String: function () { + var _toBase64String = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(blobBuffer) { + var blobBufferType, arrayBuffer; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!(typeof blobBuffer === 'string')) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", blobBuffer); + case 2: /** - * strings need an empty string, see - * @link https://github.com/pubkey/rxdb/issues/585 + * in the electron-renderer we have a typed array insteaf of a blob + * so we have to transform it. + * @link https://github.com/pubkey/rxdb/issues/1371 */ - if (typeof query.selector[key] !== 'string') { - query.selector[key].$gt = ''; + blobBufferType = Object.prototype.toString.call(blobBuffer); + if (blobBufferType === '[object Uint8Array]') { + blobBuffer = new Blob([blobBuffer]); } - break; - default: - query.selector[key].$gt = null; - break; - } - } - }); - } - - // regex does not work over the primary key - if (_overwritable.overwritable.isDevMode() && query.selector && query.selector[primaryKey] && query.selector[primaryKey].$regex) { - throw (0, _rxError.newRxError)('QU4', { - path: primaryKey, - query: mutateableQuery - }); - } - - // primary-swap sorting - if (query.sort) { - var sortArray = query.sort.map(function (part) { - var _newPart; - var key = Object.keys(part)[0]; - var direction = Object.values(part)[0]; - var useKey = key === primaryKey ? '_id' : key; - var newPart = (_newPart = {}, _newPart[useKey] = direction, _newPart); - return newPart; - }); - query.sort = sortArray; - } - - // strip empty selectors - Object.entries((0, _util.ensureNotFalsy)(query.selector)).forEach(function (_ref2) { - var k = _ref2[0], - v = _ref2[1]; - if (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 0) { - delete (0, _util.ensureNotFalsy)(query.selector)[k]; + _context2.next = 6; + return fetch(URL.createObjectURL(blobBuffer)).then(function (res) { + return res.arrayBuffer(); + }); + case 6: + arrayBuffer = _context2.sent; + return _context2.abrupt("return", (0, _utilsBase.arrayBufferToBase64)(arrayBuffer)); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function toBase64String(_x3) { + return _toBase64String.apply(this, arguments); } - }); - - /** - * Set use_index - * @link https://pouchdb.com/guides/mango-queries.html#use_index - */ - if (mutateableQuery.index) { - var indexMaybeArray = mutateableQuery.index; - var indexArray = (0, _util.isMaybeReadonlyArray)(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; - indexArray = indexArray.map(function (str) { - if (str === primaryKey) { - return '_id'; - } else { - return str; - } - }); - var indexName = (0, _pouchdbHelper.getPouchIndexDesignDocNameByIndex)(indexArray); - delete query.index; - query.use_index = indexName; + return toBase64String; + }(), + size: function size(blobBuffer) { + return blobBuffer.size; } - query.selector = (0, _pouchdbHelper.primarySwapPouchDbQuerySelector)(query.selector, primaryKey); - return query; -} +}; +exports.blobBufferUtil = blobBufferUtil; -},{"../../overwritable":8,"../../rx-error":35,"../../rx-schema-helper":38,"../../util":44,"./pouchdb-helper":16,"pouchdb-selector-core":439}],16:[function(require,module,exports){ -(function (Buffer){(function (){ +}).call(this)}).call(this,require("buffer").Buffer) +},{"./utils-base64":14,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"buffer":102}],16:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.RX_STORAGE_NAME_POUCHDB = exports.RXDB_POUCH_DELETED_FLAG = exports.POUCHDB_META_FIELDNAME = exports.POUCHDB_LOCAL_PREFIX_LENGTH = exports.POUCHDB_LOCAL_PREFIX = exports.POUCHDB_DESIGN_PREFIX = exports.POUCHDB_CHECKPOINT_SCHEMA = exports.OPEN_POUCH_INSTANCES = exports.OPEN_POUCHDB_STORAGE_INSTANCES = void 0; -exports.getEventKey = getEventKey; -exports.getPouchIndexDesignDocNameByIndex = getPouchIndexDesignDocNameByIndex; -exports.hashAttachmentData = hashAttachmentData; -exports.openPouchId = openPouchId; -exports.pouchChangeRowToChangeEvent = pouchChangeRowToChangeEvent; -exports.pouchChangeRowToChangeStreamEvent = pouchChangeRowToChangeStreamEvent; -exports.pouchDocumentDataToRxDocumentData = pouchDocumentDataToRxDocumentData; -exports.pouchHash = pouchHash; -exports.pouchStripLocalFlagFromPrimary = pouchStripLocalFlagFromPrimary; -exports.pouchSwapIdToPrimary = pouchSwapIdToPrimary; -exports.pouchSwapIdToPrimaryString = pouchSwapIdToPrimaryString; -exports.pouchSwapPrimaryToId = pouchSwapPrimaryToId; -exports.primarySwapPouchDbQuerySelector = primarySwapPouchDbQuerySelector; -exports.rxDocumentDataToPouchDocumentData = rxDocumentDataToPouchDocumentData; -exports.writeAttachmentsToAttachments = void 0; -var _pouchdbMd = require("pouchdb-md5"); -var _util = require("../../util"); -var _rxError = require("../../rx-error"); -var _rxStorageHelper = require("../../rx-storage-helper"); -var writeAttachmentsToAttachments = function writeAttachmentsToAttachments(attachments) { - try { - if (!attachments) { - return Promise.resolve({}); - } - var ret = {}; - return Promise.resolve(Promise.all(Object.entries(attachments).map(function (_ref4) { - try { - var key = _ref4[0], - obj = _ref4[1]; - if (!obj.type) { - throw (0, _rxError.newRxError)('SNH', { - args: { - obj: obj - } - }); - } - /** - * Is write attachment, - * so we have to remove the data to have a - * non-write attachment. - */ - var _temp3 = function () { - if (obj.data) { - var _temp2 = function _temp2(dataAsBase64String) { - return Promise.resolve(hashAttachmentData(dataAsBase64String)).then(function (hash) { - var length = (0, _rxStorageHelper.getAttachmentSize)(dataAsBase64String); - ret[key] = { - digest: 'md5-' + hash, - length: length, - type: _asWrite.type - }; - }); - }; - var _asWrite = obj; - var data = _asWrite.data; - var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(data); - if (isBuffer) { - data = new Blob([data]); - } - var _temp = typeof data === 'string'; - return _temp ? _temp2(data) : Promise.resolve(_util.blobBufferUtil.toBase64String(data)).then(_temp2); - } else { - ret[key] = obj; - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.writeAttachmentsToAttachments = writeAttachmentsToAttachments; -var RX_STORAGE_NAME_POUCHDB = 'pouchdb'; - -/** - * Used to check in tests if all instances have been cleaned up. - */ -exports.RX_STORAGE_NAME_POUCHDB = RX_STORAGE_NAME_POUCHDB; -var OPEN_POUCHDB_STORAGE_INSTANCES = new Set(); - +exports.RX_META_LWT_MINIMUM = void 0; +exports.areRxDocumentArraysEqual = areRxDocumentArraysEqual; +exports.getDefaultRevision = getDefaultRevision; +exports.getDefaultRxDocumentMeta = getDefaultRxDocumentMeta; +exports.getSortDocumentsByLastWriteTimeComparator = getSortDocumentsByLastWriteTimeComparator; +exports.sortDocumentsByLastWriteTime = sortDocumentsByLastWriteTime; +exports.stripMetaDataFromDocument = stripMetaDataFromDocument; /** - * All open PouchDB instances are stored here - * so that we can find them again when needed in the internals. + * We use 1 as minimum so that the value is never falsy. + * This const is used in several places because querying + * with a value lower then the minimum could give false results. */ -exports.OPEN_POUCHDB_STORAGE_INSTANCES = OPEN_POUCHDB_STORAGE_INSTANCES; -var OPEN_POUCH_INSTANCES = new Map(); -exports.OPEN_POUCH_INSTANCES = OPEN_POUCH_INSTANCES; -function openPouchId(databaseInstanceToken, databaseName, collectionName, schemaVersion) { - return [databaseInstanceToken, databaseName, collectionName, schemaVersion + ''].join('||'); +var RX_META_LWT_MINIMUM = 1; +exports.RX_META_LWT_MINIMUM = RX_META_LWT_MINIMUM; +function getDefaultRxDocumentMeta() { + return { + /** + * Set this to 1 to not waste performance + * while calling new Date().. + * The storage wrappers will anyway update + * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage() + */ + lwt: RX_META_LWT_MINIMUM + }; } /** - * prefix of local pouchdb documents - */ -var POUCHDB_LOCAL_PREFIX = '_local/'; -exports.POUCHDB_LOCAL_PREFIX = POUCHDB_LOCAL_PREFIX; -var POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX.length; - -/** - * Pouchdb stores indexes as design documents, - * we have to filter them out and not return the - * design documents to the outside. + * Returns a revision that is not valid. + * Use this to have correct typings + * while the storage wrapper anyway will overwrite the revision. */ -exports.POUCHDB_LOCAL_PREFIX_LENGTH = POUCHDB_LOCAL_PREFIX_LENGTH; -var POUCHDB_DESIGN_PREFIX = '_design/'; +function getDefaultRevision() { + /** + * Use a non-valid revision format, + * to ensure that the RxStorage will throw + * when the revision is not replaced downstream. + */ + return ''; +} +function stripMetaDataFromDocument(docData) { + return Object.assign({}, docData, { + _meta: undefined, + _deleted: undefined, + _rev: undefined + }); +} /** - * PouchDB does not allow to add custom properties - * that start with lodash like RxDB's _meta field. - * So we have to map this field into a non-lodashed field. + * Faster way to check the equalness of document lists + * compared to doing a deep-equal. + * Here we only check the ids and revisions. */ -exports.POUCHDB_DESIGN_PREFIX = POUCHDB_DESIGN_PREFIX; -var POUCHDB_META_FIELDNAME = 'rxdbMeta'; -exports.POUCHDB_META_FIELDNAME = POUCHDB_META_FIELDNAME; -function pouchSwapIdToPrimary(primaryKey, docData) { - if (primaryKey === '_id' || docData[primaryKey]) { - return docData; - } - docData = (0, _util.flatClone)(docData); - docData[primaryKey] = docData._id; - delete docData._id; - return docData; -} -function pouchSwapIdToPrimaryString(primaryKey, str) { - if (str === '_id') { - return primaryKey; - } else { - return str; +function areRxDocumentArraysEqual(primaryPath, ar1, ar2) { + if (ar1.length !== ar2.length) { + return false; } -} -function pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc) { - var useDoc = pouchSwapIdToPrimary(primaryKey, pouchDoc); - - // always flat clone because we mutate the _attachments property. - useDoc = (0, _util.flatClone)(useDoc); - delete useDoc._revisions; - - // ensure deleted flag is set. - useDoc._deleted = !!useDoc._deleted; - useDoc._attachments = {}; - if (pouchDoc._attachments) { - Object.entries(pouchDoc._attachments).forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; - if (value.data) { - useDoc._attachments[key] = { - data: value.data, - type: value.type ? value.type : value.content_type - }; - } else { - useDoc._attachments[key] = { - digest: value.digest, - // TODO why do we need to access value.type? - type: value.type ? value.type : value.content_type, - length: value.length - }; - } - }); + var i = 0; + var len = ar1.length; + while (i < len) { + var row1 = ar1[i]; + var row2 = ar2[i]; + i++; + if (row1._rev !== row2._rev || row1[primaryPath] !== row2[primaryPath]) { + return false; + } } - useDoc._meta = useDoc[POUCHDB_META_FIELDNAME]; - delete useDoc[POUCHDB_META_FIELDNAME]; - return useDoc; + return true; } -function rxDocumentDataToPouchDocumentData(primaryKey, doc) { - var pouchDoc = pouchSwapPrimaryToId(primaryKey, doc); - - // always flat clone because we mutate the _attachments property. - pouchDoc = (0, _util.flatClone)(pouchDoc); - pouchDoc._attachments = {}; - if (doc._attachments) { - Object.entries(doc._attachments).forEach(function (_ref2) { - var key = _ref2[0], - value = _ref2[1]; - var useValue = value; - if (useValue.data) { - pouchDoc._attachments[key] = { - data: useValue.data, - content_type: useValue.type - }; +function getSortDocumentsByLastWriteTimeComparator(primaryPath) { + return function (a, b) { + if (a._meta.lwt === b._meta.lwt) { + if (b[primaryPath] < a[primaryPath]) { + return 1; } else { - pouchDoc._attachments[key] = { - digest: useValue.digest, - content_type: useValue.type, - length: useValue.length, - stub: true - }; + return -1; } - }); - } - pouchDoc[POUCHDB_META_FIELDNAME] = pouchDoc._meta; - delete pouchDoc._meta; - return pouchDoc; + } else { + return a._meta.lwt - b._meta.lwt; + } + }; } - -/** - * Swaps the primaryKey of the document - * to the _id property. - */ -function pouchSwapPrimaryToId(primaryKey, docData) { - // optimisation shortcut - if (primaryKey === '_id') { - return docData; - } - var idValue = docData[primaryKey]; - var ret = (0, _util.flatClone)(docData); - delete ret[primaryKey]; - ret._id = idValue; - return ret; +function sortDocumentsByLastWriteTime(primaryPath, docs) { + return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath)); } +},{}],17:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.errorToPlainJson = errorToPlainJson; +exports.pluginMissing = pluginMissing; +var _utilsString = require("./utils-string"); /** - * in: '_local/foobar' - * out: 'foobar' + * Returns an error that indicates that a plugin is missing + * We do not throw a RxError because this should not be handled + * programmatically but by using the correct import */ -function pouchStripLocalFlagFromPrimary(str) { - return str.substring(POUCHDB_LOCAL_PREFIX.length); -} -function getEventKey(pouchDBInstance, primary, change) { - var useRev = change.doc ? change.doc._rev : change.previous._rev; - var eventKey = pouchDBInstance.name + '|' + primary + '|' + change.operation + '|' + useRev; - return eventKey; -} -function pouchChangeRowToChangeEvent(primaryKey, pouchDoc) { - if (!pouchDoc) { - throw (0, _rxError.newRxError)('SNH', { - args: { - pouchDoc: pouchDoc - } - }); - } - var id = pouchDoc._id; - var doc = pouchDocumentDataToRxDocumentData(primaryKey, pouchDoc); - var revHeight = doc._rev ? (0, _util.getHeightOfRevision)(doc._rev) : 1; - if (pouchDoc._deleted) { - return { - operation: 'DELETE', - id: id, - doc: null, - previous: doc - }; - } else if (revHeight === 1) { - return { - operation: 'INSERT', - id: id, - doc: doc, - previous: null - }; - } else { - return { - operation: 'UPDATE', - id: id, - doc: doc, - previous: 'UNKNOWN' - }; - } +function pluginMissing(pluginKey) { + var keyParts = pluginKey.split('-'); + var pluginName = 'RxDB'; + keyParts.forEach(function (part) { + pluginName += (0, _utilsString.ucfirst)(part); + }); + pluginName += 'Plugin'; + return new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { " + pluginName + " } from 'rxdb/plugins/" + pluginKey + "';\n addRxPlugin(" + pluginName + ");\n "); } -function pouchChangeRowToChangeStreamEvent(primaryKey, pouchRow) { - var doc = pouchRow.doc; - if (!doc) { - throw (0, _rxError.newRxError)('SNH', { - args: { - pouchRow: pouchRow - } - }); - } - var revHeight = (0, _util.getHeightOfRevision)(doc._rev); - if (pouchRow.deleted) { - var previousDoc = (0, _util.flatClone)(pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc)); - var ev = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'DELETE', - doc: null, - previous: previousDoc - }; - return ev; - } else if (revHeight === 1) { - var _ev = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'INSERT', - doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), - previous: null - }; - return _ev; - } else { - var _ev2 = { - sequence: pouchRow.seq, - id: pouchRow.id, - operation: 'UPDATE', - doc: pouchDocumentDataToRxDocumentData(primaryKey, pouchRow.doc), - previous: 'UNKNOWN' - }; - return _ev2; - } +function errorToPlainJson(err) { + var ret = { + name: err.name, + message: err.message, + rxdb: err.rxdb, + parameters: err.parameters, + code: err.code, + // stack must be last to make it easier to read the json in a console. + stack: err.stack + }; + return ret; } +},{"./utils-string":23}],18:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.defaultHashFunction = defaultHashFunction; +exports.fastUnsecureHash = fastUnsecureHash; /** - * Runs a primary swap with transform all custom primaryKey occurrences - * into '_id' - * @recursive + * This is a very fast hash method + * but it is not cryptographically secure. + * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int). + * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery + * @return a string as hash-result */ -function primarySwapPouchDbQuerySelector(selector, primaryKey) { - if (primaryKey === '_id') { - return selector; - } - if (Array.isArray(selector)) { - return selector.map(function (item) { - return primarySwapPouchDbQuerySelector(item, primaryKey); - }); - } else if (typeof selector === 'object') { - var ret = {}; - Object.entries(selector).forEach(function (_ref3) { - var k = _ref3[0], - v = _ref3[1]; - if (k === primaryKey) { - ret._id = v; - } else { - if (k.startsWith('$')) { - ret[k] = primarySwapPouchDbQuerySelector(v, primaryKey); - } else { - ret[k] = v; - } - } - }); - return ret; +function fastUnsecureHash(inputString, +// used to test the polyfill +doNotUseTextEncoder) { + var hashValue = 0, + i, + chr, + len; + + /** + * For better performance we first transform all + * chars into their ascii numbers at once. + * + * This is what makes the murmurhash implementation such fast. + * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4 + */ + var encoded; + + /** + * All modern browsers support the TextEncoder + * @link https://caniuse.com/textencoder + * But to make RxDB work in other JavaScript runtimes, + * like when using it in flutter or QuickJS, we need to + * make it work even when there is no TextEncoder. + */ + if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) { + encoded = new TextEncoder().encode(inputString); } else { - return selector; + encoded = []; + for (var j = 0; j < inputString.length; j++) { + encoded.push(inputString.charCodeAt(j)); + } + } + for (i = 0, len = inputString.length; i < len; i++) { + chr = encoded[i]; + hashValue = (hashValue << 5) - hashValue + chr; + hashValue |= 0; // Convert to 32bit integer } -} -function pouchHash(data) { - return new Promise(function (res) { - (0, _pouchdbMd.binaryMd5)(data, function (digest) { - res(digest); - }); - }); -} -/** - * Runs the same hashing as PouchDB would do. - * Used to pre-calculated the hashes which is required to emit the correct events. - */ -function hashAttachmentData(attachmentBase64String) { - var binary; - try { - binary = atob(attachmentBase64String); - } catch (err) { - console.log('hashAttachmentData() could not run b64DecodeUnicode() on ' + attachmentBase64String); - throw err; + if (hashValue < 0) { + hashValue = hashValue * -1; } - return pouchHash(binary); -} -function getPouchIndexDesignDocNameByIndex(index) { - var indexName = 'idx-rxdb-index-' + index.join(','); - return indexName; + + /** + * To make the output smaller + * but still have it to represent the same value, + * we use the biggest radix of 36 instead of just + * transforming it into a hex string. + */ + return hashValue.toString(36); } /** - * PouchDB has not way to read deleted local documents - * out of the database. - * So instead of deleting them, we set a custom deleted flag. + * Default hash method used to create revision hashes + * that do not have to be cryptographically secure. + * IMPORTANT: Changing the default hashing method + * requires a BREAKING change! */ -var RXDB_POUCH_DELETED_FLAG = 'rxdb-pouch-deleted'; -exports.RXDB_POUCH_DELETED_FLAG = RXDB_POUCH_DELETED_FLAG; -var POUCHDB_CHECKPOINT_SCHEMA = { - type: 'object', - properties: { - sequence: { - type: 'number' - } - }, - required: ['sequence'], - additionalProperties: false -}; -exports.POUCHDB_CHECKPOINT_SCHEMA = POUCHDB_CHECKPOINT_SCHEMA; +function defaultHashFunction(input) { + return fastUnsecureHash(input); +} -}).call(this)}).call(this,require("buffer").Buffer) -},{"../../rx-error":35,"../../rx-storage-helper":40,"../../util":44,"buffer":96,"pouchdb-md5":437}],17:[function(require,module,exports){ -(function (Buffer){(function (){ +},{}],19:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.RxStorageInstancePouch = void 0; -var _obliviousSet = require("oblivious-set"); -var _rxjs = require("rxjs"); -var _rxError = require("../../rx-error"); -var _pouchdbHelper = require("./pouchdb-helper"); -var _util = require("../../util"); -var _customEventsPlugin = require("./custom-events-plugin"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); +exports.clone = void 0; +exports.deepFreeze = deepFreeze; +exports.firstPropertyNameOfObject = firstPropertyNameOfObject; +exports.firstPropertyValueOfObject = firstPropertyValueOfObject; +exports.flatClone = flatClone; +exports.flattenObject = flattenObject; +exports.getFromObjectOrThrow = getFromObjectOrThrow; +exports.objectPathMonad = objectPathMonad; +exports.overwriteGetterForCaching = overwriteGetterForCaching; +exports.sortObject = sortObject; +exports.stringifyFilter = stringifyFilter; +function deepFreeze(o) { + Object.freeze(o); + Object.getOwnPropertyNames(o).forEach(function (prop) { + if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop])) { + deepFreeze(o[prop]); } - } + }); + return o; } -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } + +/** + * To get specific nested path values from objects, + * RxDB normally uses the 'object-path' npm module. + * But when performance is really relevant, this is not fast enough. + * Instead we use a monad that can prepare some stuff up front + * and we can re-use the generated function. + */ + +function objectPathMonad(objectPath) { + var split = objectPath.split('.'); + + /** + * Performance shortcut, + * if no nested path is used, + * directly return the field of the object. + */ + if (split.length === 1) { + return function (obj) { + return obj[objectPath]; }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); + return function (obj) { + var currentVal = obj; + var t = 0; + while (t < split.length) { + var subPath = split[t]; + currentVal = currentVal[subPath]; + if (typeof currentVal === 'undefined') { + return currentVal; } - } else { - _settle(pact, 1, result); + t++; } + return currentVal; + }; +} +function getFromObjectOrThrow(obj, key) { + var val = obj[key]; + if (!val) { + throw new Error('missing value from object ' + key); } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); + return val; +} + +/** + * returns a flattened object + * @link https://gist.github.com/penguinboy/762197 + */ +function flattenObject(ob) { + var toReturn = {}; + for (var i in ob) { + if (!ob.hasOwnProperty(i)) continue; + if (typeof ob[i] === 'object') { + var flatObject = flattenObject(ob[i]); + for (var x in flatObject) { + if (!flatObject.hasOwnProperty(x)) continue; + toReturn[i + '.' + x] = flatObject[x]; } } else { - _settle(pact, 1, result); + toReturn[i] = ob[i]; } } + return toReturn; } + /** - * Because we internally use the findDocumentsById() - * method, it is defined here because RxStorage wrappers - * might swap out the function. + * does a flat copy on the objects, + * is about 3 times faster then using deepClone + * @link https://jsperf.com/object-rest-spread-vs-clone/2 */ -var pouchFindDocumentsById = function pouchFindDocumentsById(instance, ids, deleted) { - try { - ensureNotClosed(instance); - var ret = {}; +function flatClone(obj) { + return Object.assign({}, obj); +} - /** - * On deleted documents, PouchDB will only return the tombstone. - * So we have to get the properties directly for each document - * with the hack of getting the changes and then make one request per document - * with the latest revision. - * TODO create an issue at pouchdb on how to get the document data of deleted documents, - * when one past revision was written via new_edits=false - * @link https://stackoverflow.com/a/63516761/3443137 - */ - if (deleted) { - instance.nonParallelQueue = instance.nonParallelQueue.then(function () { - try { - return Promise.resolve(instance.internals.pouch.changes({ - live: false, - since: 0, - doc_ids: ids, - style: 'all_docs' - })).then(function (viaChanges) { - return Promise.resolve(Promise.all(viaChanges.results.map(function (result) { - try { - return Promise.resolve(instance.internals.pouch.get(result.id, { - rev: result.changes[0].rev, - deleted: 'ok', - style: 'all_docs' - })).then(function (firstDoc) { - var useFirstDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(instance.primaryPath, firstDoc); - ret[result.id] = useFirstDoc; - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(instance.nonParallelQueue).then(function () { - return ret; - }); - } else { - instance.nonParallelQueue = instance.nonParallelQueue.then(function () { - try { - return Promise.resolve(instance.internals.pouch.allDocs({ - include_docs: true, - keys: ids - })).then(function (pouchResult) { - pouchResult.rows.filter(function (row) { - return !!row.doc; - }).forEach(function (row) { - var docData = row.doc; - docData = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(instance.primaryPath, docData); - ret[row.id] = docData; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(instance.nonParallelQueue).then(function () { - return ret; - }); - } - } catch (e) { - return Promise.reject(e); - } -}; -var lastId = 0; -var RxStorageInstancePouch = /*#__PURE__*/function () { - /** - * Some PouchDB operations give wrong results when they run in parallel. - * So we have to ensure they are queued up. - */ +/** + * @link https://stackoverflow.com/a/11509718/3443137 + */ +function firstPropertyNameOfObject(obj) { + return Object.keys(obj)[0]; +} +function firstPropertyValueOfObject(obj) { + var key = Object.keys(obj)[0]; + return obj[key]; +} - function RxStorageInstancePouch(storage, databaseName, collectionName, schema, internals, options) { - var _this = this; - this.id = lastId++; - this.changes$ = new _rxjs.Subject(); - this.subs = []; - this.closed = false; - this.nonParallelQueue = _util.PROMISE_RESOLVE_VOID; - this.storage = storage; - this.databaseName = databaseName; - this.collectionName = collectionName; - this.schema = schema; - this.internals = internals; - this.options = options; - _pouchdbHelper.OPEN_POUCHDB_STORAGE_INSTANCES.add(this); - this.primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(this.schema.primaryKey); - /** - * Instead of listening to pouch.changes, - * we have overwritten pouchdbs bulkDocs() - * and create our own event stream, this will work more reliable - * and does not mix up with write events from other sources. - */ - var emitter = (0, _customEventsPlugin.getCustomEventEmitterByPouch)(this.internals.pouch); +/** + * deep-sort an object so its attributes are in lexical order. + * Also sorts the arrays inside of the object if no-array-sort not set + */ +function sortObject(obj) { + var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (!obj) return obj; // do not sort null, false or undefined - /** - * Contains all eventIds that of emitted events, - * used because multi-instance pouchdbs often will reemit the same - * event on the other browser tab so we have to de-duplicate them. - */ - var emittedEventBulkIds = new _obliviousSet.ObliviousSet(60 * 1000); - var eventSub = emitter.subject.subscribe(function (eventBulk) { - if (eventBulk.events.length === 0 || emittedEventBulkIds.has(eventBulk.id)) { - return; - } - emittedEventBulkIds.add(eventBulk.id); - - // rewrite primaryPath of all events - eventBulk.events.forEach(function (event) { - if (event.documentData) { - event.documentData = (0, _pouchdbHelper.pouchSwapIdToPrimary)(_this.primaryPath, event.documentData); - } - if (event.previousDocumentData) { - event.previousDocumentData = (0, _pouchdbHelper.pouchSwapIdToPrimary)(_this.primaryPath, event.previousDocumentData); - } - }); - _this.changes$.next(eventBulk); + // array + if (!noArraySort && Array.isArray(obj)) { + return obj.sort(function (a, b) { + if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b); + if (typeof a === 'object') return 1;else return -1; + }).map(function (i) { + return sortObject(i, noArraySort); }); - this.subs.push(eventSub); } - var _proto = RxStorageInstancePouch.prototype; - _proto.close = function close() { - ensureNotClosed(this); - this.closed = true; - this.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - _pouchdbHelper.OPEN_POUCHDB_STORAGE_INSTANCES["delete"](this); - _pouchdbHelper.OPEN_POUCH_INSTANCES["delete"](this.internals.pouchInstanceId); - - // TODO this did not work because a closed pouchdb cannot be recreated in the same process run - // await this.internals.pouch.close(); - return _util.PROMISE_RESOLVE_VOID; - }; - _proto.remove = function remove() { - try { - var _this2 = this; - ensureNotClosed(_this2); - _this2.closed = true; - _this2.subs.forEach(function (sub) { - return sub.unsubscribe(); - }); - _pouchdbHelper.OPEN_POUCHDB_STORAGE_INSTANCES["delete"](_this2); - _pouchdbHelper.OPEN_POUCH_INSTANCES["delete"](_this2.internals.pouchInstanceId); - return Promise.resolve(_this2.internals.pouch.destroy()).then(function () {}); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.bulkWrite = function bulkWrite(documentWrites, context) { - try { - var _this3 = this; - ensureNotClosed(_this3); - if (documentWrites.length === 0) { - throw (0, _rxError.newRxError)('P2', { - args: { - documentWrites: documentWrites - } - }); - } - var writeRowById = new Map(); - var insertDocsById = new Map(); - var writeDocs = documentWrites.map(function (writeData) { - /** - * Ensure that _meta.lwt is set correctly - */ - if (writeData.document._meta.lwt < 1000 || writeData.previous && writeData.previous._meta.lwt >= writeData.document._meta.lwt) { - throw (0, _rxError.newRxError)('SNH', { - args: writeData - }); - } - /** - * Ensure that a revision exists, - * having an empty revision here would not throw - * but just not resolve forever. - */ - if (!writeData.document._rev) { - throw (0, _rxError.newRxError)('SNH', { - args: writeData - }); - } - var primary = writeData.document[_this3.primaryPath]; - writeRowById.set(primary, writeData); - var storeDocumentData = (0, _pouchdbHelper.rxDocumentDataToPouchDocumentData)(_this3.primaryPath, writeData.document); - insertDocsById.set(primary, storeDocumentData); - return storeDocumentData; - }); - var previousDocsInDb = new Map(); - var ret = { - success: {}, - error: {} - }; - _this3.nonParallelQueue = _this3.nonParallelQueue.then(function () { - try { - return Promise.resolve(_this3.internals.pouch.bulkDocs(writeDocs, { - new_edits: false, - custom: { - primaryPath: _this3.primaryPath, - writeRowById: writeRowById, - insertDocsById: insertDocsById, - previousDocsInDb: previousDocsInDb, - context: context - } - })).then(function (pouchResult) { - return Promise.all(pouchResult.map(function (resultRow) { - try { - var writeRow = (0, _util.getFromMapOrThrow)(writeRowById, resultRow.id); - var _temp3 = function () { - if (resultRow.error) { - var previousDoc = (0, _util.getFromMapOrThrow)(previousDocsInDb, resultRow.id); - var err = { - isError: true, - status: 409, - documentId: resultRow.id, - writeRow: writeRow, - documentInDb: (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(_this3.primaryPath, previousDoc) - }; - ret.error[resultRow.id] = err; - } else { - var _temp2 = function _temp2() { - ret.success[resultRow.id] = _pushObj; - }; - var _pushObj = (0, _util.flatClone)(writeRow.document); - _pushObj = (0, _pouchdbHelper.pouchSwapIdToPrimary)(_this3.primaryPath, _pushObj); - _pushObj._rev = resultRow.rev; - - // replace the inserted attachments with their diggest - _pushObj._attachments = {}; - var _temp = function () { - if (!writeRow.document._attachments) { - writeRow.document._attachments = {}; - } else { - return Promise.resolve((0, _pouchdbHelper.writeAttachmentsToAttachments)(writeRow.document._attachments)).then(function (_writeAttachmentsToAt) { - _pushObj._attachments = _writeAttachmentsToAt; - }); - } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - })); - }); - } catch (e) { - return Promise.reject(e); - } - }); - return Promise.resolve(_this3.nonParallelQueue).then(function () { - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.query = function query(preparedQuery) { - try { - var _this4 = this; - ensureNotClosed(_this4); - return Promise.resolve(_this4.internals.pouch.find(preparedQuery)).then(function (findResult) { - var ret = { - documents: findResult.docs.map(function (pouchDoc) { - var useDoc = (0, _pouchdbHelper.pouchDocumentDataToRxDocumentData)(_this4.primaryPath, pouchDoc); - return useDoc; - }) - }; - return ret; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.count = function count(preparedQuery) { - try { - var _this5 = this; - /** - * There is no count method in PouchDB, - * so we have to run a normal query and use the result length. - */ - return Promise.resolve(_this5.query(preparedQuery)).then(function (result) { - return { - count: result.documents.length, - mode: 'fast' - }; - }); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.getAttachmentData = function getAttachmentData(documentId, attachmentId) { - try { - var _this6 = this; - ensureNotClosed(_this6); - return Promise.resolve(_this6.internals.pouch.getAttachment(documentId, attachmentId)).then(function (attachmentData) { - /** - * In Node.js, PouchDB works with Buffers because it is old and Node.js did - * not support Blob at the time is was coded. - * So here we have to transform the Buffer to a Blob. - */ - var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(attachmentData); - if (isBuffer) { - attachmentData = new Blob([attachmentData]); - } - return Promise.resolve(_util.blobBufferUtil.toBase64String(attachmentData)); - }); - } catch (e) { - return Promise.reject(e); + // object + // array is also of type object + if (typeof obj === 'object' && !Array.isArray(obj)) { + if (obj instanceof RegExp) { + return obj; } - }; - _proto.findDocumentsById = function findDocumentsById(ids, deleted) { - return pouchFindDocumentsById(this, ids, deleted); - }; - _proto.changeStream = function changeStream() { - ensureNotClosed(this); - return this.changes$.asObservable(); - }; - _proto.cleanup = function cleanup(_minimumDeletedTime) { - ensureNotClosed(this); - /** - * PouchDB does not support purging documents. - * So instead we run a compaction that might at least help a bit - * in freeing up disc space. - * @link https://github.com/pouchdb/pouchdb/issues/802 - */ - return this.internals.pouch.compact().then(function () { - return true; + var out = {}; + Object.keys(obj).sort(function (a, b) { + return a.localeCompare(b); + }).forEach(function (key) { + out[key] = sortObject(obj[key], noArraySort); }); - }; - _proto.getChangedDocumentsSince = function getChangedDocumentsSince(limit, checkpoint) { - try { - var _temp5 = function _temp5() { - return Promise.resolve(pouchFindDocumentsById(_this7, changedDocuments.map(function (o) { - return o.id; - }), true)).then(function (documentsData) { - if (Object.keys(documentsData).length > 0 && checkpoint && checkpoint.sequence === lastSequence) { - /** - * When documents are returned, it makes no sense - * if the sequence is equal to the one given at the checkpoint. - */ - throw new Error('same sequence'); - } - var lastRow = (0, _util.lastOfArray)(changedDocuments); - var documents = changedDocuments.map(function (changeRow) { - return (0, _util.getFromObjectOrThrow)(documentsData, changeRow.id); - }); - return { - documents: documents, - checkpoint: lastRow ? { - sequence: lastRow.sequence - } : checkpoint ? checkpoint : { - sequence: -1 - } - }; - }); - }; - var _this7 = this; - ensureNotClosed(_this7); - if (!limit || typeof limit !== 'number') { - throw new Error('wrong limit'); - } - var pouchChangesOpts = { - live: false, - limit: limit, - include_docs: false, - since: checkpoint ? checkpoint.sequence : 0, - descending: false - }; - var lastSequence = 0; - var first = true; - var skippedDesignDocuments = 0; - var changedDocuments = []; - /** - * Because PouchDB also returns changes of _design documents, - * we have to fill up the results with more changes if this happens. - */ - var _temp4 = _for(function () { - return !!first || skippedDesignDocuments > 0; - }, void 0, function () { - first = false; - skippedDesignDocuments = 0; - return Promise.resolve(_this7.internals.pouch.changes(pouchChangesOpts)).then(function (pouchResults) { - var addChangedDocuments = pouchResults.results.filter(function (row) { - var isDesignDoc = row.id.startsWith(_pouchdbHelper.POUCHDB_DESIGN_PREFIX); - if (isDesignDoc) { - skippedDesignDocuments = skippedDesignDocuments + 1; - return false; - } else { - return true; - } - }).map(function (row) { - return { - id: row.id, - sequence: row.seq - }; - }); - changedDocuments = changedDocuments.concat(addChangedDocuments); - lastSequence = pouchResults.last_seq; - - // modify pouch options for next run of pouch.changes() - pouchChangesOpts.since = lastSequence; - pouchChangesOpts.limit = skippedDesignDocuments; - }); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.conflictResultionTasks = function conflictResultionTasks() { - return new _rxjs.Subject(); - }; - _proto.resolveConflictResultionTask = function resolveConflictResultionTask(_taskSolution) { - return Promise.resolve(); - }; - return RxStorageInstancePouch; -}(); -exports.RxStorageInstancePouch = RxStorageInstancePouch; -function ensureNotClosed(instance) { - if (instance.closed) { - throw new Error('RxStorageInstancePouch is closed ' + instance.databaseName + '-' + instance.collectionName); + return out; } -} -}).call(this)}).call(this,require("buffer").Buffer) -},{"../../rx-error":35,"../../rx-schema-helper":38,"../../util":44,"./custom-events-plugin":12,"./pouchdb-helper":16,"buffer":96,"oblivious-set":422,"rxjs":458}],18:[function(require,module,exports){ -"use strict"; + // everything else + return obj; +} -var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RxStoragePouch = void 0; -exports.checkPouchAdapter = checkPouchAdapter; -exports.createIndexesOnPouch = void 0; -exports.getPouchDBOfRxCollection = getPouchDBOfRxCollection; -exports.getPouchLocation = getPouchLocation; -exports.getRxStoragePouch = getRxStoragePouch; -var _util = require("../../util"); -var _pouchDb = require("./pouch-db"); -var _rxError = require("../../rx-error"); -var _rxStorageInstancePouch = require("./rx-storage-instance-pouch"); -var _pouchdbHelper = require("./pouchdb-helper"); -var _pouchdbFind = _interopRequireDefault(require("pouchdb-find")); -var _pouchStatics = require("./pouch-statics"); -var _rxSchemaHelper = require("../../rx-schema-helper"); -var _customEventsPlugin = require("./custom-events-plugin"); -var _rxStorageMultiinstance = require("../../rx-storage-multiinstance"); -var _rxStorageHelper = require("../../rx-storage-helper"); /** - * Creates the indexes of the schema inside of the pouchdb instance. - * Will skip indexes that already exist. + * Deep clone a plain json object. + * Does not work with recursive stuff + * or non-plain-json. + * IMPORANT: Performance of this is very important, + * do not change it without running performance tests! + * + * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts */ -var createIndexesOnPouch = function createIndexesOnPouch(pouch, schema) { - try { - if (!schema.indexes) { - return Promise.resolve(); +function deepClone(src) { + if (!src) { + return src; + } + if (src === null || typeof src !== 'object') { + return src; + } + if (Array.isArray(src)) { + var ret = new Array(src.length); + var i = ret.length; + while (i--) { + ret[i] = deepClone(src[i]); } - var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - return Promise.resolve(pouch.getIndexes()).then(function (before) { - var existingIndexes = new Set(before.indexes.map(function (idx) { - return idx.name; - })); - return Promise.resolve(Promise.all(schema.indexes.map(function (indexMaybeArray) { - var indexArray = (0, _util.isMaybeReadonlyArray)(indexMaybeArray) ? indexMaybeArray : [indexMaybeArray]; - - /** - * replace primary key with _id - * because that is the enforced primary key on pouchdb. - */ - indexArray = indexArray.map(function (key) { - if (key === primaryKey) { - return '_id'; - } else { - return key; - } - }); - var indexName = (0, _pouchdbHelper.getPouchIndexDesignDocNameByIndex)(indexArray); - if (existingIndexes.has(indexName)) { - // index already exists - return; - } - - /** - * TODO we might have even better performance by doing a pouch.bulkDocs() - * on index creation - */ - return pouch.createIndex({ - name: indexName, - ddoc: indexName, - index: { - fields: indexArray - } - }); - }))).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + return ret; } -}; -/** - * returns the pouchdb-database-name - */ -exports.createIndexesOnPouch = createIndexesOnPouch; -var RxStoragePouch = /*#__PURE__*/function () { - function RxStoragePouch(adapter) { - var pouchSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - this.name = _pouchdbHelper.RX_STORAGE_NAME_POUCHDB; - this.statics = _pouchStatics.RxStoragePouchStatics; - this.adapter = adapter; - this.pouchSettings = pouchSettings; - checkPouchAdapter(adapter); - } - var _proto = RxStoragePouch.prototype; - _proto.createPouch = function createPouch(location, options) { - var pouchDbParameters = { - location: location, - adapter: (0, _util.adapterObject)(this.adapter), - settings: options - }; - var pouchDBOptions = Object.assign({}, pouchDbParameters.adapter, this.pouchSettings, pouchDbParameters.settings); - var pouch = new _pouchDb.PouchDB(pouchDbParameters.location, pouchDBOptions); - - /** - * In the past we found some errors where the PouchDB is not directly usable - * so we we had to call .info() first to ensure it can be used. - * I commented this out for now to get faster database/collection creation. - * We might have to add this again if something fails. - */ - // await pouch.info(); - - return Promise.resolve(pouch); - }; - _proto.createStorageInstance = function createStorageInstance(params) { - try { - var _this = this; - (0, _rxStorageHelper.ensureRxStorageInstanceParamsAreCorrect)(params); - var pouchLocation = getPouchLocation(params.databaseName, params.collectionName, params.schema.version); - return Promise.resolve(_this.createPouch(pouchLocation, params.options)).then(function (pouch) { - return Promise.resolve(createIndexesOnPouch(pouch, params.schema)).then(function () { - var pouchInstanceId = (0, _pouchdbHelper.openPouchId)(params.databaseInstanceToken, params.databaseName, params.collectionName, params.schema.version); - var instance = new _rxStorageInstancePouch.RxStorageInstancePouch(_this, params.databaseName, params.collectionName, params.schema, { - pouch: pouch, - pouchInstanceId: pouchInstanceId - }, params.options); - _pouchdbHelper.OPEN_POUCH_INSTANCES.set(pouchInstanceId, pouch); - (0, _rxStorageMultiinstance.addRxStorageMultiInstanceSupport)(_pouchdbHelper.RX_STORAGE_NAME_POUCHDB, params, instance); - return instance; - }); - }); - } catch (e) { - return Promise.reject(e); + var dest = {}; + // eslint-disable-next-line guard-for-in + for (var key in src) { + // TODO we should not be required to deep clone RegEx objects, + // this must be fixed in RxDB. + if (src[key] instanceof RegExp) { + dest[key] = src[key]; + } else { + dest[key] = deepClone(src[key]); } - }; - return RxStoragePouch; -}(); + } + return dest; +} +var clone = deepClone; + /** - * Checks if all is ok with the given adapter, - * else throws an error. + * overwrites the getter with the actual value + * Mostly used for caching stuff on the first run */ -exports.RxStoragePouch = RxStoragePouch; -function checkPouchAdapter(adapter) { - if (typeof adapter === 'string') { - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters[adapter]) { - throw (0, _rxError.newRxError)('DB9', { - adapter: adapter - }); - } - } else { - (0, _pouchDb.isLevelDown)(adapter); - if (!_pouchDb.PouchDB.adapters || !_pouchDb.PouchDB.adapters.leveldb) { - throw (0, _rxError.newRxError)('DB10', { - adapter: adapter - }); +exports.clone = clone; +function overwriteGetterForCaching(obj, getterName, value) { + Object.defineProperty(obj, getterName, { + get: function get() { + return value; } - } -} -function getPouchLocation(dbName, collectionName, schemaVersion) { - var prefix = dbName + '-rxdb-' + schemaVersion + '-'; - if (!collectionName.includes('/')) { - return prefix + collectionName; - } else { - // if collectionName is a path, we have to prefix the last part only - var split = collectionName.split('/'); - var last = split.pop(); - var ret = split.join('/'); - ret += '/' + prefix + last; - return ret; - } -} -function getPouchDBOfRxCollection(collection) { - var id = (0, _pouchdbHelper.openPouchId)(collection.database.token, collection.database.name, collection.name, collection.schema.version); - var pouch = (0, _util.getFromMapOrThrow)(_pouchdbHelper.OPEN_POUCH_INSTANCES, id); - return pouch; + }); + return value; } -var addedRxDBPouchPlugins = false; /** - * @deprecated PouchDB RxStorage is deprecated, see - * @link https://rxdb.info/questions-answers.html#why-is-the-pouchdb-rxstorage-deprecated + * used to JSON.stringify() objects that contain a regex + * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs! */ -function getRxStoragePouch(adapter, pouchSettings) { - if (!addedRxDBPouchPlugins) { - addedRxDBPouchPlugins = true; - (0, _pouchDb.addPouchPlugin)(_pouchdbFind["default"]); - (0, _customEventsPlugin.addCustomEventsPluginToPouch)(); - } - if (!adapter) { - throw new Error('adapter missing'); +function stringifyFilter(key, value) { + if (value instanceof RegExp) { + return value.toString(); } - var storage = new RxStoragePouch(adapter, pouchSettings); - return storage; + return value; } -},{"../../rx-error":35,"../../rx-schema-helper":38,"../../rx-storage-helper":40,"../../rx-storage-multiinstance":41,"../../util":44,"./custom-events-plugin":12,"./pouch-db":14,"./pouch-statics":15,"./pouchdb-helper":16,"./rx-storage-instance-pouch":17,"@babel/runtime/helpers/interopRequireDefault":51,"pouchdb-find":434}],19:[function(require,module,exports){ +},{}],20:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.QueryCache = exports.DEFAULT_UNEXECUTED_LIFETME = exports.DEFAULT_TRY_TO_KEEP_MAX = exports.COLLECTIONS_WITH_RUNNING_CLEANUP = void 0; -exports.countRxQuerySubscribers = countRxQuerySubscribers; -exports.createQueryCache = createQueryCache; -exports.defaultCacheReplacementPolicyMonad = exports.defaultCacheReplacementPolicy = void 0; -exports.triggerCacheReplacement = triggerCacheReplacement; -exports.uncacheRxQuery = uncacheRxQuery; -var _util = require("./util"); -/** - * the query-cache makes sure that on every query-state, exactly one instance can exist - * if you use the same mango-query more then once, it will reuse the first RxQuery - */ -var QueryCache = /*#__PURE__*/function () { - function QueryCache() { - this._map = new Map(); - } - var _proto = QueryCache.prototype; - /** - * check if an equal query is in the cache, - * if true, return the cached one, - * if false, save the given one and return it - */ - _proto.getByQuery = function getByQuery(rxQuery) { - var stringRep = rxQuery.toString(); - if (!this._map.has(stringRep)) { - this._map.set(stringRep, rxQuery); - } - return this._map.get(stringRep); - }; - return QueryCache; -}(); -exports.QueryCache = QueryCache; -function createQueryCache() { - return new QueryCache(); +exports.RXJS_SHARE_REPLAY_DEFAULTS = void 0; +exports.ensureInteger = ensureInteger; +exports.ensureNotFalsy = ensureNotFalsy; +exports.getFromMapOrFill = getFromMapOrFill; +exports.getFromMapOrThrow = getFromMapOrThrow; +exports.runXTimes = runXTimes; +function runXTimes(xTimes, fn) { + new Array(xTimes).fill(0).forEach(function (_v, idx) { + return fn(idx); + }); } -function uncacheRxQuery(queryCache, rxQuery) { - rxQuery.uncached = true; - var stringRep = rxQuery.toString(); - queryCache._map["delete"](stringRep); +function ensureNotFalsy(obj) { + if (!obj) { + throw new Error('ensureNotFalsy() is falsy'); + } + return obj; } -function countRxQuerySubscribers(rxQuery) { - return rxQuery.refCount$.observers.length; +function ensureInteger(obj) { + if (!Number.isInteger(obj)) { + throw new Error('ensureInteger() is falsy'); + } + return obj; +} +function getFromMapOrThrow(map, key) { + var val = map.get(key); + if (typeof val === 'undefined') { + throw new Error('missing value from map ' + key); + } + return val; +} +function getFromMapOrFill(map, key, fillerFunction) { + var value = map.get(key); + if (!value) { + value = fillerFunction(); + map.set(key, value); + } + return value; } -var DEFAULT_TRY_TO_KEEP_MAX = 100; -exports.DEFAULT_TRY_TO_KEEP_MAX = DEFAULT_TRY_TO_KEEP_MAX; -var DEFAULT_UNEXECUTED_LIFETME = 30 * 1000; /** - * The default cache replacement policy - * See docs-src/query-cache.md to learn how it should work. - * Notice that this runs often and should block the cpu as less as possible - * This is a monad which makes it easier to unit test + * Using shareReplay() without settings will not unsubscribe + * if there are no more subscribers. + * So we use these defaults. + * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95 */ -exports.DEFAULT_UNEXECUTED_LIFETME = DEFAULT_UNEXECUTED_LIFETME; -var defaultCacheReplacementPolicyMonad = function defaultCacheReplacementPolicyMonad(tryToKeepMax, unExecutedLifetime) { - return function (_collection, queryCache) { - if (queryCache._map.size < tryToKeepMax) { - return; - } - var minUnExecutedLifetime = (0, _util.now)() - unExecutedLifetime; - var maybeUncash = []; - var queriesInCache = Array.from(queryCache._map.values()); - for (var _i = 0, _queriesInCache = queriesInCache; _i < _queriesInCache.length; _i++) { - var rxQuery = _queriesInCache[_i]; - // filter out queries with subscribers - if (countRxQuerySubscribers(rxQuery) > 0) { - continue; - } - // directly uncache queries that never executed and are older then unExecutedLifetime - if (rxQuery._lastEnsureEqual === 0 && rxQuery._creationTime < minUnExecutedLifetime) { - uncacheRxQuery(queryCache, rxQuery); - continue; - } - maybeUncash.push(rxQuery); - } - var mustUncache = maybeUncash.length - tryToKeepMax; - if (mustUncache <= 0) { - return; - } - var sortedByLastUsage = maybeUncash.sort(function (a, b) { - return a._lastEnsureEqual - b._lastEnsureEqual; - }); - var toRemove = sortedByLastUsage.slice(0, mustUncache); - toRemove.forEach(function (rxQuery) { - return uncacheRxQuery(queryCache, rxQuery); - }); - }; +var RXJS_SHARE_REPLAY_DEFAULTS = { + bufferSize: 1, + refCount: true }; -exports.defaultCacheReplacementPolicyMonad = defaultCacheReplacementPolicyMonad; -var defaultCacheReplacementPolicy = defaultCacheReplacementPolicyMonad(DEFAULT_TRY_TO_KEEP_MAX, DEFAULT_UNEXECUTED_LIFETME); -exports.defaultCacheReplacementPolicy = defaultCacheReplacementPolicy; -var COLLECTIONS_WITH_RUNNING_CLEANUP = new WeakSet(); +exports.RXJS_SHARE_REPLAY_DEFAULTS = RXJS_SHARE_REPLAY_DEFAULTS; + +},{}],21:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PROMISE_RESOLVE_VOID = exports.PROMISE_RESOLVE_TRUE = exports.PROMISE_RESOLVE_NULL = exports.PROMISE_RESOLVE_FALSE = void 0; +exports.nextTick = nextTick; +exports.promiseSeries = promiseSeries; +exports.promiseWait = promiseWait; +exports.requestIdleCallbackIfAvailable = requestIdleCallbackIfAvailable; +exports.requestIdlePromise = requestIdlePromise; +exports.toPromise = toPromise; /** - * Triggers the cache replacement policy after waitTime has passed. - * We do not run this directly because at exactly the time a query is created, - * we need all CPU to minimize latency. - * Also this should not be triggered multiple times when waitTime is still waiting. + * returns a promise that resolves on the next tick */ -exports.COLLECTIONS_WITH_RUNNING_CLEANUP = COLLECTIONS_WITH_RUNNING_CLEANUP; -function triggerCacheReplacement(rxCollection) { - if (COLLECTIONS_WITH_RUNNING_CLEANUP.has(rxCollection)) { - // already started - return; +function nextTick() { + return new Promise(function (res) { + return setTimeout(res, 0); + }); +} +function promiseWait() { + var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + return new Promise(function (res) { + return setTimeout(res, ms); + }); +} +function toPromise(maybePromise) { + if (maybePromise && typeof maybePromise.then === 'function') { + // is promise + return maybePromise; + } else { + return Promise.resolve(maybePromise); } - COLLECTIONS_WITH_RUNNING_CLEANUP.add(rxCollection); +} +var PROMISE_RESOLVE_TRUE = Promise.resolve(true); +exports.PROMISE_RESOLVE_TRUE = PROMISE_RESOLVE_TRUE; +var PROMISE_RESOLVE_FALSE = Promise.resolve(false); +exports.PROMISE_RESOLVE_FALSE = PROMISE_RESOLVE_FALSE; +var PROMISE_RESOLVE_NULL = Promise.resolve(null); +exports.PROMISE_RESOLVE_NULL = PROMISE_RESOLVE_NULL; +var PROMISE_RESOLVE_VOID = Promise.resolve(); +exports.PROMISE_RESOLVE_VOID = PROMISE_RESOLVE_VOID; +function requestIdlePromise() { + var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + if (typeof window === 'object' && window['requestIdleCallback']) { + return new Promise(function (res) { + return window['requestIdleCallback'](res, { + timeout: timeout + }); + }); + } else { + return promiseWait(0); + } +} - /** - * Do not run directly to not reduce result latency of a new query - */ - (0, _util.nextTick)() // wait at least one tick - .then(function () { - return (0, _util.requestIdlePromise)(200); - }) // and then wait for the CPU to be idle - .then(function () { - if (!rxCollection.destroyed) { - rxCollection.cacheReplacementPolicy(rxCollection, rxCollection._queryCache); - } - COLLECTIONS_WITH_RUNNING_CLEANUP["delete"](rxCollection); - }); +/** + * run the callback if requestIdleCallback available + * do nothing if not + * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback + */ +function requestIdleCallbackIfAvailable(fun) { + if (typeof window === 'object' && window['requestIdleCallback']) window['requestIdleCallback'](fun); } -},{"./util":44}],20:[function(require,module,exports){ +/** + * like Promise.all() but runs in series instead of parallel + * @link https://github.com/egoist/promise.series/blob/master/index.js + * @param tasks array with functions that return a promise + */ +function promiseSeries(tasks, initial) { + return tasks.reduce(function (current, next) { + return current.then(next); + }, Promise.resolve(initial)); +} + +},{}],22:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.UPPER_BOUND_LOGICAL_OPERATORS = exports.LOWER_BOUND_LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = exports.INDEX_MIN = exports.INDEX_MAX = void 0; -exports.getMatcherQueryOpts = getMatcherQueryOpts; -exports.getQueryPlan = getQueryPlan; -exports.isSelectorSatisfiedByIndex = isSelectorSatisfiedByIndex; -exports.rateQueryPlan = rateQueryPlan; -var _rxSchemaHelper = require("./rx-schema-helper"); -var INDEX_MAX = String.fromCharCode(65535); -exports.INDEX_MAX = INDEX_MAX; -var INDEX_MIN = -Infinity; +exports.createRevision = createRevision; +exports.getHeightOfRevision = getHeightOfRevision; +exports.parseRevision = parseRevision; +function parseRevision(revision) { + var split = revision.split('-'); + return { + height: parseInt(split[0], 10), + hash: split[1] + }; +} +function getHeightOfRevision(revision) { + return parseRevision(revision).height; +} /** - * Returns the query plan which contains - * information about how to run the query - * and which indexes to use. - * - * This is used in some storage like Memory, dexie.js and IndexedDB. + * Creates the next write revision for a given document. */ -exports.INDEX_MIN = INDEX_MIN; -function getQueryPlan(schema, query) { - var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var selector = query.selector; - var indexes = schema.indexes ? schema.indexes.slice(0) : []; - if (query.index) { - indexes = [query.index]; - } else { - indexes.push([primaryPath]); +function createRevision(databaseInstanceToken, previousDocData) { + var previousRevision = previousDocData ? previousDocData._rev : null; + var previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0; + var newRevisionHeight = previousRevisionHeigth + 1; + return newRevisionHeight + '-' + databaseInstanceToken; +} + +},{}],23:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RANDOM_STRING = void 0; +exports.isFolderPath = isFolderPath; +exports.randomCouchString = randomCouchString; +exports.trimDots = trimDots; +exports.ucfirst = ucfirst; +/** + * get a random string which can be used with couchdb + * @link http://stackoverflow.com/a/1349426/3443137 + */ +function randomCouchString() { + var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; + var text = ''; + var possible = 'abcdefghijklmnopqrstuvwxyz'; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); } - var optimalSortIndex = query.sort.map(function (sortField) { - return Object.keys(sortField)[0]; - }); - var optimalSortIndexCompareString = optimalSortIndex.join(','); - /** - * Most storages do not support descending indexes - * so having a 'desc' in the sorting, means we always have to re-sort the results. - */ + return text; +} + +/** + * A random string that is never inside of any storage + */ +var RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX'; + +/** + * uppercase first char + */ +exports.RANDOM_STRING = RANDOM_STRING; +function ucfirst(str) { + str += ''; + var f = str.charAt(0).toUpperCase(); + return f + str.substr(1); +} + +/** + * removes trailing and ending dots from the string + */ +function trimDots(str) { + // start + while (str.charAt(0) === '.') str = str.substr(1); + + // end + while (str.slice(-1) === '.') str = str.slice(0, -1); + return str; +} + +/** + * returns true if the given name is likely a folder path + */ +function isFolderPath(name) { + // do not check, if foldername is given + if (name.includes('/') || + // unix + name.includes('\\') // windows + ) { + return true; + } else { + return false; + } +} + +},{}],24:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.now = now; +/** + * Returns the current unix time in milliseconds (with two decmials!) + * Because the accuracy of getTime() in javascript is bad, + * and we cannot rely on performance.now() on all platforms, + * this method implements a way to never return the same value twice. + * This ensures that when now() is called often, we do not loose the information + * about which call came first and which came after. + * + * We had to move from having no decimals, to having two decimal + * because it turned out that some storages are such fast that + * calling this method too often would return 'the future'. + */ +var _lastNow = 0; +/** + * Returns the current time in milliseconds, + * also ensures to not return the same value twice. + */ +function now() { + var ret = new Date().getTime(); + ret = ret + 0.01; + if (ret <= _lastNow) { + ret = _lastNow + 0.01; + } + + /** + * Strip the returned number to max two decimals. + * In theory we would not need this but + * in practice JavaScript has no such good number precision + * so rounding errors could add another decimal place. + */ + var twoDecimals = parseFloat(ret.toFixed(2)); + _lastNow = twoDecimals; + return twoDecimals; +} + +},{}],25:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.QueryCache = exports.DEFAULT_UNEXECUTED_LIFETME = exports.DEFAULT_TRY_TO_KEEP_MAX = exports.COLLECTIONS_WITH_RUNNING_CLEANUP = void 0; +exports.countRxQuerySubscribers = countRxQuerySubscribers; +exports.createQueryCache = createQueryCache; +exports.defaultCacheReplacementPolicyMonad = exports.defaultCacheReplacementPolicy = void 0; +exports.triggerCacheReplacement = triggerCacheReplacement; +exports.uncacheRxQuery = uncacheRxQuery; +var _utils = require("./plugins/utils"); +/** + * the query-cache makes sure that on every query-state, exactly one instance can exist + * if you use the same mango-query more then once, it will reuse the first RxQuery + */ +var QueryCache = /*#__PURE__*/function () { + function QueryCache() { + this._map = new Map(); + } + var _proto = QueryCache.prototype; + /** + * check if an equal query is in the cache, + * if true, return the cached one, + * if false, save the given one and return it + */ + _proto.getByQuery = function getByQuery(rxQuery) { + var stringRep = rxQuery.toString(); + if (!this._map.has(stringRep)) { + this._map.set(stringRep, rxQuery); + } + return this._map.get(stringRep); + }; + return QueryCache; +}(); +exports.QueryCache = QueryCache; +function createQueryCache() { + return new QueryCache(); +} +function uncacheRxQuery(queryCache, rxQuery) { + rxQuery.uncached = true; + var stringRep = rxQuery.toString(); + queryCache._map["delete"](stringRep); +} +function countRxQuerySubscribers(rxQuery) { + return rxQuery.refCount$.observers.length; +} +var DEFAULT_TRY_TO_KEEP_MAX = 100; +exports.DEFAULT_TRY_TO_KEEP_MAX = DEFAULT_TRY_TO_KEEP_MAX; +var DEFAULT_UNEXECUTED_LIFETME = 30 * 1000; + +/** + * The default cache replacement policy + * See docs-src/query-cache.md to learn how it should work. + * Notice that this runs often and should block the cpu as less as possible + * This is a monad which makes it easier to unit test + */ +exports.DEFAULT_UNEXECUTED_LIFETME = DEFAULT_UNEXECUTED_LIFETME; +var defaultCacheReplacementPolicyMonad = function defaultCacheReplacementPolicyMonad(tryToKeepMax, unExecutedLifetime) { + return function (_collection, queryCache) { + if (queryCache._map.size < tryToKeepMax) { + return; + } + var minUnExecutedLifetime = (0, _utils.now)() - unExecutedLifetime; + var maybeUncash = []; + var queriesInCache = Array.from(queryCache._map.values()); + for (var _i = 0, _queriesInCache = queriesInCache; _i < _queriesInCache.length; _i++) { + var rxQuery = _queriesInCache[_i]; + // filter out queries with subscribers + if (countRxQuerySubscribers(rxQuery) > 0) { + continue; + } + // directly uncache queries that never executed and are older then unExecutedLifetime + if (rxQuery._lastEnsureEqual === 0 && rxQuery._creationTime < minUnExecutedLifetime) { + uncacheRxQuery(queryCache, rxQuery); + continue; + } + maybeUncash.push(rxQuery); + } + var mustUncache = maybeUncash.length - tryToKeepMax; + if (mustUncache <= 0) { + return; + } + var sortedByLastUsage = maybeUncash.sort(function (a, b) { + return a._lastEnsureEqual - b._lastEnsureEqual; + }); + var toRemove = sortedByLastUsage.slice(0, mustUncache); + toRemove.forEach(function (rxQuery) { + return uncacheRxQuery(queryCache, rxQuery); + }); + }; +}; +exports.defaultCacheReplacementPolicyMonad = defaultCacheReplacementPolicyMonad; +var defaultCacheReplacementPolicy = defaultCacheReplacementPolicyMonad(DEFAULT_TRY_TO_KEEP_MAX, DEFAULT_UNEXECUTED_LIFETME); +exports.defaultCacheReplacementPolicy = defaultCacheReplacementPolicy; +var COLLECTIONS_WITH_RUNNING_CLEANUP = new WeakSet(); + +/** + * Triggers the cache replacement policy after waitTime has passed. + * We do not run this directly because at exactly the time a query is created, + * we need all CPU to minimize latency. + * Also this should not be triggered multiple times when waitTime is still waiting. + */ +exports.COLLECTIONS_WITH_RUNNING_CLEANUP = COLLECTIONS_WITH_RUNNING_CLEANUP; +function triggerCacheReplacement(rxCollection) { + if (COLLECTIONS_WITH_RUNNING_CLEANUP.has(rxCollection)) { + // already started + return; + } + COLLECTIONS_WITH_RUNNING_CLEANUP.add(rxCollection); + + /** + * Do not run directly to not reduce result latency of a new query + */ + (0, _utils.nextTick)() // wait at least one tick + .then(function () { + return (0, _utils.requestIdlePromise)(200); + }) // and then wait for the CPU to be idle + .then(function () { + if (!rxCollection.destroyed) { + rxCollection.cacheReplacementPolicy(rxCollection, rxCollection._queryCache); + } + COLLECTIONS_WITH_RUNNING_CLEANUP["delete"](rxCollection); + }); +} + +},{"./plugins/utils":12}],26:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.UPPER_BOUND_LOGICAL_OPERATORS = exports.LOWER_BOUND_LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = exports.INDEX_MIN = exports.INDEX_MAX = void 0; +exports.getMatcherQueryOpts = getMatcherQueryOpts; +exports.getQueryPlan = getQueryPlan; +exports.isSelectorSatisfiedByIndex = isSelectorSatisfiedByIndex; +exports.rateQueryPlan = rateQueryPlan; +var _rxSchemaHelper = require("./rx-schema-helper"); +var INDEX_MAX = String.fromCharCode(65535); +exports.INDEX_MAX = INDEX_MAX; +var INDEX_MIN = -Infinity; + +/** + * Returns the query plan which contains + * information about how to run the query + * and which indexes to use. + * + * This is used in some storage like Memory, dexie.js and IndexedDB. + */ +exports.INDEX_MIN = INDEX_MIN; +function getQueryPlan(schema, query) { + var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); + var selector = query.selector; + var indexes = schema.indexes ? schema.indexes.slice(0) : []; + if (query.index) { + indexes = [query.index]; + } else { + indexes.push([primaryPath]); + } + var optimalSortIndex = query.sort.map(function (sortField) { + return Object.keys(sortField)[0]; + }); + var optimalSortIndexCompareString = optimalSortIndex.join(','); + /** + * Most storages do not support descending indexes + * so having a 'desc' in the sorting, means we always have to re-sort the results. + */ var hasDescSorting = !!query.sort.find(function (sortField) { return Object.values(sortField)[0] === 'desc'; }); @@ -4017,206 +3415,106 @@ function rateQueryPlan(schema, query, queryPlan) { return quality; } -},{"./rx-schema-helper":38}],21:[function(require,module,exports){ +},{"./rx-schema-helper":44}],27:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.getCheckpointKey = getCheckpointKey; -exports.setCheckpoint = exports.getLastCheckpointDoc = void 0; +exports.getLastCheckpointDoc = getLastCheckpointDoc; +exports.setCheckpoint = setCheckpoint; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxSchemaHelper = require("../rx-schema-helper"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _metaInstance = require("./meta-instance"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } +function getLastCheckpointDoc(_x, _x2) { + return _getLastCheckpointDoc.apply(this, arguments); } /** * Sets the checkpoint, * automatically resolves conflicts that appear. */ -var setCheckpoint = function setCheckpoint(state, direction, checkpoint) { - try { - var _exit = false; - var previousCheckpointDoc = state.lastCheckpointDoc[direction]; - return Promise.resolve(function () { - if (checkpoint && - /** - * If the replication is already canceled, - * we do not write a checkpoint - * because that could mean we write a checkpoint - * for data that has been fetched from the master - * but not been written to the child. - */ - !state.events.canceled.getValue() && ( - /** - * Only write checkpoint if it is different from before - * to have less writes to the storage. - */ +function _getLastCheckpointDoc() { + _getLastCheckpointDoc = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(state, direction) { + var checkpointDocId, checkpointResult, checkpointDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + checkpointDocId = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, { + isCheckpoint: '1', + itemId: direction, + replicationIdentifier: state.checkpointKey + }); + _context.next = 3; + return state.input.metaInstance.findDocumentsById([checkpointDocId], false); + case 3: + checkpointResult = _context.sent; + checkpointDoc = checkpointResult[checkpointDocId]; + state.lastCheckpointDoc[direction] = checkpointDoc; + if (!checkpointDoc) { + _context.next = 10; + break; + } + return _context.abrupt("return", checkpointDoc.data); + case 10: + return _context.abrupt("return", undefined); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getLastCheckpointDoc.apply(this, arguments); +} +function setCheckpoint(_x3, _x4, _x5) { + return _setCheckpoint.apply(this, arguments); +} +function _setCheckpoint() { + _setCheckpoint = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(state, direction, checkpoint) { + var previousCheckpointDoc, newDoc, result, error; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + previousCheckpointDoc = state.lastCheckpointDoc[direction]; + if (!(checkpoint && + /** + * If the replication is already canceled, + * we do not write a checkpoint + * because that could mean we write a checkpoint + * for data that has been fetched from the master + * but not been written to the child. + */ + !state.events.canceled.getValue() && ( + /** + * Only write checkpoint if it is different from before + * to have less writes to the storage. + */ - !previousCheckpointDoc || JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint))) { - var newDoc = { - id: '', - isCheckpoint: '1', - itemId: direction, - replicationIdentifier: state.checkpointKey, - _deleted: false, - _attachments: {}, - data: checkpoint, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)() - }; - newDoc.id = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, newDoc); - return _for(function () { - return !_exit; - }, void 0, function () { + !previousCheckpointDoc || JSON.stringify(previousCheckpointDoc.data) !== JSON.stringify(checkpoint)))) { + _context2.next = 25; + break; + } + newDoc = { + id: '', + isCheckpoint: '1', + itemId: direction, + replicationIdentifier: state.checkpointKey, + _deleted: false, + _attachments: {}, + data: checkpoint, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)() + }; + newDoc.id = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, newDoc); + case 4: + if (!true) { + _context2.next = 25; + break; + } /** * Instead of just storign the new checkpoint, * we have to stack up the checkpoint with the previous one. @@ -4227,114 +3525,60 @@ var setCheckpoint = function setCheckpoint(state, direction, checkpoint) { if (previousCheckpointDoc) { newDoc.data = (0, _rxStorageHelper.stackCheckpoints)([previousCheckpointDoc.data, newDoc.data]); } - newDoc._meta.lwt = (0, _util.now)(); - newDoc._rev = (0, _util.createRevision)(state.input.hashFunction, newDoc, previousCheckpointDoc); - return Promise.resolve(state.input.metaInstance.bulkWrite([{ + newDoc._meta.lwt = (0, _utils.now)(); + newDoc._rev = (0, _utils.createRevision)(state.input.identifier, previousCheckpointDoc); + _context2.next = 10; + return state.input.metaInstance.bulkWrite([{ previous: previousCheckpointDoc, document: newDoc - }], 'replication-set-checkpoint')).then(function (result) { - if (result.success[newDoc.id]) { - state.lastCheckpointDoc[direction] = (0, _util.getFromObjectOrThrow)(result.success, newDoc.id); - _exit = true; - } else { - var error = (0, _util.getFromObjectOrThrow)(result.error, newDoc.id); - if (error.status !== 409) { - throw error; - } else { - previousCheckpointDoc = (0, _util.ensureNotFalsy)(error.documentInDb); - newDoc._rev = (0, _util.createRevision)(state.input.hashFunction, newDoc, previousCheckpointDoc); - } - } - }); - }); - } - }()); - } catch (e) { - return Promise.reject(e); - } -}; -exports.setCheckpoint = setCheckpoint; -var getLastCheckpointDoc = function getLastCheckpointDoc(state, direction) { - try { - var checkpointDocId = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(_metaInstance.RX_REPLICATION_META_INSTANCE_SCHEMA, { - isCheckpoint: '1', - itemId: direction, - replicationIdentifier: state.checkpointKey - }); - return Promise.resolve(state.input.metaInstance.findDocumentsById([checkpointDocId], false)).then(function (checkpointResult) { - var checkpointDoc = checkpointResult[checkpointDocId]; - state.lastCheckpointDoc[direction] = checkpointDoc; - if (checkpointDoc) { - return checkpointDoc.data; - } else { - return undefined; + }], 'replication-set-checkpoint'); + case 10: + result = _context2.sent; + if (!result.success[newDoc.id]) { + _context2.next = 16; + break; + } + state.lastCheckpointDoc[direction] = (0, _utils.getFromObjectOrThrow)(result.success, newDoc.id); + return _context2.abrupt("return"); + case 16: + error = (0, _utils.getFromObjectOrThrow)(result.error, newDoc.id); + if (!(error.status !== 409)) { + _context2.next = 21; + break; + } + throw error; + case 21: + previousCheckpointDoc = (0, _utils.ensureNotFalsy)(error.documentInDb); + newDoc._rev = (0, _utils.createRevision)(state.input.identifier, previousCheckpointDoc); + case 23: + _context2.next = 4; + break; + case 25: + case "end": + return _context2.stop(); } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.getLastCheckpointDoc = getLastCheckpointDoc; + }, _callee2); + })); + return _setCheckpoint.apply(this, arguments); +} function getCheckpointKey(input) { - var hash = (0, _util.fastUnsecureHash)([input.identifier, input.forkInstance.databaseName, input.forkInstance.collectionName].join('||')); + var hash = (0, _utils.fastUnsecureHash)([input.identifier, input.forkInstance.databaseName, input.forkInstance.collectionName].join('||')); return 'rx-storage-replication-' + hash; } -},{"../rx-schema-helper":38,"../rx-storage-helper":40,"../util":44,"./meta-instance":26}],22:[function(require,module,exports){ +},{"../plugins/utils":12,"../rx-schema-helper":44,"../rx-storage-helper":46,"./meta-instance":32,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66}],28:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveConflictError = exports.defaultConflictHandler = void 0; -var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); -var _util = require("../util"); -/** - * Resolves a conflict error or determines that the given document states are equal. - * Returns the resolved document that must be written to the fork. - * Then the new document state can be pushed upstream. - * If document is not in conflict, returns undefined. - * If error is non-409, it throws an error. - * Conflicts are only solved in the upstream, never in the downstream. - */ -var resolveConflictError = function resolveConflictError(state, input, forkState) { - try { - var conflictHandler = state.input.conflictHandler; - return Promise.resolve(conflictHandler(input, 'replication-resolve-conflict')).then(function (conflictHandlerOutput) { - if (conflictHandlerOutput.isEqual) { - /** - * Documents are equal, - * so this is not a conflict -> do nothing. - */ - return undefined; - } else { - /** - * We have a resolved conflict, - * use the resolved document data. - */ - var resolvedDoc = Object.assign({}, conflictHandlerOutput.documentData, { - /** - * Because the resolved conflict is written to the fork, - * we have to keep/update the forks _meta data, not the masters. - */ - _meta: (0, _util.flatClone)(forkState._meta), - _rev: (0, _util.getDefaultRevision)(), - _attachments: (0, _util.flatClone)(forkState._attachments) - }); - resolvedDoc._meta.lwt = (0, _util.now)(); - resolvedDoc._rev = (0, _util.createRevision)(state.input.hashFunction, resolvedDoc, forkState); - return { - resolvedDoc: resolvedDoc, - output: conflictHandlerOutput - }; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; +exports.defaultConflictHandler = void 0; exports.resolveConflictError = resolveConflictError; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); +var _utils = require("../plugins/utils"); var defaultConflictHandler = function defaultConflictHandler(i, _context) { /** * If the documents are deep equal, @@ -4358,170 +3602,81 @@ var defaultConflictHandler = function defaultConflictHandler(i, _context) { documentData: i.realMasterState }); }; + +/** + * Resolves a conflict error or determines that the given document states are equal. + * Returns the resolved document that must be written to the fork. + * Then the new document state can be pushed upstream. + * If document is not in conflict, returns undefined. + * If error is non-409, it throws an error. + * Conflicts are only solved in the upstream, never in the downstream. + */ exports.defaultConflictHandler = defaultConflictHandler; +function resolveConflictError(_x, _x2, _x3) { + return _resolveConflictError.apply(this, arguments); +} +function _resolveConflictError() { + _resolveConflictError = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(state, input, forkState) { + var conflictHandler, conflictHandlerOutput, resolvedDoc; + return _regenerator["default"].wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + conflictHandler = state.input.conflictHandler; + _context2.next = 3; + return conflictHandler(input, 'replication-resolve-conflict'); + case 3: + conflictHandlerOutput = _context2.sent; + if (!conflictHandlerOutput.isEqual) { + _context2.next = 8; + break; + } + return _context2.abrupt("return", undefined); + case 8: + /** + * We have a resolved conflict, + * use the resolved document data. + */ + resolvedDoc = Object.assign({}, conflictHandlerOutput.documentData, { + /** + * Because the resolved conflict is written to the fork, + * we have to keep/update the forks _meta data, not the masters. + */ + _meta: (0, _utils.flatClone)(forkState._meta), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: (0, _utils.flatClone)(forkState._attachments) + }); + resolvedDoc._meta.lwt = (0, _utils.now)(); + resolvedDoc._rev = (0, _utils.createRevision)(state.input.identifier, forkState); + return _context2.abrupt("return", { + resolvedDoc: resolvedDoc, + output: conflictHandlerOutput + }); + case 12: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return _resolveConflictError.apply(this, arguments); +} -},{"../util":44,"@babel/runtime/helpers/interopRequireDefault":51,"fast-deep-equal":411}],23:[function(require,module,exports){ +},{"../plugins/utils":12,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"fast-deep-equal":416}],29:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.startReplicationDownstream = startReplicationDownstream; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); +var _rxError = require("../rx-error"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _checkpoint = require("./checkpoint"); var _helper = require("./helper"); var _metaInstance = require("./meta-instance"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} /** * Writes all documents from the master to the fork. * The downstream has two operation modes @@ -4531,49 +3686,6 @@ function _for(test, update, body) { * and still can have fast event based sync when the client is not offline. */ function startReplicationDownstream(state) { - var downstreamResyncOnce = function downstreamResyncOnce() { - try { - state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1; - if (state.events.canceled.getValue()) { - return Promise.resolve(); - } - state.checkpointQueue = state.checkpointQueue.then(function () { - return (0, _checkpoint.getLastCheckpointDoc)(state, 'down'); - }); - return Promise.resolve(state.checkpointQueue).then(function (lastCheckpoint) { - var _interrupt = false; - function _temp2() { - return Promise.resolve(Promise.all(promises)).then(function () {}); - } - var promises = []; - var _temp = _for(function () { - return !_interrupt && !state.events.canceled.getValue(); - }, void 0, function () { - lastTimeMasterChangesRequested = timer++; - return Promise.resolve(replicationHandler.masterChangesSince(lastCheckpoint, state.input.pullBatchSize)).then(function (downResult) { - if (downResult.documents.length === 0) { - _interrupt = true; - return; - } - lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, downResult.checkpoint]); - promises.push(persistFromMaster(downResult.documents, lastCheckpoint)); - - /** - * By definition we stop pull when the pulled documents - * do not fill up the pullBatchSize because we - * can assume that the remote has no more documents. - */ - if (downResult.documents.length < state.input.pullBatchSize) { - _interrupt = true; - } - }); - }); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - } catch (e) { - return Promise.reject(e); - } - }; var replicationHandler = state.input.replicationHandler; // used to detect which tasks etc can in it at which order. @@ -4590,7 +3702,7 @@ function startReplicationDownstream(state) { var useTasks = []; while (openTasks.length > 0) { state.events.active.down.next(true); - var innerTaskWithTime = (0, _util.ensureNotFalsy)(openTasks.shift()); + var innerTaskWithTime = (0, _utils.ensureNotFalsy)(openTasks.shift()); /** * If the task came in before the last time we started the pull @@ -4642,6 +3754,73 @@ function startReplicationDownstream(state) { * and then await all writes at the end. */ var lastTimeMasterChangesRequested = -1; + function downstreamResyncOnce() { + return _downstreamResyncOnce.apply(this, arguments); + } + function _downstreamResyncOnce() { + _downstreamResyncOnce = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var lastCheckpoint, promises, downResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + state.stats.down.downstreamResyncOnce = state.stats.down.downstreamResyncOnce + 1; + if (!state.events.canceled.getValue()) { + _context2.next = 3; + break; + } + return _context2.abrupt("return"); + case 3: + state.checkpointQueue = state.checkpointQueue.then(function () { + return (0, _checkpoint.getLastCheckpointDoc)(state, 'down'); + }); + _context2.next = 6; + return state.checkpointQueue; + case 6: + lastCheckpoint = _context2.sent; + promises = []; + case 8: + if (state.events.canceled.getValue()) { + _context2.next = 21; + break; + } + lastTimeMasterChangesRequested = timer++; + _context2.next = 12; + return replicationHandler.masterChangesSince(lastCheckpoint, state.input.pullBatchSize); + case 12: + downResult = _context2.sent; + if (!(downResult.documents.length === 0)) { + _context2.next = 15; + break; + } + return _context2.abrupt("break", 21); + case 15: + lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, downResult.checkpoint]); + promises.push(persistFromMaster(downResult.documents, lastCheckpoint)); + + /** + * By definition we stop pull when the pulled documents + * do not fill up the pullBatchSize because we + * can assume that the remote has no more documents. + */ + if (!(downResult.documents.length < state.input.pullBatchSize)) { + _context2.next = 19; + break; + } + return _context2.abrupt("break", 21); + case 19: + _context2.next = 8; + break; + case 21: + _context2.next = 23; + return Promise.all(promises); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _downstreamResyncOnce.apply(this, arguments); + } function downstreamProcessChanges(tasks) { state.stats.down.downstreamProcessChanges = state.stats.down.downstreamProcessChanges + 1; var docsOfAllTasks = []; @@ -4653,7 +3832,7 @@ function startReplicationDownstream(state) { docsOfAllTasks = docsOfAllTasks.concat(task.documents); lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, task.checkpoint]); }); - return persistFromMaster(docsOfAllTasks, (0, _util.ensureNotFalsy)(lastCheckpoint)); + return persistFromMaster(docsOfAllTasks, (0, _utils.ensureNotFalsy)(lastCheckpoint)); } /** @@ -4664,7 +3843,7 @@ function startReplicationDownstream(state) { * This often bundles up single writes and improves performance * by processing the documents in bulks. */ - var persistenceQueue = _util.PROMISE_RESOLVE_VOID; + var persistenceQueue = _utils.PROMISE_RESOLVE_VOID; var nonPersistedFromMaster = { docs: {} }; @@ -4690,7 +3869,7 @@ function startReplicationDownstream(state) { var useCheckpoint = nonPersistedFromMaster.checkpoint; var docIds = Object.keys(downDocsById); if (state.events.canceled.getValue() || docIds.length === 0) { - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } var writeRowsToFork = []; var writeRowsToForkById = {}; @@ -4699,47 +3878,55 @@ function startReplicationDownstream(state) { return Promise.all([state.input.forkInstance.findDocumentsById(docIds, true), (0, _metaInstance.getAssumedMasterState)(state, docIds)]).then(function (_ref) { var currentForkState = _ref[0], assumedMasterState = _ref[1]; - return Promise.all(docIds.map(function (docId) { - try { - var forkStateFullDoc = currentForkState[docId]; - var forkStateDocData = forkStateFullDoc ? (0, _helper.writeDocToDocState)(forkStateFullDoc) : undefined; - var masterState = downDocsById[docId]; - var assumedMaster = assumedMasterState[docId]; - if (assumedMaster && assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev) { - /** - * The current fork state represents a resolved conflict - * that first must be send to the master in the upstream. - * All conflicts are resolved by the upstream. - */ - return Promise.resolve(_util.PROMISE_RESOLVE_VOID); - } - var isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ? _util.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ - realMasterState: assumedMaster.docData, - newDocumentState: forkStateDocData - }, 'downstream-check-if-equal-0').then(function (r) { - return r.isEqual; - }); - return Promise.resolve(isAssumedMasterEqualToForkStatePromise).then(function (isAssumedMasterEqualToForkState) { - if (!isAssumedMasterEqualToForkState && assumedMaster && assumedMaster.docData._rev && forkStateFullDoc._meta[state.input.identifier] && (0, _util.parseRevision)(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]) { - isAssumedMasterEqualToForkState = true; - } - if (forkStateFullDoc && assumedMaster && isAssumedMasterEqualToForkState === false || forkStateFullDoc && !assumedMaster) { - /** - * We have a non-upstream-replicated - * local write to the fork. - * This means we ignore the downstream of this document - * because anyway the upstream will first resolve the conflict. - */ - return _util.PROMISE_RESOLVE_VOID; - } - var areStatesExactlyEqualPromise = !forkStateDocData ? _util.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ - realMasterState: masterState, - newDocumentState: forkStateDocData - }, 'downstream-check-if-equal-1').then(function (r) { - return r.isEqual; - }); - return Promise.resolve(areStatesExactlyEqualPromise).then(function (areStatesExactlyEqual) { - if (forkStateDocData && areStatesExactlyEqual) { + return Promise.all(docIds.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(docId) { + var forkStateFullDoc, forkStateDocData, masterState, assumedMaster, isAssumedMasterEqualToForkStatePromise, isAssumedMasterEqualToForkState, areStatesExactlyEqualPromise, areStatesExactlyEqual, newForkState, nextRevisionHeight, forkWriteRow; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + forkStateFullDoc = currentForkState[docId]; + forkStateDocData = forkStateFullDoc ? (0, _helper.writeDocToDocState)(forkStateFullDoc) : undefined; + masterState = downDocsById[docId]; + assumedMaster = assumedMasterState[docId]; + if (!(assumedMaster && assumedMaster.metaDocument.isResolvedConflict === forkStateFullDoc._rev)) { + _context.next = 6; + break; + } + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 6: + isAssumedMasterEqualToForkStatePromise = !assumedMaster || !forkStateDocData ? _utils.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ + realMasterState: assumedMaster.docData, + newDocumentState: forkStateDocData + }, 'downstream-check-if-equal-0').then(function (r) { + return r.isEqual; + }); + _context.next = 9; + return isAssumedMasterEqualToForkStatePromise; + case 9: + isAssumedMasterEqualToForkState = _context.sent; + if (!isAssumedMasterEqualToForkState && assumedMaster && assumedMaster.docData._rev && forkStateFullDoc._meta[state.input.identifier] && (0, _utils.parseRevision)(forkStateFullDoc._rev).height === forkStateFullDoc._meta[state.input.identifier]) { + isAssumedMasterEqualToForkState = true; + } + if (!(forkStateFullDoc && assumedMaster && isAssumedMasterEqualToForkState === false || forkStateFullDoc && !assumedMaster)) { + _context.next = 13; + break; + } + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 13: + areStatesExactlyEqualPromise = !forkStateDocData ? _utils.PROMISE_RESOLVE_FALSE : state.input.conflictHandler({ + realMasterState: masterState, + newDocumentState: forkStateDocData + }, 'downstream-check-if-equal-1').then(function (r) { + return r.isEqual; + }); + _context.next = 16; + return areStatesExactlyEqualPromise; + case 16: + areStatesExactlyEqual = _context.sent; + if (!(forkStateDocData && areStatesExactlyEqual)) { + _context.next = 20; + break; + } /** * Document states are exactly equal. * This can happen when the replication is shut down @@ -4751,57 +3938,50 @@ function startReplicationDownstream(state) { if (!assumedMaster || isAssumedMasterEqualToForkState === false) { useMetaWriteRows.push((0, _metaInstance.getMetaWriteRow)(state, forkStateDocData, assumedMaster ? assumedMaster.metaDocument : undefined)); } - return _util.PROMISE_RESOLVE_VOID; - } - - /** - * All other master states need to be written to the forkInstance - * and metaInstance. - */ - var newForkState = Object.assign({}, masterState, forkStateFullDoc ? { - _meta: (0, _util.flatClone)(forkStateFullDoc._meta), - _attachments: {}, - _rev: (0, _util.getDefaultRevision)() - } : { - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }); - - /** - * TODO for unknown reason we need - * to manually set the lwt and the _rev here - * to fix the pouchdb tests. This is not required for - * the other RxStorage implementations which means something is wrong. - */ - newForkState._meta.lwt = (0, _util.now)(); - newForkState._rev = masterState._rev ? masterState._rev : (0, _util.createRevision)(state.input.hashFunction, newForkState, forkStateFullDoc); - - /** - * If the remote works with revisions, - * we store the height of the next fork-state revision - * inside of the documents meta data. - * By doing so we can filter it out in the upstream - * and detect the document as being equal to master or not. - * This is used for example in the CouchDB replication plugin. - */ - if (masterState._rev) { - var nextRevisionHeight = !forkStateFullDoc ? 1 : (0, _util.parseRevision)(forkStateFullDoc._rev).height + 1; - newForkState._meta[state.input.identifier] = nextRevisionHeight; - } - var forkWriteRow = { - previous: forkStateFullDoc, - document: newForkState - }; - writeRowsToFork.push(forkWriteRow); - writeRowsToForkById[docId] = forkWriteRow; - writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, masterState, assumedMaster ? assumedMaster.metaDocument : undefined); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })); + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 20: + /** + * All other master states need to be written to the forkInstance + * and metaInstance. + */ + newForkState = Object.assign({}, masterState, forkStateFullDoc ? { + _meta: (0, _utils.flatClone)(forkStateFullDoc._meta), + _attachments: {}, + _rev: (0, _utils.getDefaultRevision)() + } : { + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }); + /** + * If the remote works with revisions, + * we store the height of the next fork-state revision + * inside of the documents meta data. + * By doing so we can filter it out in the upstream + * and detect the document as being equal to master or not. + * This is used for example in the CouchDB replication plugin. + */ + if (masterState._rev) { + nextRevisionHeight = !forkStateFullDoc ? 1 : (0, _utils.parseRevision)(forkStateFullDoc._rev).height + 1; + newForkState._meta[state.input.identifier] = nextRevisionHeight; + } + forkWriteRow = { + previous: forkStateFullDoc, + document: newForkState + }; + writeRowsToFork.push(forkWriteRow); + writeRowsToForkById[docId] = forkWriteRow; + writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, masterState, assumedMaster ? assumedMaster.metaDocument : undefined); + case 26: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); }).then(function () { if (writeRowsToFork.length > 0) { return state.input.forkInstance.bulkWrite(writeRowsToFork, state.downstreamBulkWriteFlag).then(function (forkWriteResult) { @@ -4809,6 +3989,19 @@ function startReplicationDownstream(state) { state.events.processed.down.next(writeRowsToForkById[docId]); useMetaWriteRows.push(writeRowsToMeta[docId]); }); + Object.values(forkWriteResult.error).forEach(function (error) { + /** + * We do not have to care about downstream conflict errors here + * because on conflict, it will be solved locally and result in another write. + */ + if (error.status === 409) { + return; + } + // other non-conflict errors must be handled + state.events.error.next((0, _rxError.newRxError)('RC_PULL', { + writeError: error + })); + }); }); } }).then(function () { @@ -4832,7 +4025,7 @@ function startReplicationDownstream(state) { } } -},{"../rx-storage-helper":40,"../util":44,"./checkpoint":21,"./helper":24,"./meta-instance":26,"rxjs":458}],24:[function(require,module,exports){ +},{"../plugins/utils":12,"../rx-error":41,"../rx-storage-helper":46,"./checkpoint":27,"./helper":30,"./meta-instance":32,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"rxjs":423}],30:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -4840,49 +4033,52 @@ Object.defineProperty(exports, "__esModule", { }); exports.docStateToWriteDoc = docStateToWriteDoc; exports.writeDocToDocState = writeDocToDocState; -var _util = require("../util"); -function docStateToWriteDoc(hashFunction, docState, previous) { +var _utils = require("../plugins/utils"); +function docStateToWriteDoc(databaseInstanceToken, docState, previous) { var docData = Object.assign({}, docState, { _attachments: {}, _meta: { - lwt: (0, _util.now)() + lwt: (0, _utils.now)() }, - _rev: (0, _util.getDefaultRevision)() + _rev: (0, _utils.getDefaultRevision)() }); - docData._rev = (0, _util.createRevision)(hashFunction, docData, previous); + docData._rev = (0, _utils.createRevision)(databaseInstanceToken, previous); return docData; } function writeDocToDocState(writeDoc) { - var ret = (0, _util.flatClone)(writeDoc); + var ret = (0, _utils.flatClone)(writeDoc); delete ret._attachments; delete ret._meta; delete ret._rev; return ret; } -},{"../util":44}],25:[function(require,module,exports){ +},{"../plugins/utils":12}],31:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { - awaitRxStorageReplicationIdle: true, replicateRxStorageInstance: true, awaitRxStorageReplicationFirstInSync: true, awaitRxStorageReplicationInSync: true, + awaitRxStorageReplicationIdle: true, rxStorageInstanceToReplicationHandler: true, cancelRxStorageReplication: true }; exports.awaitRxStorageReplicationFirstInSync = awaitRxStorageReplicationFirstInSync; -exports.awaitRxStorageReplicationIdle = void 0; +exports.awaitRxStorageReplicationIdle = awaitRxStorageReplicationIdle; exports.awaitRxStorageReplicationInSync = awaitRxStorageReplicationInSync; exports.cancelRxStorageReplication = cancelRxStorageReplication; exports.replicateRxStorageInstance = replicateRxStorageInstance; exports.rxStorageInstanceToReplicationHandler = rxStorageInstanceToReplicationHandler; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _rxSchemaHelper = require("../rx-schema-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _checkpoint = require("./checkpoint"); Object.keys(_checkpoint).forEach(function (key) { if (key === "default" || key === "__esModule") return; @@ -4955,187 +4151,12 @@ Object.keys(_conflicts).forEach(function (key) { } }); }); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} /** * These files contain the replication protocol. * It can be used to replicated RxStorageInstances or RxCollections * or even to do a client(s)-server replication. */ -var awaitRxStorageReplicationIdle = function awaitRxStorageReplicationIdle(state) { - try { - return Promise.resolve(awaitRxStorageReplicationFirstInSync(state)).then(function () { - var _exit = false; - return _for(function () { - return !_exit; - }, void 0, function () { - var _state$streamQueue = state.streamQueue, - down = _state$streamQueue.down, - up = _state$streamQueue.up; - return Promise.resolve(Promise.all([up, down])).then(function () { - if (down === state.streamQueue.down && up === state.streamQueue.up) { - _exit = true; - } - }); - /** - * If the Promises have not been reasigned - * after awaiting them, we know that the replication - * is in idle state at this point in time. - */ - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.awaitRxStorageReplicationIdle = awaitRxStorageReplicationIdle; + function replicateRxStorageInstance(input) { var checkpointKey = (0, _checkpoint.getCheckpointKey)(input); var state = { @@ -5178,10 +4199,10 @@ function replicateRxStorageInstance(input) { up: new _rxjs.BehaviorSubject(false) }, streamQueue: { - down: _util.PROMISE_RESOLVE_VOID, - up: _util.PROMISE_RESOLVE_VOID + down: _utils.PROMISE_RESOLVE_VOID, + up: _utils.PROMISE_RESOLVE_VOID }, - checkpointQueue: _util.PROMISE_RESOLVE_VOID, + checkpointQueue: _utils.PROMISE_RESOLVE_VOID, lastCheckpointDoc: {} }; (0, _downstream.startReplicationDownstream)(state); @@ -5198,14 +4219,50 @@ function awaitRxStorageReplicationFirstInSync(state) { function awaitRxStorageReplicationInSync(replicationState) { return Promise.all([replicationState.streamQueue.up, replicationState.streamQueue.down, replicationState.checkpointQueue]); } -function rxStorageInstanceToReplicationHandler(instance, conflictHandler, hashFunction) { +function awaitRxStorageReplicationIdle(_x) { + return _awaitRxStorageReplicationIdle.apply(this, arguments); +} +function _awaitRxStorageReplicationIdle() { + _awaitRxStorageReplicationIdle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(state) { + var _state$streamQueue, down, up; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return awaitRxStorageReplicationFirstInSync(state); + case 2: + if (!true) { + _context3.next = 10; + break; + } + _state$streamQueue = state.streamQueue, down = _state$streamQueue.down, up = _state$streamQueue.up; + _context3.next = 6; + return Promise.all([up, down]); + case 6: + if (!(down === state.streamQueue.down && up === state.streamQueue.up)) { + _context3.next = 8; + break; + } + return _context3.abrupt("return"); + case 8: + _context3.next = 2; + break; + case 10: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _awaitRxStorageReplicationIdle.apply(this, arguments); +} +function rxStorageInstanceToReplicationHandler(instance, conflictHandler, databaseInstanceToken) { var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(instance.schema.primaryKey); var replicationHandler = { masterChangeStream$: instance.changeStream().pipe((0, _rxjs.map)(function (eventBulk) { var ret = { checkpoint: eventBulk.checkpoint, documents: eventBulk.events.map(function (event) { - return (0, _helper.writeDocToDocState)((0, _util.ensureNotFalsy)(event.documentData)); + return (0, _helper.writeDocToDocState)((0, _utils.ensureNotFalsy)(event.documentData)); }) }; return ret; @@ -5220,75 +4277,109 @@ function rxStorageInstanceToReplicationHandler(instance, conflictHandler, hashFu }; }); }, - masterWrite: function masterWrite(rows) { - try { - var rowById = {}; - rows.forEach(function (row) { - var docId = row.newDocumentState[primaryPath]; - rowById[docId] = row; - }); - var ids = Object.keys(rowById); - return Promise.resolve(instance.findDocumentsById(ids, true)).then(function (masterDocsState) { - var conflicts = []; - var writeRows = []; - return Promise.resolve(Promise.all(Object.entries(rowById).map(function (_ref) { - try { - var id = _ref[0], - row = _ref[1]; - var masterState = masterDocsState[id]; - var _temp3 = function () { - if (!masterState) { - writeRows.push({ - document: (0, _helper.docStateToWriteDoc)(hashFunction, row.newDocumentState) - }); - } else { - var _temp4 = function () { - if (masterState && !row.assumedMasterState) { - conflicts.push((0, _helper.writeDocToDocState)(masterState)); - } else return Promise.resolve(conflictHandler({ - realMasterState: (0, _helper.writeDocToDocState)(masterState), - newDocumentState: (0, _util.ensureNotFalsy)(row.assumedMasterState) - }, 'rxStorageInstanceToReplicationHandler-masterWrite')).then(function (_conflictHandler) { - if (_conflictHandler.isEqual === true) { + masterWrite: function () { + var _masterWrite = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rows) { + var rowById, ids, masterDocsState, conflicts, writeRows, result; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + rowById = {}; + rows.forEach(function (row) { + var docId = row.newDocumentState[primaryPath]; + rowById[docId] = row; + }); + ids = Object.keys(rowById); + _context2.next = 5; + return instance.findDocumentsById(ids, true); + case 5: + masterDocsState = _context2.sent; + conflicts = []; + writeRows = []; + _context2.next = 10; + return Promise.all(Object.entries(rowById).map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_ref) { + var id, row, masterState; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + id = _ref[0], row = _ref[1]; + masterState = masterDocsState[id]; + if (masterState) { + _context.next = 6; + break; + } + writeRows.push({ + document: (0, _helper.docStateToWriteDoc)(databaseInstanceToken, row.newDocumentState) + }); + _context.next = 18; + break; + case 6: + if (!(masterState && !row.assumedMasterState)) { + _context.next = 10; + break; + } + conflicts.push((0, _helper.writeDocToDocState)(masterState)); + _context.next = 18; + break; + case 10: + _context.next = 12; + return conflictHandler({ + realMasterState: (0, _helper.writeDocToDocState)(masterState), + newDocumentState: (0, _utils.ensureNotFalsy)(row.assumedMasterState) + }, 'rxStorageInstanceToReplicationHandler-masterWrite'); + case 12: + _context.t0 = _context.sent.isEqual; + if (!(_context.t0 === true)) { + _context.next = 17; + break; + } writeRows.push({ previous: masterState, - document: (0, _helper.docStateToWriteDoc)(hashFunction, row.newDocumentState, masterState) + document: (0, _helper.docStateToWriteDoc)(databaseInstanceToken, row.newDocumentState, masterState) }); - } else { + _context.next = 18; + break; + case 17: conflicts.push((0, _helper.writeDocToDocState)(masterState)); - } - }); - }(); - if (_temp4 && _temp4.then) return _temp4.then(function () {}); - } - }(); - return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp = function () { - if (writeRows.length > 0) { - return Promise.resolve(instance.bulkWrite(writeRows, 'replication-master-write')).then(function (result) { - Object.values(result.error).forEach(function (err) { - if (err.status !== 409) { - throw new Error('non conflict error'); - } else { - conflicts.push((0, _helper.writeDocToDocState)((0, _util.ensureNotFalsy)(err.documentInDb))); + case 18: + case "end": + return _context.stop(); } - }); - }); + }, _callee); + })); + return function (_x3) { + return _ref2.apply(this, arguments); + }; + }())); + case 10: + if (!(writeRows.length > 0)) { + _context2.next = 15; + break; } - }(); - return _temp && _temp.then ? _temp.then(function () { - return conflicts; - }) : conflicts; - }); - }); - } catch (e) { - return Promise.reject(e); + _context2.next = 13; + return instance.bulkWrite(writeRows, 'replication-master-write'); + case 13: + result = _context2.sent; + Object.values(result.error).forEach(function (err) { + if (err.status !== 409) { + throw new Error('non conflict error'); + } else { + conflicts.push((0, _helper.writeDocToDocState)((0, _utils.ensureNotFalsy)(err.documentInDb))); + } + }); + case 15: + return _context2.abrupt("return", conflicts); + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function masterWrite(_x2) { + return _masterWrite.apply(this, arguments); } - } + return masterWrite; + }() }; return replicationHandler; } @@ -5302,7 +4393,7 @@ function cancelRxStorageReplication(replicationState) { replicationState.events.canceled.complete(); } -},{"../rx-schema-helper":38,"../util":44,"./checkpoint":21,"./conflicts":22,"./downstream":23,"./helper":24,"./meta-instance":26,"./upstream":27,"rxjs":458}],26:[function(require,module,exports){ +},{"../plugins/utils":12,"../rx-schema-helper":44,"./checkpoint":27,"./conflicts":28,"./downstream":29,"./helper":30,"./meta-instance":32,"./upstream":33,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"rxjs":423}],32:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -5313,7 +4404,7 @@ exports.getAssumedMasterState = getAssumedMasterState; exports.getMetaWriteRow = getMetaWriteRow; var _rxSchemaHelper = require("../rx-schema-helper"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var RX_REPLICATION_META_INSTANCE_SCHEMA = (0, _rxSchemaHelper.fillWithDefaultSettings)({ primaryKey: { key: 'id', @@ -5385,185 +4476,39 @@ function getMetaWriteRow(state, newMasterDocState, previous, isResolvedConflict) data: newMasterDocState, _attachments: {}, _deleted: false, - _rev: (0, _util.getDefaultRevision)(), + _rev: (0, _utils.getDefaultRevision)(), _meta: { lwt: 0 } }; newMeta.data = newMasterDocState; newMeta.isResolvedConflict = isResolvedConflict; - newMeta._meta.lwt = (0, _util.now)(); + newMeta._meta.lwt = (0, _utils.now)(); newMeta.id = (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(RX_REPLICATION_META_INSTANCE_SCHEMA, newMeta); - newMeta._rev = (0, _util.createRevision)(state.input.hashFunction, newMeta, previous); + newMeta._rev = (0, _utils.createRevision)(state.input.identifier, previous); return { previous: previous, document: newMeta }; } -},{"../rx-schema-helper":38,"../rx-storage-helper":40,"../util":44}],27:[function(require,module,exports){ +},{"../plugins/utils":12,"../rx-schema-helper":44,"../rx-storage-helper":46}],33:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.startReplicationUpstream = startReplicationUpstream; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _rxStorageHelper = require("../rx-storage-helper"); -var _util = require("../util"); +var _utils = require("../plugins/utils"); var _checkpoint = require("./checkpoint"); var _conflicts = require("./conflicts"); var _helper = require("./helper"); var _metaInstance = require("./meta-instance"); -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} /** * Writes all document changes from the fork to the master. * The upstream runs on two modes: @@ -5573,60 +4518,6 @@ function _for(test, update, body) { * so we do not have to prepare for missed out events. */ function startReplicationUpstream(state) { - var upstreamInitialSync = function upstreamInitialSync() { - try { - state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1; - if (state.events.canceled.getValue()) { - return Promise.resolve(); - } - state.checkpointQueue = state.checkpointQueue.then(function () { - return (0, _checkpoint.getLastCheckpointDoc)(state, 'up'); - }); - return Promise.resolve(state.checkpointQueue).then(function (lastCheckpoint) { - var _interrupt = false; - function _temp11() { - /** - * If we had conflicts during the initial sync, - * it means that we likely have new writes to the fork - * and so we have to run the initial sync again to upastream these new writes. - */ - return Promise.resolve(Promise.all(promises)).then(function (resolvedPromises) { - var hadConflicts = resolvedPromises.find(function (r) { - return !!r; - }); - var _temp9 = function () { - if (hadConflicts) { - return Promise.resolve(upstreamInitialSync()).then(function () {}); - } else if (!state.firstSyncDone.up.getValue()) { - state.firstSyncDone.up.next(true); - } - }(); - if (_temp9 && _temp9.then) return _temp9.then(function () {}); - }); - } - var promises = []; - var _temp10 = _for(function () { - return !_interrupt && !state.events.canceled.getValue(); - }, void 0, function () { - initialSyncStartTime = timer++; - return Promise.resolve(state.input.forkInstance.getChangedDocumentsSince(state.input.pushBatchSize, lastCheckpoint)).then(function (upResult) { - if (upResult.documents.length === 0) { - _interrupt = true; - return; - } - lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, upResult.checkpoint]); - promises.push(persistToMaster(upResult.documents, (0, _util.ensureNotFalsy)(lastCheckpoint))); - }); - }); - return _temp10 && _temp10.then ? _temp10.then(_temp11) : _temp11(_temp10); - }); - } catch (e) { - return Promise.reject(e); - } - }; - /** - * Takes all open tasks an processes them at once. - */ var replicationHandler = state.input.replicationHandler; state.streamQueue.up = state.streamQueue.up.then(function () { return upstreamInitialSync().then(function () { @@ -5659,21 +4550,97 @@ function startReplicationUpstream(state) { }))).then(function () { return sub.unsubscribe(); }); - function processTasks() { - if (state.events.canceled.getValue() || openTasks.length === 0) { - state.events.active.up.next(false); - return; - } - state.stats.up.processTasks = state.stats.up.processTasks + 1; - state.events.active.up.next(true); - state.streamQueue.up = state.streamQueue.up.then(function () { - /** - * Merge/filter all open tasks - */ - var docs = []; - var checkpoint = {}; - while (openTasks.length > 0) { - var taskWithTime = (0, _util.ensureNotFalsy)(openTasks.shift()); + function upstreamInitialSync() { + return _upstreamInitialSync.apply(this, arguments); + } + /** + * Takes all open tasks an processes them at once. + */ + function _upstreamInitialSync() { + _upstreamInitialSync = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var lastCheckpoint, promises, upResult, resolvedPromises, hadConflicts; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + state.stats.up.upstreamInitialSync = state.stats.up.upstreamInitialSync + 1; + if (!state.events.canceled.getValue()) { + _context4.next = 3; + break; + } + return _context4.abrupt("return"); + case 3: + state.checkpointQueue = state.checkpointQueue.then(function () { + return (0, _checkpoint.getLastCheckpointDoc)(state, 'up'); + }); + _context4.next = 6; + return state.checkpointQueue; + case 6: + lastCheckpoint = _context4.sent; + promises = []; + case 8: + if (state.events.canceled.getValue()) { + _context4.next = 19; + break; + } + initialSyncStartTime = timer++; + _context4.next = 12; + return state.input.forkInstance.getChangedDocumentsSince(state.input.pushBatchSize, lastCheckpoint); + case 12: + upResult = _context4.sent; + if (!(upResult.documents.length === 0)) { + _context4.next = 15; + break; + } + return _context4.abrupt("break", 19); + case 15: + lastCheckpoint = (0, _rxStorageHelper.stackCheckpoints)([lastCheckpoint, upResult.checkpoint]); + promises.push(persistToMaster(upResult.documents, (0, _utils.ensureNotFalsy)(lastCheckpoint))); + _context4.next = 8; + break; + case 19: + _context4.next = 21; + return Promise.all(promises); + case 21: + resolvedPromises = _context4.sent; + hadConflicts = resolvedPromises.find(function (r) { + return !!r; + }); + if (!hadConflicts) { + _context4.next = 28; + break; + } + _context4.next = 26; + return upstreamInitialSync(); + case 26: + _context4.next = 29; + break; + case 28: + if (!state.firstSyncDone.up.getValue()) { + state.firstSyncDone.up.next(true); + } + case 29: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _upstreamInitialSync.apply(this, arguments); + } + function processTasks() { + if (state.events.canceled.getValue() || openTasks.length === 0) { + state.events.active.up.next(false); + return; + } + state.stats.up.processTasks = state.stats.up.processTasks + 1; + state.events.active.up.next(true); + state.streamQueue.up = state.streamQueue.up.then(function () { + /** + * Merge/filter all open tasks + */ + var docs = []; + var checkpoint = {}; + while (openTasks.length > 0) { + var taskWithTime = (0, _utils.ensureNotFalsy)(openTasks.shift()); /** * If the task came in before the last time the initial sync fetching * has run, we can ignore the task because the initial sync already processed @@ -5687,7 +4654,7 @@ function startReplicationUpstream(state) { })); checkpoint = (0, _rxStorageHelper.stackCheckpoints)([checkpoint, taskWithTime.task.checkpoint]); } - var promise = docs.length === 0 ? _util.PROMISE_RESOLVE_FALSE : persistToMaster(docs, checkpoint); + var promise = docs.length === 0 ? _utils.PROMISE_RESOLVE_FALSE : persistToMaster(docs, checkpoint); return promise.then(function () { if (openTasks.length === 0) { state.events.active.up.next(false); @@ -5697,7 +4664,7 @@ function startReplicationUpstream(state) { }); }); } - var persistenceQueue = _util.PROMISE_RESOLVE_FALSE; + var persistenceQueue = _utils.PROMISE_RESOLVE_FALSE; var nonPersistedFromMaster = { docs: {} }; @@ -5717,191 +4684,242 @@ function startReplicationUpstream(state) { nonPersistedFromMaster.docs[docId] = docData; }); nonPersistedFromMaster.checkpoint = checkpoint; - persistenceQueue = persistenceQueue.then(function () { - try { - if (state.events.canceled.getValue()) { - return Promise.resolve(false); - } - var upDocsById = nonPersistedFromMaster.docs; - nonPersistedFromMaster.docs = {}; - var useCheckpoint = nonPersistedFromMaster.checkpoint; - var docIds = Object.keys(upDocsById); - if (docIds.length === 0) { - return Promise.resolve(false); - } - return Promise.resolve((0, _metaInstance.getAssumedMasterState)(state, docIds)).then(function (assumedMasterState) { - var writeRowsToMaster = {}; - var writeRowsToMasterIds = []; - var writeRowsToMeta = {}; - var forkStateById = {}; - return Promise.resolve(Promise.all(docIds.map(function (docId) { - try { - var _temp8 = function _temp8(_state$input$conflict) { - if (_temp7 && _state$input$conflict.isEqual || - /** - * If the master works with _rev fields, - * we use that to check if our current doc state - * is different from the assumedMasterDoc. - */ - - assumedMasterDoc && assumedMasterDoc.docData._rev && (0, _util.parseRevision)(fullDocData._rev).height === fullDocData._meta[state.input.identifier]) { - _exit = true; - return; - } - writeRowsToMasterIds.push(docId); - writeRowsToMaster[docId] = { - assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined, - newDocumentState: docData - }; - writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, docData, assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined); - }; - var _exit = false; - var fullDocData = upDocsById[docId]; - forkStateById[docId] = fullDocData; - var docData = (0, _helper.writeDocToDocState)(fullDocData); - var assumedMasterDoc = assumedMasterState[docId]; - - /** - * If the master state is equal to the - * fork state, we can assume that the document state is already - * replicated. - */ - var _temp7 = assumedMasterDoc && - // if the isResolvedConflict is correct, we do not have to compare the documents. - assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev; - return Promise.resolve(_temp7 ? Promise.resolve(state.input.conflictHandler({ - realMasterState: assumedMasterDoc.docData, - newDocumentState: docData - }, 'upstream-check-if-equal')).then(_temp8) : _temp8(_temp7)); - } catch (e) { - return Promise.reject(e); + persistenceQueue = persistenceQueue.then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var upDocsById, useCheckpoint, docIds, assumedMasterState, writeRowsToMaster, writeRowsToMasterIds, writeRowsToMeta, forkStateById, writeRowsArray, conflictIds, conflictsById, writeBatches, useWriteRowsToMeta, hadConflictWrites, conflictWriteFork, conflictWriteMeta, forkWriteResult, useMetaWrites; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!state.events.canceled.getValue()) { + _context3.next = 2; + break; } - }))).then(function () { - if (writeRowsToMasterIds.length === 0) { - return false; + return _context3.abrupt("return", false); + case 2: + upDocsById = nonPersistedFromMaster.docs; + nonPersistedFromMaster.docs = {}; + useCheckpoint = nonPersistedFromMaster.checkpoint; + docIds = Object.keys(upDocsById); + if (!(docIds.length === 0)) { + _context3.next = 8; + break; } - var writeRowsArray = Object.values(writeRowsToMaster); - var conflictIds = new Set(); - var conflictsById = {}; - + return _context3.abrupt("return", false); + case 8: + _context3.next = 10; + return (0, _metaInstance.getAssumedMasterState)(state, docIds); + case 10: + assumedMasterState = _context3.sent; + writeRowsToMaster = {}; + writeRowsToMasterIds = []; + writeRowsToMeta = {}; + forkStateById = {}; + _context3.next = 17; + return Promise.all(docIds.map( /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(docId) { + var fullDocData, docData, assumedMasterDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + fullDocData = upDocsById[docId]; + forkStateById[docId] = fullDocData; + docData = (0, _helper.writeDocToDocState)(fullDocData); + assumedMasterDoc = assumedMasterState[docId]; + /** + * If the master state is equal to the + * fork state, we can assume that the document state is already + * replicated. + */ + _context.t1 = assumedMasterDoc && + // if the isResolvedConflict is correct, we do not have to compare the documents. + assumedMasterDoc.metaDocument.isResolvedConflict !== fullDocData._rev; + if (!_context.t1) { + _context.next = 9; + break; + } + _context.next = 8; + return state.input.conflictHandler({ + realMasterState: assumedMasterDoc.docData, + newDocumentState: docData + }, 'upstream-check-if-equal'); + case 8: + _context.t1 = _context.sent.isEqual; + case 9: + _context.t0 = _context.t1; + if (_context.t0) { + _context.next = 12; + break; + } + _context.t0 = + /** + * If the master works with _rev fields, + * we use that to check if our current doc state + * is different from the assumedMasterDoc. + */ + + assumedMasterDoc && assumedMasterDoc.docData._rev && (0, _utils.parseRevision)(fullDocData._rev).height === fullDocData._meta[state.input.identifier]; + case 12: + if (!_context.t0) { + _context.next = 14; + break; + } + return _context.abrupt("return"); + case 14: + writeRowsToMasterIds.push(docId); + writeRowsToMaster[docId] = { + assumedMasterState: assumedMasterDoc ? assumedMasterDoc.docData : undefined, + newDocumentState: docData + }; + writeRowsToMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, docData, assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined); + case 17: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref2.apply(this, arguments); + }; + }())); + case 17: + if (!(writeRowsToMasterIds.length === 0)) { + _context3.next = 19; + break; + } + return _context3.abrupt("return", false); + case 19: + writeRowsArray = Object.values(writeRowsToMaster); + conflictIds = new Set(); + conflictsById = {}; /** * To always respect the push.batchSize, * we have to split the write rows into batches * to ensure that replicationHandler.masterWrite() is never * called with more documents than what the batchSize limits. */ - var writeBatches = (0, _util.batchArray)(writeRowsArray, state.input.pushBatchSize); - return Promise.resolve(Promise.all(writeBatches.map(function (writeBatch) { - try { - return Promise.resolve(replicationHandler.masterWrite(writeBatch)).then(function (masterWriteResult) { - masterWriteResult.forEach(function (conflictDoc) { - var id = conflictDoc[state.primaryPath]; - conflictIds.add(id); - conflictsById[id] = conflictDoc; - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - function _temp6() { - function _temp4() { - /** - * For better performance we do not await checkpoint writes, - * but to ensure order on parallel checkpoint writes, - * we have to use a queue. - */ - state.checkpointQueue = state.checkpointQueue.then(function () { - return (0, _checkpoint.setCheckpoint)(state, 'up', useCheckpoint); - }); - return hadConflictWrites; - } - /** - * Resolve conflicts by writing a new document - * state to the fork instance and the 'real' master state - * to the meta instance. - * Non-409 errors will be detected by resolveConflictError() - */ - var hadConflictWrites = false; - var _temp3 = function () { - if (conflictIds.size > 0) { - state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1; - var conflictWriteFork = []; - var conflictWriteMeta = {}; - return Promise.resolve(Promise.all(Object.entries(conflictsById).map(function (_ref) { - var docId = _ref[0], - realMasterState = _ref[1]; - var writeToMasterRow = writeRowsToMaster[docId]; - var input = { - newDocumentState: writeToMasterRow.newDocumentState, - assumedMasterState: writeToMasterRow.assumedMasterState, - realMasterState: realMasterState - }; - return (0, _conflicts.resolveConflictError)(state, input, forkStateById[docId]).then(function (resolved) { - if (resolved) { - state.events.resolvedConflicts.next({ - input: input, - output: resolved.output - }); - conflictWriteFork.push({ - previous: forkStateById[docId], - document: resolved.resolvedDoc - }); - var assumedMasterDoc = assumedMasterState[docId]; - conflictWriteMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, (0, _util.ensureNotFalsy)(realMasterState), assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined, resolved.resolvedDoc._rev); - } + writeBatches = (0, _utils.batchArray)(writeRowsArray, state.input.pushBatchSize); + _context3.next = 25; + return Promise.all(writeBatches.map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(writeBatch) { + var masterWriteResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return replicationHandler.masterWrite(writeBatch); + case 2: + masterWriteResult = _context2.sent; + masterWriteResult.forEach(function (conflictDoc) { + var id = conflictDoc[state.primaryPath]; + conflictIds.add(id); + conflictsById[id] = conflictDoc; }); - }))).then(function () { - var _temp2 = function () { - if (conflictWriteFork.length > 0) { - hadConflictWrites = true; - state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1; - return Promise.resolve(state.input.forkInstance.bulkWrite(conflictWriteFork, 'replication-up-write-conflict')).then(function (forkWriteResult) { - /** - * Errors in the forkWriteResult must not be handled - * because they have been caused by a write to the forkInstance - * in between which will anyway trigger a new upstream cycle - * that will then resolved the conflict again. - */ - var useMetaWrites = []; - Object.keys(forkWriteResult.success).forEach(function (docId) { - useMetaWrites.push(conflictWriteMeta[docId]); - }); - var _temp = function () { - if (useMetaWrites.length > 0) { - return Promise.resolve(state.input.metaInstance.bulkWrite(useMetaWrites, 'replication-up-write-conflict-meta')).then(function () {}); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); // TODO what to do with conflicts while writing to the metaInstance? - } - }(); - if (_temp2 && _temp2.then) return _temp2.then(function () {}); - }); + case 4: + case "end": + return _context2.stop(); } - }(); - return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3); + }, _callee2); + })); + return function (_x2) { + return _ref3.apply(this, arguments); + }; + }())); + case 25: + useWriteRowsToMeta = []; + writeRowsToMasterIds.forEach(function (docId) { + if (!conflictIds.has(docId)) { + state.events.processed.up.next(writeRowsToMaster[docId]); + useWriteRowsToMeta.push(writeRowsToMeta[docId]); } - var useWriteRowsToMeta = []; - writeRowsToMasterIds.forEach(function (docId) { - if (!conflictIds.has(docId)) { - state.events.processed.up.next(writeRowsToMaster[docId]); - useWriteRowsToMeta.push(writeRowsToMeta[docId]); + }); + if (!(useWriteRowsToMeta.length > 0)) { + _context3.next = 30; + break; + } + _context3.next = 30; + return state.input.metaInstance.bulkWrite(useWriteRowsToMeta, 'replication-up-write-meta'); + case 30: + /** + * Resolve conflicts by writing a new document + * state to the fork instance and the 'real' master state + * to the meta instance. + * Non-409 errors will be detected by resolveConflictError() + */ + hadConflictWrites = false; + if (!(conflictIds.size > 0)) { + _context3.next = 48; + break; + } + state.stats.up.persistToMasterHadConflicts = state.stats.up.persistToMasterHadConflicts + 1; + conflictWriteFork = []; + conflictWriteMeta = {}; + _context3.next = 37; + return Promise.all(Object.entries(conflictsById).map(function (_ref4) { + var docId = _ref4[0], + realMasterState = _ref4[1]; + var writeToMasterRow = writeRowsToMaster[docId]; + var input = { + newDocumentState: writeToMasterRow.newDocumentState, + assumedMasterState: writeToMasterRow.assumedMasterState, + realMasterState: realMasterState + }; + return (0, _conflicts.resolveConflictError)(state, input, forkStateById[docId]).then(function (resolved) { + if (resolved) { + state.events.resolvedConflicts.next({ + input: input, + output: resolved.output + }); + conflictWriteFork.push({ + previous: forkStateById[docId], + document: resolved.resolvedDoc + }); + var assumedMasterDoc = assumedMasterState[docId]; + conflictWriteMeta[docId] = (0, _metaInstance.getMetaWriteRow)(state, (0, _utils.ensureNotFalsy)(realMasterState), assumedMasterDoc ? assumedMasterDoc.metaDocument : undefined, resolved.resolvedDoc._rev); } }); - var _temp5 = function () { - if (useWriteRowsToMeta.length > 0) { - return Promise.resolve(state.input.metaInstance.bulkWrite(useWriteRowsToMeta, 'replication-up-write-meta')).then(function () {}); // TODO what happens when we have conflicts here? - } - }(); - return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5); + })); + case 37: + if (!(conflictWriteFork.length > 0)) { + _context3.next = 48; + break; + } + hadConflictWrites = true; + state.stats.up.persistToMasterConflictWrites = state.stats.up.persistToMasterConflictWrites + 1; + _context3.next = 42; + return state.input.forkInstance.bulkWrite(conflictWriteFork, 'replication-up-write-conflict'); + case 42: + forkWriteResult = _context3.sent; + /** + * Errors in the forkWriteResult must not be handled + * because they have been caused by a write to the forkInstance + * in between which will anyway trigger a new upstream cycle + * that will then resolved the conflict again. + */ + useMetaWrites = []; + Object.keys(forkWriteResult.success).forEach(function (docId) { + useMetaWrites.push(conflictWriteMeta[docId]); }); - }); - }); - } catch (e) { - return Promise.reject(e); - } - })["catch"](function (unhandledError) { + if (!(useMetaWrites.length > 0)) { + _context3.next = 48; + break; + } + _context3.next = 48; + return state.input.metaInstance.bulkWrite(useMetaWrites, 'replication-up-write-conflict-meta'); + case 48: + /** + * For better performance we do not await checkpoint writes, + * but to ensure order on parallel checkpoint writes, + * we have to use a queue. + */ + state.checkpointQueue = state.checkpointQueue.then(function () { + return (0, _checkpoint.setCheckpoint)(state, 'up', useCheckpoint); + }); + return _context3.abrupt("return", hadConflictWrites); + case 50: + case "end": + return _context3.stop(); + } + }, _callee3); + })))["catch"](function (unhandledError) { state.events.error.next(unhandledError); return false; }); @@ -5909,7 +4927,7 @@ function startReplicationUpstream(state) { } } -},{"../rx-storage-helper":40,"../util":44,"./checkpoint":21,"./conflicts":22,"./helper":24,"./meta-instance":26,"rxjs":458}],28:[function(require,module,exports){ +},{"../plugins/utils":12,"../rx-storage-helper":46,"./checkpoint":27,"./conflicts":28,"./helper":30,"./meta-instance":32,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"rxjs":423}],34:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -5996,127 +5014,23 @@ function flattenEvents(input) { return nonDuplicate; } -},{"./overwritable":8}],29:[function(require,module,exports){ +},{"./overwritable":9}],35:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.createRxCollectionStorageInstance = void 0; +exports.createRxCollectionStorageInstance = createRxCollectionStorageInstance; exports.fillObjectDataBeforeInsert = fillObjectDataBeforeInsert; -exports.removeCollectionStorages = void 0; -var _util = require("./util"); +exports.removeCollectionStorages = removeCollectionStorages; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); +var _utils = require("./plugins/utils"); var _rxSchemaHelper = require("./rx-schema-helper"); var _hooks = require("./hooks"); var _rxDatabaseInternalStore = require("./rx-database-internal-store"); var _rxStorageHelper = require("./rx-storage-helper"); -/** - * Removes the main storage of the collection - * and all connected storages like the ones from the replication meta etc. - */ -var removeCollectionStorages = function removeCollectionStorages(storage, databaseInternalStorage, databaseInstanceToken, databaseName, collectionName, -/** - * If no hash function is provided, - * we assume that the whole internal store is removed anyway - * so we do not have to delete the meta documents. - */ -hashFunction) { - try { - return Promise.resolve((0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, databaseInternalStorage)).then(function (allCollectionMetaDocs) { - var relevantCollectionMetaDocs = allCollectionMetaDocs.filter(function (metaDoc) { - return metaDoc.data.name === collectionName; - }); - var removeStorages = []; - relevantCollectionMetaDocs.forEach(function (metaDoc) { - removeStorages.push({ - collectionName: metaDoc.data.name, - schema: metaDoc.data.schema, - isCollection: true - }); - metaDoc.data.connectedStorages.forEach(function (row) { - return removeStorages.push({ - collectionName: row.collectionName, - isCollection: false, - schema: row.schema - }); - }); - }); - - // ensure uniqueness - var alreadyAdded = new Set(); - removeStorages = removeStorages.filter(function (row) { - var key = row.collectionName + '||' + row.schema.version; - if (alreadyAdded.has(key)) { - return false; - } else { - alreadyAdded.add(key); - return true; - } - }); - - // remove all the storages - return Promise.resolve(Promise.all(removeStorages.map(function (row) { - try { - return Promise.resolve(storage.createStorageInstance({ - collectionName: row.collectionName, - databaseInstanceToken: databaseInstanceToken, - databaseName: databaseName, - multiInstance: false, - options: {}, - schema: row.schema - })).then(function (storageInstance) { - return Promise.resolve(storageInstance.remove()).then(function () { - var _temp2 = function () { - if (row.isCollection) { - return Promise.resolve((0, _hooks.runAsyncPluginHooks)('postRemoveRxCollection', { - storage: storage, - databaseName: databaseName, - collectionName: collectionName - })).then(function () {}); - } - }(); - if (_temp2 && _temp2.then) return _temp2.then(function () {}); - }); - }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - var _temp = function () { - if (hashFunction) { - var writeRows = relevantCollectionMetaDocs.map(function (doc) { - var writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); - writeDoc._deleted = true; - writeDoc._meta.lwt = (0, _util.now)(); - writeDoc._rev = (0, _util.createRevision)(hashFunction, writeDoc, doc); - return { - previous: doc, - document: writeDoc - }; - }); - return Promise.resolve(databaseInternalStorage.bulkWrite(writeRows, 'rx-database-remove-collection-all')).then(function () {}); - } - }(); - if (_temp && _temp.then) return _temp.then(function () {}); - }); // remove the meta documents - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.removeCollectionStorages = removeCollectionStorages; -/** - * Creates the storage instances that are used internally in the collection - */ -var createRxCollectionStorageInstance = function createRxCollectionStorageInstance(rxDatabase, storageInstanceCreationParams) { - try { - storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance; - return Promise.resolve(rxDatabase.storage.createStorageInstance(storageInstanceCreationParams)); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createRxCollectionStorageInstance = createRxCollectionStorageInstance; /** * fills in the default data. * This also clones the data. @@ -6124,7 +5038,7 @@ exports.createRxCollectionStorageInstance = createRxCollectionStorageInstance; function fillObjectDataBeforeInsert(schema, data) { var useJson = schema.fillObjectWithDefaults(data); useJson = (0, _rxSchemaHelper.fillPrimaryKey)(schema.primaryPath, schema.jsonSchema, useJson); - useJson._meta = (0, _util.getDefaultRxDocumentMeta)(); + useJson._meta = (0, _utils.getDefaultRxDocumentMeta)(); if (!useJson.hasOwnProperty('_deleted')) { useJson._deleted = false; } @@ -6132,12 +5046,160 @@ function fillObjectDataBeforeInsert(schema, data) { useJson._attachments = {}; } if (!useJson.hasOwnProperty('_rev')) { - useJson._rev = (0, _util.getDefaultRevision)(); + useJson._rev = (0, _utils.getDefaultRevision)(); } return useJson; } -},{"./hooks":6,"./rx-database-internal-store":31,"./rx-schema-helper":38,"./rx-storage-helper":40,"./util":44}],30:[function(require,module,exports){ +/** + * Creates the storage instances that are used internally in the collection + */ +function createRxCollectionStorageInstance(_x, _x2) { + return _createRxCollectionStorageInstance.apply(this, arguments); +} +/** + * Removes the main storage of the collection + * and all connected storages like the ones from the replication meta etc. + */ +function _createRxCollectionStorageInstance() { + _createRxCollectionStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(rxDatabase, storageInstanceCreationParams) { + var storageInstance; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + storageInstanceCreationParams.multiInstance = rxDatabase.multiInstance; + _context.next = 3; + return rxDatabase.storage.createStorageInstance(storageInstanceCreationParams); + case 3: + storageInstance = _context.sent; + return _context.abrupt("return", storageInstance); + case 5: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _createRxCollectionStorageInstance.apply(this, arguments); +} +function removeCollectionStorages(_x3, _x4, _x5, _x6, _x7, _x8) { + return _removeCollectionStorages.apply(this, arguments); +} +function _removeCollectionStorages() { + _removeCollectionStorages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(storage, databaseInternalStorage, databaseInstanceToken, databaseName, collectionName, + /** + * If no hash function is provided, + * we assume that the whole internal store is removed anyway + * so we do not have to delete the meta documents. + */ + hashFunction) { + var allCollectionMetaDocs, relevantCollectionMetaDocs, removeStorages, alreadyAdded, writeRows; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return (0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, databaseInternalStorage); + case 2: + allCollectionMetaDocs = _context3.sent; + relevantCollectionMetaDocs = allCollectionMetaDocs.filter(function (metaDoc) { + return metaDoc.data.name === collectionName; + }); + removeStorages = []; + relevantCollectionMetaDocs.forEach(function (metaDoc) { + removeStorages.push({ + collectionName: metaDoc.data.name, + schema: metaDoc.data.schema, + isCollection: true + }); + metaDoc.data.connectedStorages.forEach(function (row) { + return removeStorages.push({ + collectionName: row.collectionName, + isCollection: false, + schema: row.schema + }); + }); + }); + + // ensure uniqueness + alreadyAdded = new Set(); + removeStorages = removeStorages.filter(function (row) { + var key = row.collectionName + '||' + row.schema.version; + if (alreadyAdded.has(key)) { + return false; + } else { + alreadyAdded.add(key); + return true; + } + }); + + // remove all the storages + _context3.next = 10; + return Promise.all(removeStorages.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(row) { + var storageInstance; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return storage.createStorageInstance({ + collectionName: row.collectionName, + databaseInstanceToken: databaseInstanceToken, + databaseName: databaseName, + multiInstance: false, + options: {}, + schema: row.schema + }); + case 2: + storageInstance = _context2.sent; + _context2.next = 5; + return storageInstance.remove(); + case 5: + if (!row.isCollection) { + _context2.next = 8; + break; + } + _context2.next = 8; + return (0, _hooks.runAsyncPluginHooks)('postRemoveRxCollection', { + storage: storage, + databaseName: databaseName, + collectionName: collectionName + }); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x9) { + return _ref.apply(this, arguments); + }; + }())); + case 10: + if (!hashFunction) { + _context3.next = 14; + break; + } + writeRows = relevantCollectionMetaDocs.map(function (doc) { + var writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); + writeDoc._deleted = true; + writeDoc._meta.lwt = (0, _utils.now)(); + writeDoc._rev = (0, _utils.createRevision)(databaseInstanceToken, doc); + return { + previous: doc, + document: writeDoc + }; + }); + _context3.next = 14; + return databaseInternalStorage.bulkWrite(writeRows, 'rx-database-remove-collection-all'); + case 14: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _removeCollectionStorages.apply(this, arguments); +} + +},{"./hooks":6,"./plugins/utils":12,"./rx-database-internal-store":37,"./rx-schema-helper":44,"./rx-storage-helper":46,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66}],36:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -6147,9 +5209,11 @@ Object.defineProperty(exports, "__esModule", { exports.RxCollectionBase = void 0; exports.createRxCollection = createRxCollection; exports.isRxCollection = isRxCollection; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxCollectionHelper = require("./rx-collection-helper"); var _rxQuery = require("./rx-query"); var _rxError = require("./rx-error"); @@ -6160,6 +5224,8 @@ var _hooks = require("./hooks"); var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); var _rxStorageHelper = require("./rx-storage-helper"); var _replicationProtocol = require("./replication-protocol"); +var _incrementalWrite = require("./incremental-write"); +var _rxDocument = require("./rx-document"); var HOOKS_WHEN = ['pre', 'post']; var HOOKS_KEYS = ['insert', 'save', 'remove', 'create']; var hooksApplied = false; @@ -6179,11 +5245,12 @@ var RxCollectionBase = /*#__PURE__*/function () { var conflictHandler = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : _replicationProtocol.defaultConflictHandler; this.storageInstance = {}; this.timeouts = new Set(); - this._atomicUpsertQueues = new Map(); + this.incrementalWriteQueue = {}; + this._incrementalUpsertQueues = new Map(); this.synced = false; this.hooks = {}; this._subs = []; - this._docCache = new _docCache.DocCache(); + this._docCache = {}; this._queryCache = (0, _queryCache.createQueryCache)(); this.$ = {}; this._changeEventBuffer = {}; @@ -6204,79 +5271,87 @@ var RxCollectionBase = /*#__PURE__*/function () { _applyHookFunctions(this.asRxCollection); } var _proto = RxCollectionBase.prototype; - _proto.prepare = function prepare() { - try { + _proto.prepare = /*#__PURE__*/function () { + var _prepare = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { var _this = this; - _this.storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(_this.database, _this.internalStorageInstance, _this.schema.jsonSchema); - _this.$ = _this.database.eventBulks$.pipe((0, _operators.filter)(function (changeEventBulk) { - return changeEventBulk.collectionName === _this.name; - }), (0, _operators.mergeMap)(function (changeEventBulk) { - return changeEventBulk.events; - })); - _this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(_this.asRxCollection); - - /** - * Instead of resolving the EventBulk array here and spit it into - * single events, we should fully work with event bulks internally - * to save performance. - */ - return Promise.resolve(_this.database.storageToken).then(function (databaseStorageToken) { - var subDocs = _this.storageInstance.changeStream().subscribe(function (eventBulk) { - var changeEventBulk = { - id: eventBulk.id, - internal: false, - collectionName: _this.name, - storageToken: databaseStorageToken, - events: eventBulk.events.map(function (ev) { - return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(false, ev, _this); - }), - databaseToken: _this.database.token, - checkpoint: eventBulk.checkpoint, - context: eventBulk.context - }; - _this.database.$emit(changeEventBulk); - }); - _this._subs.push(subDocs); - - /** - * When a write happens to the collection - * we find the changed document in the docCache - * and tell it that it has to change its data. - */ - _this._subs.push(_this.$.pipe((0, _operators.filter)(function (cE) { - return !cE.isLocal; - })).subscribe(function (cE) { - // when data changes, send it to RxDocument in docCache - var doc = _this._docCache.get(cE.documentId); - if (doc) { - doc._handleChangeEvent(cE); - } - })); + var databaseStorageToken, subDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + this.storageInstance = (0, _rxStorageHelper.getWrappedStorageInstance)(this.database, this.internalStorageInstance, this.schema.jsonSchema); + this.incrementalWriteQueue = new _incrementalWrite.IncrementalWriteQueue(this.storageInstance, this.schema.primaryPath, function (newData, oldData) { + return (0, _rxDocument.beforeDocumentUpdateWrite)(_this, newData, oldData); + }, function (result) { + return _this._runHooks('post', 'save', result); + }); + this.$ = this.database.eventBulks$.pipe((0, _operators.filter)(function (changeEventBulk) { + return changeEventBulk.collectionName === _this.name; + }), (0, _operators.mergeMap)(function (changeEventBulk) { + return changeEventBulk.events; + })); + this._changeEventBuffer = (0, _changeEventBuffer.createChangeEventBuffer)(this.asRxCollection); + this._docCache = new _docCache.DocumentCache(this.schema.primaryPath, this.$.pipe((0, _operators.filter)(function (cE) { + return !cE.isLocal; + })), function (docData) { + return (0, _rxDocumentPrototypeMerge.createNewRxDocument)(_this.asRxCollection, docData); + }); - /** - * Resolve the conflict tasks - * of the RxStorageInstance - */ - _this._subs.push(_this.storageInstance.conflictResultionTasks().subscribe(function (task) { - _this.conflictHandler(task.input, task.context).then(function (output) { - _this.storageInstance.resolveConflictResultionTask({ - id: task.id, - output: output + /** + * Instead of resolving the EventBulk array here and spit it into + * single events, we should fully work with event bulks internally + * to save performance. + */ + _context.next = 7; + return this.database.storageToken; + case 7: + databaseStorageToken = _context.sent; + subDocs = this.storageInstance.changeStream().subscribe(function (eventBulk) { + var changeEventBulk = { + id: eventBulk.id, + internal: false, + collectionName: _this.name, + storageToken: databaseStorageToken, + events: eventBulk.events.map(function (ev) { + return (0, _rxStorageHelper.storageChangeEventToRxChangeEvent)(false, ev, _this); + }), + databaseToken: _this.database.token, + checkpoint: eventBulk.checkpoint, + context: eventBulk.context + }; + _this.database.$emit(changeEventBulk); }); - }); - })); - return _util.PROMISE_RESOLVE_VOID; - }); - } catch (e) { - return Promise.reject(e); + this._subs.push(subDocs); + + /** + * Resolve the conflict tasks + * of the RxStorageInstance + */ + this._subs.push(this.storageInstance.conflictResultionTasks().subscribe(function (task) { + _this.conflictHandler(task.input, task.context).then(function (output) { + _this.storageInstance.resolveConflictResultionTask({ + id: task.id, + output: output + }); + }); + })); + return _context.abrupt("return", _utils.PROMISE_RESOLVE_VOID); + case 12: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function prepare() { + return _prepare.apply(this, arguments); } - } // overwritte by migration-plugin + return prepare; + }() // overwritte by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { - throw (0, _util.pluginMissing)('migration'); + throw (0, _utils.pluginMissing)('migration'); }; _proto.getDataMigrator = function getDataMigrator() { - throw (0, _util.pluginMissing)('migration'); + throw (0, _utils.pluginMissing)('migration'); }; _proto.migrate = function migrate() { var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; @@ -6286,182 +5361,272 @@ var RxCollectionBase = /*#__PURE__*/function () { var batchSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; return this.getDataMigrator().migratePromise(batchSize); }; - _proto.insert = function insert(json) { - try { - var _this2 = this; - // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later - var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this2.schema, json); - return Promise.resolve(_this2.bulkInsert([useJson])).then(function (writeResult) { - var isError = writeResult.error[0]; - (0, _rxStorageHelper.throwIfIsStorageWriteError)(_this2, useJson[_this2.schema.primaryPath], json, isError); - var insertResult = (0, _util.ensureNotFalsy)(writeResult.success[0]); - return insertResult; - }); - } catch (e) { - return Promise.reject(e); + _proto.insert = /*#__PURE__*/function () { + var _insert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(json) { + var useJson, writeResult, isError, insertResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + // TODO do we need fillObjectDataBeforeInsert() here because it is also run at bulkInsert() later + useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this.schema, json); + _context2.next = 3; + return this.bulkInsert([useJson]); + case 3: + writeResult = _context2.sent; + isError = writeResult.error[0]; + (0, _rxStorageHelper.throwIfIsStorageWriteError)(this, useJson[this.schema.primaryPath], json, isError); + insertResult = (0, _utils.ensureNotFalsy)(writeResult.success[0]); + return _context2.abrupt("return", insertResult); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function insert(_x) { + return _insert.apply(this, arguments); } - }; - _proto.bulkInsert = function bulkInsert(docsData) { - try { - var _temp3 = function _temp3(docs) { - var docsMap = new Map(); - var insertRows = docs.map(function (doc) { - docsMap.set(doc[_this3.schema.primaryPath], doc); - var docData = Object.assign(doc, { - _attachments: {}, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _deleted: false - }); - var row = { - document: docData - }; - return row; - }); - return Promise.resolve(_this3.storageInstance.bulkWrite(insertRows, 'rx-collection-bulk-insert')).then(function (results) { - function _temp2() { - return { - success: rxDocuments, - error: Object.values(results.error) - }; - } - // create documents - var successDocData = Object.values(results.success); - var rxDocuments = successDocData.map(function (writtenDocData) { - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this3, writtenDocData); - return doc; - }); - var _temp = function () { - if (_this3.hasHooks('post', 'insert')) { - return Promise.resolve(Promise.all(rxDocuments.map(function (doc) { - return _this3._runHooks('post', 'insert', docsMap.get(doc.primary), doc); - }))).then(function () {}); + return insert; + }(); + _proto.bulkInsert = /*#__PURE__*/function () { + var _bulkInsert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(docsData) { + var _this2 = this; + var useDocs, docs, docsMap, insertRows, results, successDocData, rxDocuments; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (!(docsData.length === 0)) { + _context3.next = 2; + break; } - }(); - return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); - }); - }; - var _this3 = this; - /** - * Optimization shortcut, - * do nothing when called with an empty array - */ - if (docsData.length === 0) { - return Promise.resolve({ - success: [], - error: [] - }); - } - var useDocs = docsData.map(function (docData) { - var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this3.schema, docData); - return useDocData; - }); - var _this3$hasHooks = _this3.hasHooks('pre', 'insert'); - return Promise.resolve(_this3$hasHooks ? Promise.resolve(Promise.all(useDocs.map(function (doc) { - return _this3._runHooks('pre', 'insert', doc).then(function () { - return doc; - }); - }))).then(_temp3) : _temp3(useDocs)); - } catch (e) { - return Promise.reject(e); - } - }; - _proto.bulkRemove = function bulkRemove(ids) { - try { - var _this4 = this; - /** - * Optimization shortcut, - * do nothing when called with an empty array - */ - if (ids.length === 0) { - return Promise.resolve({ - success: [], - error: [] - }); - } - return Promise.resolve(_this4.findByIds(ids)).then(function (rxDocumentMap) { - var docsData = []; - var docsMap = new Map(); - Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { - var data = (0, _util.clone)(rxDocument.toJSON(true)); - docsData.push(data); - docsMap.set(rxDocument.primary, data); - }); - return Promise.resolve(Promise.all(docsData.map(function (doc) { - var primary = doc[_this4.schema.primaryPath]; - return _this4._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); - }))).then(function () { - var removeDocs = docsData.map(function (doc) { - var writeDoc = (0, _util.flatClone)(doc); - writeDoc._deleted = true; - return { - previous: doc, - document: writeDoc - }; - }); - return Promise.resolve(_this4.storageInstance.bulkWrite(removeDocs, 'rx-collection-bulk-remove')).then(function (results) { - var successIds = Object.keys(results.success); - - // run hooks - return Promise.resolve(Promise.all(successIds.map(function (id) { - return _this4._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); - }))).then(function () { - var rxDocuments = successIds.map(function (id) { - return rxDocumentMap.get(id); + return _context3.abrupt("return", { + success: [], + error: [] + }); + case 2: + useDocs = docsData.map(function (docData) { + var useDocData = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this2.schema, docData); + return useDocData; + }); + if (!this.hasHooks('pre', 'insert')) { + _context3.next = 9; + break; + } + _context3.next = 6; + return Promise.all(useDocs.map(function (doc) { + return _this2._runHooks('pre', 'insert', doc).then(function () { + return doc; + }); + })); + case 6: + _context3.t0 = _context3.sent; + _context3.next = 10; + break; + case 9: + _context3.t0 = useDocs; + case 10: + docs = _context3.t0; + docsMap = new Map(); + insertRows = docs.map(function (doc) { + docsMap.set(doc[_this2.schema.primaryPath], doc); + var docData = Object.assign(doc, { + _attachments: {}, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _deleted: false }); + var row = { + document: docData + }; + return row; + }); + _context3.next = 15; + return this.storageInstance.bulkWrite(insertRows, 'rx-collection-bulk-insert'); + case 15: + results = _context3.sent; + // create documents + successDocData = Object.values(results.success); + rxDocuments = successDocData.map(function (writtenDocData) { + return _this2._docCache.getCachedRxDocument(writtenDocData); + }); + if (!this.hasHooks('post', 'insert')) { + _context3.next = 21; + break; + } + _context3.next = 21; + return Promise.all(rxDocuments.map(function (doc) { + return _this2._runHooks('post', 'insert', docsMap.get(doc.primary), doc); + })); + case 21: + return _context3.abrupt("return", { + success: rxDocuments, + error: Object.values(results.error) + }); + case 22: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function bulkInsert(_x2) { + return _bulkInsert.apply(this, arguments); + } + return bulkInsert; + }(); + _proto.bulkRemove = /*#__PURE__*/function () { + var _bulkRemove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(ids) { + var _this3 = this; + var rxDocumentMap, docsData, docsMap, removeDocs, results, successIds, rxDocuments; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(ids.length === 0)) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", { + success: [], + error: [] + }); + case 2: + _context4.next = 4; + return this.findByIds(ids).exec(); + case 4: + rxDocumentMap = _context4.sent; + docsData = []; + docsMap = new Map(); + Array.from(rxDocumentMap.values()).forEach(function (rxDocument) { + var data = rxDocument.toMutableJSON(true); + docsData.push(data); + docsMap.set(rxDocument.primary, data); + }); + _context4.next = 10; + return Promise.all(docsData.map(function (doc) { + var primary = doc[_this3.schema.primaryPath]; + return _this3._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary)); + })); + case 10: + removeDocs = docsData.map(function (doc) { + var writeDoc = (0, _utils.flatClone)(doc); + writeDoc._deleted = true; return { - success: rxDocuments, - error: Object.values(results.error) + previous: doc, + document: writeDoc }; }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); + _context4.next = 13; + return this.storageInstance.bulkWrite(removeDocs, 'rx-collection-bulk-remove'); + case 13: + results = _context4.sent; + successIds = Object.keys(results.success); // run hooks + _context4.next = 17; + return Promise.all(successIds.map(function (id) { + return _this3._runHooks('post', 'remove', docsMap.get(id), rxDocumentMap.get(id)); + })); + case 17: + rxDocuments = successIds.map(function (id) { + return (0, _utils.getFromMapOrThrow)(rxDocumentMap, id); + }); + return _context4.abrupt("return", { + success: rxDocuments, + error: Object.values(results.error) + }); + case 19: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function bulkRemove(_x3) { + return _bulkRemove.apply(this, arguments); } - } + return bulkRemove; + }() /** * same as bulkInsert but overwrites existing document with same primary */ ; - _proto.bulkUpsert = function bulkUpsert(docsData) { - try { - var _this5 = this; - var insertData = []; - var useJsonByDocId = new Map(); - docsData.forEach(function (docData) { - var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this5.schema, docData); - var primary = useJson[_this5.schema.primaryPath]; - if (!primary) { - throw (0, _rxError.newRxError)('COL3', { - primaryPath: _this5.schema.primaryPath, - data: useJson, - schema: _this5.schema.jsonSchema - }); - } - useJsonByDocId.set(primary, useJson); - insertData.push(useJson); - }); - return Promise.resolve(_this5.bulkInsert(insertData)).then(function (insertResult) { - var ret = insertResult.success.slice(0); - return Promise.resolve(Promise.all(insertResult.error.map(function (error) { - var id = error.documentId; - var writeData = (0, _util.getFromMapOrThrow)(useJsonByDocId, id); - var docDataInDb = (0, _util.ensureNotFalsy)(error.documentInDb); - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this5.asRxCollection, docDataInDb); - return doc.atomicUpdate(function () { - return writeData; - }); - }))).then(function (updatedDocs) { - ret = ret.concat(updatedDocs); - return ret; - }); - }); - } catch (e) { - return Promise.reject(e); + _proto.bulkUpsert = + /*#__PURE__*/ + function () { + var _bulkUpsert = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(docsData) { + var _this4 = this; + var insertData, useJsonByDocId, insertResult, ret, updatedDocs; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + insertData = []; + useJsonByDocId = new Map(); + docsData.forEach(function (docData) { + var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(_this4.schema, docData); + var primary = useJson[_this4.schema.primaryPath]; + if (!primary) { + throw (0, _rxError.newRxError)('COL3', { + primaryPath: _this4.schema.primaryPath, + data: useJson, + schema: _this4.schema.jsonSchema + }); + } + useJsonByDocId.set(primary, useJson); + insertData.push(useJson); + }); + _context6.next = 5; + return this.bulkInsert(insertData); + case 5: + insertResult = _context6.sent; + ret = insertResult.success.slice(0); + _context6.next = 9; + return Promise.all(insertResult.error.map( /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(error) { + var id, writeData, docDataInDb, doc, newDoc; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!(error.status !== 409)) { + _context5.next = 2; + break; + } + throw (0, _rxError.newRxError)('VD2', { + collection: _this4.name, + writeError: error + }); + case 2: + id = error.documentId; + writeData = (0, _utils.getFromMapOrThrow)(useJsonByDocId, id); + docDataInDb = (0, _utils.ensureNotFalsy)(error.documentInDb); + doc = _this4._docCache.getCachedRxDocument(docDataInDb); + _context5.next = 8; + return doc.incrementalModify(function () { + return writeData; + }); + case 8: + newDoc = _context5.sent; + return _context5.abrupt("return", newDoc); + case 10: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return function (_x5) { + return _ref.apply(this, arguments); + }; + }())); + case 9: + updatedDocs = _context6.sent; + ret = ret.concat(updatedDocs); + return _context6.abrupt("return", ret); + case 12: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function bulkUpsert(_x4) { + return _bulkUpsert.apply(this, arguments); } - } + return bulkUpsert; + }() /** * same as insert but overwrites existing document with same primary */ @@ -6473,10 +5638,10 @@ var RxCollectionBase = /*#__PURE__*/function () { } /** - * upserts to a RxDocument, uses atomicUpdate if document already exists + * upserts to a RxDocument, uses incrementalModify if document already exists */; - _proto.atomicUpsert = function atomicUpsert(json) { - var _this6 = this; + _proto.incrementalUpsert = function incrementalUpsert(json) { + var _this5 = this; var useJson = (0, _rxCollectionHelper.fillObjectDataBeforeInsert)(this.schema, json); var primary = useJson[this.schema.primaryPath]; if (!primary) { @@ -6486,22 +5651,20 @@ var RxCollectionBase = /*#__PURE__*/function () { } // ensure that it won't try 2 parallel runs - var queue = this._atomicUpsertQueues.get(primary); + var queue = this._incrementalUpsertQueues.get(primary); if (!queue) { - queue = _util.PROMISE_RESOLVE_VOID; + queue = _utils.PROMISE_RESOLVE_VOID; } queue = queue.then(function () { - return _atomicUpsertEnsureRxDocumentExists(_this6, primary, useJson); + return _incrementalUpsertEnsureRxDocumentExists(_this5, primary, useJson); }).then(function (wasInserted) { if (!wasInserted.inserted) { - return _atomicUpsertUpdate(wasInserted.doc, useJson).then(function () { - return wasInserted.doc; - }); + return _incrementalUpsertUpdate(wasInserted.doc, useJson); } else { return wasInserted.doc; } }); - this._atomicUpsertQueues.set(primary, queue); + this._incrementalUpsertQueues.set(primary, queue); return queue; }; _proto.find = function find(queryObj) { @@ -6513,7 +5676,7 @@ var RxCollectionBase = /*#__PURE__*/function () { if (!queryObj) { queryObj = (0, _rxQuery._getDefaultQuery)(); } - var query = (0, _rxQuery.createRxQuery)('find', queryObj, this.asRxCollection); + var query = (0, _rxQuery.createRxQuery)('find', queryObj, this); return query; }; _proto.findOne = function findOne(queryObj) { @@ -6534,7 +5697,7 @@ var RxCollectionBase = /*#__PURE__*/function () { throw (0, _rxError.newRxError)('QU6'); } queryObj.limit = 1; - query = (0, _rxQuery.createRxQuery)('findOne', queryObj, this.asRxCollection); + query = (0, _rxQuery.createRxQuery)('findOne', queryObj, this); } if (typeof queryObj === 'number' || Array.isArray(queryObj)) { throw (0, _rxError.newRxTypeError)('COL6', { @@ -6547,7 +5710,7 @@ var RxCollectionBase = /*#__PURE__*/function () { if (!queryObj) { queryObj = (0, _rxQuery._getDefaultQuery)(); } - var query = (0, _rxQuery.createRxQuery)('count', queryObj, this.asRxCollection); + var query = (0, _rxQuery.createRxQuery)('count', queryObj, this); return query; } @@ -6556,158 +5719,21 @@ var RxCollectionBase = /*#__PURE__*/function () { * has way better performance then running multiple findOne() or a find() with a complex $or-selected */; _proto.findByIds = function findByIds(ids) { - try { - var _this7 = this; - var ret = new Map(); - var mustBeQueried = []; - - // first try to fill from docCache - ids.forEach(function (id) { - var doc = _this7._docCache.get(id); - if (doc) { - ret.set(id, doc); - } else { - mustBeQueried.push(id); - } - }); - - // find everything which was not in docCache - var _temp4 = function () { - if (mustBeQueried.length > 0) { - return Promise.resolve(_this7.storageInstance.findDocumentsById(mustBeQueried, false)).then(function (docs) { - Object.values(docs).forEach(function (docData) { - var doc = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this7, docData); - ret.set(doc.primary, doc); - }); - }); - } - }(); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(function () { - return ret; - }) : ret); - } catch (e) { - return Promise.reject(e); - } - } - /** - * like this.findByIds but returns an observable - * that always emits the current state - */ - ; - _proto.findByIds$ = function findByIds$(ids) { - var _this8 = this; - var currentValue = null; - var lastChangeEvent = -1; - - /** - * Ensure we do not process events in parallel - */ - var queue = _util.PROMISE_RESOLVE_VOID; - var initialPromise = this.findByIds(ids).then(function (docsMap) { - lastChangeEvent = _this8._changeEventBuffer.counter; - currentValue = docsMap; - }); - var firstEmitDone = false; - return this.$.pipe((0, _operators.startWith)(null), - /** - * Optimization shortcut. - * Do not proceed if the emitted RxChangeEvent - * is not relevant for the query. - */ - (0, _operators.filter)(function (changeEvent) { - if ( - // first emit has no event - changeEvent && ( - // local documents are not relevant for the query - changeEvent.isLocal || - // document of the change is not in the ids list. - !ids.includes(changeEvent.documentId))) { - return false; - } else { - return true; - } - }), (0, _operators.mergeMap)(function () { - return initialPromise; - }), - /** - * Because shareReplay with refCount: true - * will often subscribe/unsusbscribe - * we always ensure that we handled all missed events - * since the last subscription. - */ - (0, _operators.mergeMap)(function () { - queue = queue.then(function () { - try { - var _temp7 = function _temp7(_result) { - if (_exit) return _result; - firstEmitDone = true; - return currentValue; - }; - var _exit = false; - /** - * We first have to clone the Map - * to ensure we do not create side effects by mutating - * a Map that has already been returned before. - */ - currentValue = new Map((0, _util.ensureNotFalsy)(currentValue)); - var missedChangeEvents = _this8._changeEventBuffer.getFrom(lastChangeEvent + 1); - lastChangeEvent = _this8._changeEventBuffer.counter; - var _temp6 = function () { - if (missedChangeEvents === null) { - /** - * changeEventBuffer is of bounds -> we must re-execute over the database - * because we cannot calculate the new results just from the events. - */ - return Promise.resolve(_this8.findByIds(ids)).then(function (newResult) { - lastChangeEvent = _this8._changeEventBuffer.counter; - _exit = true; - return newResult; - }); - } else { - var resultHasChanged = false; - missedChangeEvents.forEach(function (rxChangeEvent) { - var docId = rxChangeEvent.documentId; - if (!ids.includes(docId)) { - // document is not relevant for the result set - return; - } - var op = rxChangeEvent.operation; - if (op === 'INSERT' || op === 'UPDATE') { - resultHasChanged = true; - var rxDocument = (0, _rxDocumentPrototypeMerge.createRxDocument)(_this8.asRxCollection, rxChangeEvent.documentData); - (0, _util.ensureNotFalsy)(currentValue).set(docId, rxDocument); - } else { - if ((0, _util.ensureNotFalsy)(currentValue).has(docId)) { - resultHasChanged = true; - (0, _util.ensureNotFalsy)(currentValue)["delete"](docId); - } - } - }); - - // nothing happened that affects the result -> do not emit - if (!resultHasChanged && firstEmitDone) { - var _temp5 = false; - _exit = true; - return _temp5; - } - } - }(); - return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(_temp7) : _temp7(_temp6)); - } catch (e) { - return Promise.reject(e); - } - }); - return queue; - }), (0, _operators.filter)(function (x) { - return !!x; - }), (0, _operators.shareReplay)(_util.RXJS_SHARE_REPLAY_DEFAULTS)); + var _selector2; + var mangoQuery = { + selector: (_selector2 = {}, _selector2[this.schema.primaryPath] = { + $in: ids.slice(0) + }, _selector2) + }; + var query = (0, _rxQuery.createRxQuery)('findByIds', mangoQuery, this); + return query; } /** * Export collection to a JSON friendly format. */; _proto.exportJSON = function exportJSON() { - throw (0, _util.pluginMissing)('json-dump'); + throw (0, _utils.pluginMissing)('json-dump'); } /** @@ -6715,33 +5741,10 @@ var RxCollectionBase = /*#__PURE__*/function () { * @param _exportedJSON The previously exported data from the `.exportJSON()` method. */; _proto.importJSON = function importJSON(_exportedJSON) { - throw (0, _util.pluginMissing)('json-dump'); + throw (0, _utils.pluginMissing)('json-dump'); }; _proto.insertCRDT = function insertCRDT(_updateObj) { - throw (0, _util.pluginMissing)('crdt'); - } - - /** - * sync with a CouchDB endpoint - */; - _proto.syncCouchDB = function syncCouchDB(_syncOptions) { - throw (0, _util.pluginMissing)('replication'); - } - - /** - * sync with a GraphQL endpoint - */; - _proto.syncGraphQL = function syncGraphQL(_options) { - throw (0, _util.pluginMissing)('replication-graphql'); - }; - _proto.syncCouchDBNew = function syncCouchDBNew(_syncOptions) { - throw (0, _util.pluginMissing)('replication-couchdb-new'); - }; - _proto.syncP2P = function syncP2P(_syncOptions) { - throw (0, _util.pluginMissing)('replication-p2p'); - }; - _proto.syncFirestore = function syncFirestore(_syncOptions) { - throw (0, _util.pluginMissing)('replication-firestore'); + throw (0, _utils.pluginMissing)('crdt'); } /** @@ -6803,7 +5806,7 @@ var RxCollectionBase = /*#__PURE__*/function () { _proto._runHooks = function _runHooks(when, key, data, instance) { var hooks = this.getHooks(when, key); if (!hooks) { - return _util.PROMISE_RESOLVE_VOID; + return _utils.PROMISE_RESOLVE_VOID; } // run parallel: false @@ -6812,7 +5815,7 @@ var RxCollectionBase = /*#__PURE__*/function () { return hook(data, instance); }; }); - return (0, _util.promiseSeries)(tasks) + return (0, _utils.promiseSeries)(tasks) // run parallel: true .then(function () { return Promise.all(hooks.parallel.map(function (hook) { @@ -6838,20 +5841,20 @@ var RxCollectionBase = /*#__PURE__*/function () { * so that no running timeouts prevent the exit of the JavaScript process. */; _proto.promiseWait = function promiseWait(time) { - var _this9 = this; + var _this6 = this; var ret = new Promise(function (res) { var timeout = setTimeout(function () { - _this9.timeouts["delete"](timeout); + _this6.timeouts["delete"](timeout); res(); }, time); - _this9.timeouts.add(timeout); + _this6.timeouts.add(timeout); }); return ret; }; _proto.destroy = function destroy() { - var _this10 = this; + var _this7 = this; if (this.destroyed) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } /** @@ -6876,11 +5879,11 @@ var RxCollectionBase = /*#__PURE__*/function () { * but the change is not added to the changes collection. */ return this.database.requestIdlePromise().then(function () { - return Promise.all(_this10.onDestroy.map(function (fn) { + return Promise.all(_this7.onDestroy.map(function (fn) { return fn(); })); }).then(function () { - return _this10.storageInstance.close(); + return _this7.storageInstance.close(); }).then(function () { /** * Unsubscribing must be done AFTER the storageInstance.close() @@ -6888,11 +5891,11 @@ var RxCollectionBase = /*#__PURE__*/function () { * otherwise there might be open conflicts to be resolved which * will then stuck and never resolve. */ - _this10._subs.forEach(function (sub) { + _this7._subs.forEach(function (sub) { return sub.unsubscribe(); }); - delete _this10.database.collections[_this10.name]; - return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', _this10).then(function () { + delete _this7.database.collections[_this7.name]; + return (0, _hooks.runAsyncPluginHooks)('postDestroyRxCollection', _this7).then(function () { return true; }); }); @@ -6901,16 +5904,29 @@ var RxCollectionBase = /*#__PURE__*/function () { /** * remove all data of the collection */; - _proto.remove = function remove() { - try { - var _this11 = this; - return Promise.resolve(_this11.destroy()).then(function () { - return Promise.resolve((0, _rxCollectionHelper.removeCollectionStorages)(_this11.database.storage, _this11.database.internalStore, _this11.database.token, _this11.database.name, _this11.name, _this11.database.hashFunction)).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + _proto.remove = + /*#__PURE__*/ + function () { + var _remove = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.destroy(); + case 2: + _context7.next = 4; + return (0, _rxCollectionHelper.removeCollectionStorages)(this.database.storage, this.database.internalStore, this.database.token, this.database.name, this.name, this.database.hashFunction); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7, this); + })); + function remove() { + return _remove.apply(this, arguments); } - }; + return remove; + }(); (0, _createClass2["default"])(RxCollectionBase, [{ key: "insert$", get: function get() { @@ -6951,20 +5967,16 @@ function _applyHookFunctions(collection) { var colProto = Object.getPrototypeOf(collection); HOOKS_KEYS.forEach(function (key) { HOOKS_WHEN.map(function (when) { - var fnName = when + (0, _util.ucfirst)(key); + var fnName = when + (0, _utils.ucfirst)(key); colProto[fnName] = function (fun, parallel) { return this.addHook(when, key, fun, parallel); }; }); }); } -function _atomicUpsertUpdate(doc, json) { - return doc.atomicUpdate(function (_innerDoc) { +function _incrementalUpsertUpdate(doc, json) { + return doc.incrementalModify(function (_innerDoc) { return json; - }).then(function () { - return (0, _util.nextTick)(); - }).then(function () { - return doc; }); } @@ -6972,15 +5984,15 @@ function _atomicUpsertUpdate(doc, json) { * ensures that the given document exists * @return promise that resolves with new doc and flag if inserted */ -function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { +function _incrementalUpsertEnsureRxDocumentExists(rxCollection, primary, json) { /** * Optimisation shortcut, * first try to find the document in the doc-cache */ - var docFromCache = rxCollection._docCache.get(primary); - if (docFromCache) { + var docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary); + if (docDataFromCache) { return Promise.resolve({ - doc: docFromCache, + doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache), inserted: false }); } @@ -7004,30 +6016,30 @@ function _atomicUpsertEnsureRxDocumentExists(rxCollection, primary, json) { /** * creates and prepares a new collection */ -function createRxCollection(_ref) { - var database = _ref.database, - name = _ref.name, - schema = _ref.schema, - _ref$instanceCreation = _ref.instanceCreationOptions, - instanceCreationOptions = _ref$instanceCreation === void 0 ? {} : _ref$instanceCreation, - _ref$migrationStrateg = _ref.migrationStrategies, - migrationStrategies = _ref$migrationStrateg === void 0 ? {} : _ref$migrationStrateg, - _ref$autoMigrate = _ref.autoMigrate, - autoMigrate = _ref$autoMigrate === void 0 ? true : _ref$autoMigrate, - _ref$statics = _ref.statics, - statics = _ref$statics === void 0 ? {} : _ref$statics, - _ref$methods = _ref.methods, - methods = _ref$methods === void 0 ? {} : _ref$methods, - _ref$attachments = _ref.attachments, - attachments = _ref$attachments === void 0 ? {} : _ref$attachments, - _ref$options = _ref.options, - options = _ref$options === void 0 ? {} : _ref$options, - _ref$localDocuments = _ref.localDocuments, - localDocuments = _ref$localDocuments === void 0 ? false : _ref$localDocuments, - _ref$cacheReplacement = _ref.cacheReplacementPolicy, - cacheReplacementPolicy = _ref$cacheReplacement === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref$cacheReplacement, - _ref$conflictHandler = _ref.conflictHandler, - conflictHandler = _ref$conflictHandler === void 0 ? _replicationProtocol.defaultConflictHandler : _ref$conflictHandler; +function createRxCollection(_ref2) { + var database = _ref2.database, + name = _ref2.name, + schema = _ref2.schema, + _ref2$instanceCreatio = _ref2.instanceCreationOptions, + instanceCreationOptions = _ref2$instanceCreatio === void 0 ? {} : _ref2$instanceCreatio, + _ref2$migrationStrate = _ref2.migrationStrategies, + migrationStrategies = _ref2$migrationStrate === void 0 ? {} : _ref2$migrationStrate, + _ref2$autoMigrate = _ref2.autoMigrate, + autoMigrate = _ref2$autoMigrate === void 0 ? true : _ref2$autoMigrate, + _ref2$statics = _ref2.statics, + statics = _ref2$statics === void 0 ? {} : _ref2$statics, + _ref2$methods = _ref2.methods, + methods = _ref2$methods === void 0 ? {} : _ref2$methods, + _ref2$attachments = _ref2.attachments, + attachments = _ref2$attachments === void 0 ? {} : _ref2$attachments, + _ref2$options = _ref2.options, + options = _ref2$options === void 0 ? {} : _ref2$options, + _ref2$localDocuments = _ref2.localDocuments, + localDocuments = _ref2$localDocuments === void 0 ? false : _ref2$localDocuments, + _ref2$cacheReplacemen = _ref2.cacheReplacementPolicy, + cacheReplacementPolicy = _ref2$cacheReplacemen === void 0 ? _queryCache.defaultCacheReplacementPolicy : _ref2$cacheReplacemen, + _ref2$conflictHandler = _ref2.conflictHandler, + conflictHandler = _ref2$conflictHandler === void 0 ? _replicationProtocol.defaultConflictHandler : _ref2$conflictHandler; var storageInstanceCreationParams = { databaseInstanceToken: database.token, databaseName: database.name, @@ -7042,16 +6054,16 @@ function createRxCollection(_ref) { var collection = new RxCollectionBase(database, name, schema, storageInstance, instanceCreationOptions, migrationStrategies, methods, attachments, options, cacheReplacementPolicy, statics, conflictHandler); return collection.prepare().then(function () { // ORM add statics - Object.entries(statics).forEach(function (_ref2) { - var funName = _ref2[0], - fun = _ref2[1]; + Object.entries(statics).forEach(function (_ref3) { + var funName = _ref3[0], + fun = _ref3[1]; Object.defineProperty(collection, funName, { get: function get() { return fun.bind(collection); } }); }); - var ret = _util.PROMISE_RESOLVE_VOID; + var ret = _utils.PROMISE_RESOLVE_VOID; if (autoMigrate && collection.schema.version !== 0) { ret = collection.migratePromise(); } @@ -7089,395 +6101,296 @@ function isRxCollection(obj) { return obj instanceof RxCollectionBase; } -},{"./change-event-buffer":2,"./doc-cache":4,"./hooks":6,"./query-cache":19,"./replication-protocol":25,"./rx-collection-helper":29,"./rx-document-prototype-merge":33,"./rx-error":35,"./rx-query":37,"./rx-storage-helper":40,"./util":44,"@babel/runtime/helpers/createClass":48,"@babel/runtime/helpers/interopRequireDefault":51,"rxjs/operators":683}],31:[function(require,module,exports){ +},{"./change-event-buffer":2,"./doc-cache":4,"./hooks":6,"./incremental-write":7,"./plugins/utils":12,"./query-cache":25,"./replication-protocol":31,"./rx-collection-helper":35,"./rx-document":40,"./rx-document-prototype-merge":39,"./rx-error":41,"./rx-query":43,"./rx-storage-helper":46,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/createClass":54,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"rxjs/operators":648}],37:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.STORAGE_TOKEN_DOCUMENT_KEY = exports.STORAGE_TOKEN_DOCUMENT_ID = exports.INTERNAL_STORE_SCHEMA_TITLE = exports.INTERNAL_STORE_SCHEMA = exports.INTERNAL_CONTEXT_STORAGE_TOKEN = exports.INTERNAL_CONTEXT_COLLECTION = void 0; exports._collectionNamePrimary = _collectionNamePrimary; -exports.getAllCollectionDocuments = exports.ensureStorageTokenDocumentExists = exports.addConnectedStorageToCollection = void 0; +exports.addConnectedStorageToCollection = addConnectedStorageToCollection; +exports.ensureStorageTokenDocumentExists = ensureStorageTokenDocumentExists; +exports.getAllCollectionDocuments = getAllCollectionDocuments; exports.getPrimaryKeyOfInternalDocument = getPrimaryKeyOfInternalDocument; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxError = require("./rx-error"); var _rxSchemaHelper = require("./rx-schema-helper"); var _rxStorageHelper = require("./rx-storage-helper"); -var _util = require("./util"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); +var _utils = require("./plugins/utils"); +var INTERNAL_CONTEXT_COLLECTION = 'collection'; +exports.INTERNAL_CONTEXT_COLLECTION = INTERNAL_CONTEXT_COLLECTION; +var INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token'; + +/** + * Do not change the title, + * we have to flag the internal schema so that + * some RxStorage implementations are able + * to detect if the created RxStorageInstance + * is from the internals or not, + * to do some optimizations in some cases. + */ +exports.INTERNAL_CONTEXT_STORAGE_TOKEN = INTERNAL_CONTEXT_STORAGE_TOKEN; +var INTERNAL_STORE_SCHEMA_TITLE = 'RxInternalDocument'; +exports.INTERNAL_STORE_SCHEMA_TITLE = INTERNAL_STORE_SCHEMA_TITLE; +var INTERNAL_STORE_SCHEMA = (0, _rxSchemaHelper.fillWithDefaultSettings)({ + version: 0, + title: INTERNAL_STORE_SCHEMA_TITLE, + primaryKey: { + key: 'id', + fields: ['context', 'key'], + separator: '|' + }, + type: 'object', + properties: { + id: { + type: 'string', + maxLength: 200 + }, + key: { + type: 'string' + }, + context: { + type: 'string', + "enum": [INTERNAL_CONTEXT_COLLECTION, INTERNAL_CONTEXT_STORAGE_TOKEN, 'OTHER'] + }, + data: { + type: 'object', + additionalProperties: true } + }, + indexes: [], + required: ['key', 'context', 'data'], + additionalProperties: false, + /** + * If the sharding plugin is used, + * it must not shard on the internal RxStorageInstance + * because that one anyway has only a small amount of documents + * and also its creation is in the hot path of the initial page load, + * so we should spend less time creating multiple RxStorageInstances. + */ + sharding: { + shards: 1, + mode: 'collection' } +}); +exports.INTERNAL_STORE_SCHEMA = INTERNAL_STORE_SCHEMA; +function getPrimaryKeyOfInternalDocument(key, context) { + return (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(INTERNAL_STORE_SCHEMA, { + key: key, + context: context + }); } -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; + +/** + * Returns all internal documents + * with context 'collection' + */ +function getAllCollectionDocuments(_x, _x2) { + return _getAllCollectionDocuments.apply(this, arguments); } -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} -var addConnectedStorageToCollection = function addConnectedStorageToCollection(collection, storageCollectionName, schema) { - try { - var _exit = false; - var collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema); - var collectionDocId = getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION); - return Promise.resolve(_for(function () { - return !_exit; - }, void 0, function () { - return Promise.resolve((0, _rxStorageHelper.getSingleDocument)(collection.database.internalStore, collectionDocId)).then(function (collectionDoc) { - var saveData = (0, _util.clone)((0, _util.ensureNotFalsy)(collectionDoc)); - /** - * Add array if not exist for backwards compatibility - * TODO remove this in 2023 - */ - if (!saveData.data.connectedStorages) { - saveData.data.connectedStorages = []; - } - - // do nothing if already in array - var alreadyThere = saveData.data.connectedStorages.find(function (row) { - return row.collectionName === storageCollectionName && row.schema.version === schema.version; - }); - if (alreadyThere) { - _exit = true; - return; - } - - // otherwise add to array and save - saveData.data.connectedStorages.push({ - collectionName: storageCollectionName, - schema: schema - }); - return _catch(function () { - return Promise.resolve((0, _rxStorageHelper.writeSingle)(collection.database.internalStore, { - previous: (0, _util.ensureNotFalsy)(collectionDoc), - document: saveData - }, 'add-connected-storage-to-collection')).then(function () {}); - }, function (err) { - if (!(0, _rxError.isBulkWriteConflictError)(err)) { - throw err; - } - }); - }); - })); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * returns the primary for a given collection-data - * used in the internal store of a RxDatabase - */ -exports.addConnectedStorageToCollection = addConnectedStorageToCollection; -var ensureStorageTokenDocumentExists = function ensureStorageTokenDocumentExists(rxDatabase) { - try { - /** - * To have less read-write cycles, - * we just try to insert a new document - * and only fetch the existing one if a conflict happened. - */ - var storageToken = (0, _util.randomCouchString)(10); - var passwordHash = rxDatabase.password ? (0, _util.fastUnsecureHash)(rxDatabase.password) : undefined; - var docData = { - id: STORAGE_TOKEN_DOCUMENT_ID, - context: INTERNAL_CONTEXT_STORAGE_TOKEN, - key: STORAGE_TOKEN_DOCUMENT_KEY, - data: { - token: storageToken, - /** - * We add the instance token here - * to be able to detect if a given RxDatabase instance - * is the first instance that was ever created - * or if databases have existed earlier on that storage - * with the same database name. - */ - instanceToken: rxDatabase.token, - passwordHash: passwordHash - }, - _deleted: false, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }; - return Promise.resolve(rxDatabase.internalStore.bulkWrite([{ - document: docData - }], 'internal-add-storage-token')).then(function (writeResult) { - if (writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) { - return writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]; - } - - /** - * If we get a 409 error, - * it means another instance already inserted the storage token. - * So we get that token from the database and return that one. - */ - var error = (0, _util.ensureNotFalsy)(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]); - if (error.isError && error.status === 409) { - var conflictError = error; - if (passwordHash && passwordHash !== (0, _util.ensureNotFalsy)(conflictError.documentInDb).data.passwordHash) { - throw (0, _rxError.newRxError)('DB1', { - passwordHash: passwordHash, - existingPasswordHash: (0, _util.ensureNotFalsy)(conflictError.documentInDb).data.passwordHash - }); - } - var storageTokenDocInDb = conflictError.documentInDb; - return (0, _util.ensureNotFalsy)(storageTokenDocInDb); - } - throw error; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.ensureStorageTokenDocumentExists = ensureStorageTokenDocumentExists; -/** - * Returns all internal documents - * with context 'collection' - */ -var getAllCollectionDocuments = function getAllCollectionDocuments(storageStatics, storageInstance) { - try { - var getAllQueryPrepared = storageStatics.prepareQuery(storageInstance.schema, { - selector: { - context: INTERNAL_CONTEXT_COLLECTION - }, - sort: [{ - id: 'asc' - }], - skip: 0 - }); - return Promise.resolve(storageInstance.query(getAllQueryPrepared)).then(function (queryResult) { - var allDocs = queryResult.documents; - return allDocs; - }); - } catch (e) { - return Promise.reject(e); - } -}; /** * to not confuse multiInstance-messages with other databases that have the same * name and adapter, but do not share state with this one (for example in-memory-instances), * we set a storage-token and use it in the broadcast-channel */ -exports.getAllCollectionDocuments = getAllCollectionDocuments; -var INTERNAL_CONTEXT_COLLECTION = 'collection'; -exports.INTERNAL_CONTEXT_COLLECTION = INTERNAL_CONTEXT_COLLECTION; -var INTERNAL_CONTEXT_STORAGE_TOKEN = 'storage-token'; - -/** - * Do not change the title, - * we have to flag the internal schema so that - * some RxStorage implementations are able - * to detect if the created RxStorageInstance - * is from the internals or not, - * to do some optimizations in some cases. - */ -exports.INTERNAL_CONTEXT_STORAGE_TOKEN = INTERNAL_CONTEXT_STORAGE_TOKEN; -var INTERNAL_STORE_SCHEMA_TITLE = 'RxInternalDocument'; -exports.INTERNAL_STORE_SCHEMA_TITLE = INTERNAL_STORE_SCHEMA_TITLE; -var INTERNAL_STORE_SCHEMA = (0, _rxSchemaHelper.fillWithDefaultSettings)({ - version: 0, - title: INTERNAL_STORE_SCHEMA_TITLE, - primaryKey: { - key: 'id', - fields: ['context', 'key'], - separator: '|' - }, - type: 'object', - properties: { - id: { - type: 'string', - maxLength: 200 - }, - key: { - type: 'string' - }, - context: { - type: 'string', - "enum": [INTERNAL_CONTEXT_COLLECTION, INTERNAL_CONTEXT_STORAGE_TOKEN, 'OTHER'] - }, - data: { - type: 'object', - additionalProperties: true - } - }, - indexes: [], - required: ['key', 'context', 'data'], - additionalProperties: false, - /** - * If the sharding plugin is used, - * it must not shard on the internal RxStorageInstance - * because that one anyway has only a small amount of documents - * and also its creation is in the hot path of the initial page load, - * so we should spend less time creating multiple RxStorageInstances. - */ - sharding: { - shards: 1, - mode: 'collection' - } -}); -exports.INTERNAL_STORE_SCHEMA = INTERNAL_STORE_SCHEMA; -function getPrimaryKeyOfInternalDocument(key, context) { - return (0, _rxSchemaHelper.getComposedPrimaryKeyOfDocumentData)(INTERNAL_STORE_SCHEMA, { - key: key, - context: context - }); +function _getAllCollectionDocuments() { + _getAllCollectionDocuments = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageStatics, storageInstance) { + var getAllQueryPrepared, queryResult, allDocs; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + getAllQueryPrepared = storageStatics.prepareQuery(storageInstance.schema, { + selector: { + context: INTERNAL_CONTEXT_COLLECTION + }, + sort: [{ + id: 'asc' + }], + skip: 0 + }); + _context.next = 3; + return storageInstance.query(getAllQueryPrepared); + case 3: + queryResult = _context.sent; + allDocs = queryResult.documents; + return _context.abrupt("return", allDocs); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getAllCollectionDocuments.apply(this, arguments); } var STORAGE_TOKEN_DOCUMENT_KEY = 'storageToken'; exports.STORAGE_TOKEN_DOCUMENT_KEY = STORAGE_TOKEN_DOCUMENT_KEY; var STORAGE_TOKEN_DOCUMENT_ID = getPrimaryKeyOfInternalDocument(STORAGE_TOKEN_DOCUMENT_KEY, INTERNAL_CONTEXT_STORAGE_TOKEN); exports.STORAGE_TOKEN_DOCUMENT_ID = STORAGE_TOKEN_DOCUMENT_ID; +function ensureStorageTokenDocumentExists(_x3) { + return _ensureStorageTokenDocumentExists.apply(this, arguments); +} +function _ensureStorageTokenDocumentExists() { + _ensureStorageTokenDocumentExists = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxDatabase) { + var storageToken, passwordHash, docData, writeResult, error, conflictError, storageTokenDocInDb; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + /** + * To have less read-write cycles, + * we just try to insert a new document + * and only fetch the existing one if a conflict happened. + */ + storageToken = (0, _utils.randomCouchString)(10); + passwordHash = rxDatabase.password ? (0, _utils.fastUnsecureHash)(rxDatabase.password) : undefined; + docData = { + id: STORAGE_TOKEN_DOCUMENT_ID, + context: INTERNAL_CONTEXT_STORAGE_TOKEN, + key: STORAGE_TOKEN_DOCUMENT_KEY, + data: { + token: storageToken, + /** + * We add the instance token here + * to be able to detect if a given RxDatabase instance + * is the first instance that was ever created + * or if databases have existed earlier on that storage + * with the same database name. + */ + instanceToken: rxDatabase.token, + passwordHash: passwordHash + }, + _deleted: false, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }; + _context2.next = 5; + return rxDatabase.internalStore.bulkWrite([{ + document: docData + }], 'internal-add-storage-token'); + case 5: + writeResult = _context2.sent; + if (!writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]) { + _context2.next = 8; + break; + } + return _context2.abrupt("return", writeResult.success[STORAGE_TOKEN_DOCUMENT_ID]); + case 8: + /** + * If we get a 409 error, + * it means another instance already inserted the storage token. + * So we get that token from the database and return that one. + */ + error = (0, _utils.ensureNotFalsy)(writeResult.error[STORAGE_TOKEN_DOCUMENT_ID]); + if (!(error.isError && error.status === 409)) { + _context2.next = 15; + break; + } + conflictError = error; + if (!(passwordHash && passwordHash !== conflictError.documentInDb.data.passwordHash)) { + _context2.next = 13; + break; + } + throw (0, _rxError.newRxError)('DB1', { + passwordHash: passwordHash, + existingPasswordHash: conflictError.documentInDb.data.passwordHash + }); + case 13: + storageTokenDocInDb = conflictError.documentInDb; + return _context2.abrupt("return", (0, _utils.ensureNotFalsy)(storageTokenDocInDb)); + case 15: + throw error; + case 16: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _ensureStorageTokenDocumentExists.apply(this, arguments); +} +function addConnectedStorageToCollection(_x4, _x5, _x6) { + return _addConnectedStorageToCollection.apply(this, arguments); +} +/** + * returns the primary for a given collection-data + * used in the internal store of a RxDatabase + */ +function _addConnectedStorageToCollection() { + _addConnectedStorageToCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collection, storageCollectionName, schema) { + var collectionNameWithVersion, collectionDocId, collectionDoc, saveData, alreadyThere; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + collectionNameWithVersion = _collectionNamePrimary(collection.name, collection.schema.jsonSchema); + collectionDocId = getPrimaryKeyOfInternalDocument(collectionNameWithVersion, INTERNAL_CONTEXT_COLLECTION); + case 2: + if (!true) { + _context3.next = 23; + break; + } + _context3.next = 5; + return (0, _rxStorageHelper.getSingleDocument)(collection.database.internalStore, collectionDocId); + case 5: + collectionDoc = _context3.sent; + saveData = (0, _utils.clone)((0, _utils.ensureNotFalsy)(collectionDoc)); + /** + * Add array if not exist for backwards compatibility + * TODO remove this in 2023 + */ + if (!saveData.data.connectedStorages) { + saveData.data.connectedStorages = []; + } + + // do nothing if already in array + alreadyThere = saveData.data.connectedStorages.find(function (row) { + return row.collectionName === storageCollectionName && row.schema.version === schema.version; + }); + if (!alreadyThere) { + _context3.next = 11; + break; + } + return _context3.abrupt("return"); + case 11: + // otherwise add to array and save + saveData.data.connectedStorages.push({ + collectionName: storageCollectionName, + schema: schema + }); + _context3.prev = 12; + _context3.next = 15; + return (0, _rxStorageHelper.writeSingle)(collection.database.internalStore, { + previous: (0, _utils.ensureNotFalsy)(collectionDoc), + document: saveData + }, 'add-connected-storage-to-collection'); + case 15: + _context3.next = 21; + break; + case 17: + _context3.prev = 17; + _context3.t0 = _context3["catch"](12); + if ((0, _rxError.isBulkWriteConflictError)(_context3.t0)) { + _context3.next = 21; + break; + } + throw _context3.t0; + case 21: + _context3.next = 2; + break; + case 23: + case "end": + return _context3.stop(); + } + }, _callee3, null, [[12, 17]]); + })); + return _addConnectedStorageToCollection.apply(this, arguments); +} function _collectionNamePrimary(name, schema) { return name + '-' + schema.version; } -},{"./rx-error":35,"./rx-schema-helper":38,"./rx-storage-helper":40,"./util":44}],32:[function(require,module,exports){ +},{"./plugins/utils":12,"./rx-error":41,"./rx-schema-helper":44,"./rx-storage-helper":46,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66}],38:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -7486,14 +6399,17 @@ Object.defineProperty(exports, "__esModule", { }); exports.RxDatabaseBase = void 0; exports.createRxDatabase = createRxDatabase; -exports.createRxDatabaseStorageInstance = void 0; +exports.createRxDatabaseStorageInstance = createRxDatabaseStorageInstance; exports.dbCount = dbCount; -exports.ensureNoStartupErrors = void 0; +exports.ensureNoStartupErrors = ensureNoStartupErrors; exports.isRxDatabase = isRxDatabase; -exports.removeRxDatabase = exports.isRxDatabaseFirstTimeInstantiated = void 0; +exports.isRxDatabaseFirstTimeInstantiated = isRxDatabaseFirstTimeInstantiated; +exports.removeRxDatabase = removeRxDatabase; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _customIdleQueue = require("custom-idle-queue"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _rxSchema = require("./rx-schema"); var _hooks = require("./hooks"); @@ -7505,98 +6421,8 @@ var _obliviousSet = require("oblivious-set"); var _rxDatabaseInternalStore = require("./rx-database-internal-store"); var _rxCollectionHelper = require("./rx-collection-helper"); /** - * For better performance some tasks run async - * and are awaited later. - * But we still have to ensure that there have been no errors - * on database creation. - */ -var ensureNoStartupErrors = function ensureNoStartupErrors(rxDatabase) { - try { - return Promise.resolve(rxDatabase.storageToken).then(function () { - if (rxDatabase.startupErrors[0]) { - throw rxDatabase.startupErrors[0]; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.ensureNoStartupErrors = ensureNoStartupErrors; -/** - * Returns true if the given RxDatabase was the first - * instance that was created on the storage with this name. - * - * Can be used for some optimizations because on the first instantiation, - * we can assume that no data was written before. - */ -var isRxDatabaseFirstTimeInstantiated = function isRxDatabaseFirstTimeInstantiated(database) { - try { - return Promise.resolve(database.storageTokenDocument).then(function (tokenDoc) { - return tokenDoc.data.instanceToken === database.token; - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.isRxDatabaseFirstTimeInstantiated = isRxDatabaseFirstTimeInstantiated; -/** - * Removes the database and all its known data - * with all known collections and all internal meta data. - * - * Returns the names of the removed collections. - */ -var removeRxDatabase = function removeRxDatabase(databaseName, storage) { - try { - var databaseInstanceToken = (0, _util.randomCouchString)(10); - return Promise.resolve(createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, {}, false)).then(function (dbInternalsStorageInstance) { - return Promise.resolve((0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, dbInternalsStorageInstance)).then(function (collectionDocs) { - var collectionNames = new Set(); - collectionDocs.forEach(function (doc) { - return collectionNames.add(doc.data.name); - }); - var removedCollectionNames = Array.from(collectionNames); - return Promise.resolve(Promise.all(removedCollectionNames.map(function (collectionName) { - return (0, _rxCollectionHelper.removeCollectionStorages)(storage, dbInternalsStorageInstance, databaseInstanceToken, databaseName, collectionName); - }))).then(function () { - return Promise.resolve((0, _hooks.runAsyncPluginHooks)('postRemoveRxDatabase', { - databaseName: databaseName, - storage: storage - })).then(function () { - return Promise.resolve(dbInternalsStorageInstance.remove()).then(function () { - return removedCollectionNames; - }); - }); - }); - }); - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.removeRxDatabase = removeRxDatabase; -/** - * Creates the storage instances that are used internally in the database - * to store schemas and other configuration stuff. - */ -var createRxDatabaseStorageInstance = function createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, options, multiInstance, password) { - try { - return Promise.resolve(storage.createStorageInstance({ - databaseInstanceToken: databaseInstanceToken, - databaseName: databaseName, - collectionName: _rxStorageHelper.INTERNAL_STORAGE_NAME, - schema: _rxDatabaseInternalStore.INTERNAL_STORE_SCHEMA, - options: options, - multiInstance: multiInstance, - password: password - })); - } catch (e) { - return Promise.reject(e); - } -}; -exports.createRxDatabaseStorageInstance = createRxDatabaseStorageInstance; -/** - * stores the used database names - * so we can throw when the same database is created more then once. + * stores the used database names + * so we can throw when the same database is created more then once. */ var USED_DATABASE_NAMES = new Set(); var DB_COUNT = 0; @@ -7628,8 +6454,8 @@ var RxDatabaseBase = /*#__PURE__*/function () { this.observable$ = this.eventBulks$.pipe((0, _operators.mergeMap)(function (changeEventBulk) { return changeEventBulk.events; })); - this.storageToken = _util.PROMISE_RESOLVE_FALSE; - this.storageTokenDocument = _util.PROMISE_RESOLVE_FALSE; + this.storageToken = _utils.PROMISE_RESOLVE_FALSE; + this.storageTokenDocument = _utils.PROMISE_RESOLVE_FALSE; this.emittedEventBulkIds = new _obliviousSet.ObliviousSet(60 * 1000); this.name = name; this.token = token; @@ -7702,27 +6528,45 @@ var RxDatabaseBase = /*#__PURE__*/function () { /** * removes the collection-doc from the internalStore */; - _proto.removeCollectionDoc = function removeCollectionDoc(name, schema) { - try { - var _this2 = this; - return Promise.resolve((0, _rxStorageHelper.getSingleDocument)(_this2.internalStore, (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)((0, _rxDatabaseInternalStore._collectionNamePrimary)(name, schema), _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION))).then(function (doc) { - if (!doc) { - throw (0, _rxError.newRxError)('SNH', { - name: name, - schema: schema - }); - } - var writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); - writeDoc._deleted = true; - return Promise.resolve(_this2.internalStore.bulkWrite([{ - document: writeDoc, - previous: doc - }], 'rx-database-remove-collection')).then(function () {}); - }); - } catch (e) { - return Promise.reject(e); + _proto.removeCollectionDoc = + /*#__PURE__*/ + function () { + var _removeCollectionDoc = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(name, schema) { + var doc, writeDoc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _rxStorageHelper.getSingleDocument)(this.internalStore, (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)((0, _rxDatabaseInternalStore._collectionNamePrimary)(name, schema), _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION)); + case 2: + doc = _context.sent; + if (doc) { + _context.next = 5; + break; + } + throw (0, _rxError.newRxError)('SNH', { + name: name, + schema: schema + }); + case 5: + writeDoc = (0, _rxStorageHelper.flatCloneDocWithMeta)(doc); + writeDoc._deleted = true; + _context.next = 9; + return this.internalStore.bulkWrite([{ + document: writeDoc, + previous: doc + }], 'rx-database-remove-collection'); + case 9: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function removeCollectionDoc(_x, _x2) { + return _removeCollectionDoc.apply(this, arguments); } - } + return removeCollectionDoc; + }() /** * creates multiple RxCollections at once * to be much faster by saving db txs and doing stuff in bulk-operations @@ -7730,111 +6574,146 @@ var RxDatabaseBase = /*#__PURE__*/function () { * So it must be as fast as possible. */ ; - _proto.addCollections = function addCollections(collectionCreators) { - try { - var _this3 = this; - var jsonSchemas = {}; - var schemas = {}; - var bulkPutDocs = []; - var useArgsByCollectionName = {}; - Object.entries(collectionCreators).forEach(function (_ref) { - var name = _ref[0], - args = _ref[1]; - var collectionName = name; - var rxJsonSchema = args.schema; - jsonSchemas[collectionName] = rxJsonSchema; - var schema = (0, _rxSchema.createRxSchema)(rxJsonSchema); - schemas[collectionName] = schema; - - // collection already exists - if (_this3.collections[name]) { - throw (0, _rxError.newRxError)('DB3', { - name: name - }); - } - var collectionNameWithVersion = (0, _rxDatabaseInternalStore._collectionNamePrimary)(name, rxJsonSchema); - var collectionDocData = { - id: (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)(collectionNameWithVersion, _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION), - key: collectionNameWithVersion, - context: _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION, - data: { - name: collectionName, - schemaHash: schema.hash, - schema: schema.jsonSchema, - version: schema.version, - connectedStorages: [] - }, - _deleted: false, - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), - _attachments: {} - }; - bulkPutDocs.push({ - document: collectionDocData - }); - var useArgs = Object.assign({}, args, { - name: collectionName, - schema: schema, - database: _this3 - }); - - // run hooks - var hookData = (0, _util.flatClone)(args); - hookData.database = _this3; - hookData.name = name; - (0, _hooks.runPluginHooks)('preCreateRxCollection', hookData); - useArgs.conflictHandler = hookData.conflictHandler; - useArgsByCollectionName[collectionName] = useArgs; - }); - return Promise.resolve(_this3.internalStore.bulkWrite(bulkPutDocs, 'rx-database-add-collection')).then(function (putDocsResult) { - return Promise.resolve(ensureNoStartupErrors(_this3)).then(function () { - Object.entries(putDocsResult.error).forEach(function (_ref2) { - var _id = _ref2[0], - error = _ref2[1]; - var docInDb = (0, _util.ensureNotFalsy)(error.documentInDb); - var collectionName = docInDb.data.name; - var schema = schemas[collectionName]; - // collection already exists but has different schema - if (docInDb.data.schemaHash !== schema.hash) { - throw (0, _rxError.newRxError)('DB6', { - database: _this3.name, - collection: collectionName, - previousSchemaHash: docInDb.data.schemaHash, - schemaHash: schema.hash, - previousSchema: docInDb.data.schema, - schema: (0, _util.ensureNotFalsy)(jsonSchemas[collectionName]) + _proto.addCollections = + /*#__PURE__*/ + function () { + var _addCollections = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(collectionCreators) { + var _this2 = this; + var jsonSchemas, schemas, bulkPutDocs, useArgsByCollectionName, putDocsResult, ret; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + jsonSchemas = {}; + schemas = {}; + bulkPutDocs = []; + useArgsByCollectionName = {}; + Object.entries(collectionCreators).forEach(function (_ref) { + var name = _ref[0], + args = _ref[1]; + var collectionName = name; + var rxJsonSchema = args.schema; + jsonSchemas[collectionName] = rxJsonSchema; + var schema = (0, _rxSchema.createRxSchema)(rxJsonSchema); + schemas[collectionName] = schema; + + // collection already exists + if (_this2.collections[name]) { + throw (0, _rxError.newRxError)('DB3', { + name: name + }); + } + var collectionNameWithVersion = (0, _rxDatabaseInternalStore._collectionNamePrimary)(name, rxJsonSchema); + var collectionDocData = { + id: (0, _rxDatabaseInternalStore.getPrimaryKeyOfInternalDocument)(collectionNameWithVersion, _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION), + key: collectionNameWithVersion, + context: _rxDatabaseInternalStore.INTERNAL_CONTEXT_COLLECTION, + data: { + name: collectionName, + schemaHash: schema.hash, + schema: schema.jsonSchema, + version: schema.version, + connectedStorages: [] + }, + _deleted: false, + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), + _attachments: {} + }; + bulkPutDocs.push({ + document: collectionDocData }); - } - }); - var ret = {}; - return Promise.resolve(Promise.all(Object.keys(collectionCreators).map(function (collectionName) { - try { - var useArgs = useArgsByCollectionName[collectionName]; - return Promise.resolve((0, _rxCollection.createRxCollection)(useArgs)).then(function (collection) { - ret[collectionName] = collection; - - // set as getter to the database - _this3.collections[collectionName] = collection; - if (!_this3[collectionName]) { - Object.defineProperty(_this3, collectionName, { - get: function get() { - return _this3.collections[collectionName]; - } - }); - } + var useArgs = Object.assign({}, args, { + name: collectionName, + schema: schema, + database: _this2 }); - } catch (e) { - return Promise.reject(e); - } - }))).then(function () { - return ret; - }); - }); - }); - } catch (e) { - return Promise.reject(e); + + // run hooks + var hookData = (0, _utils.flatClone)(args); + hookData.database = _this2; + hookData.name = name; + (0, _hooks.runPluginHooks)('preCreateRxCollection', hookData); + useArgs.conflictHandler = hookData.conflictHandler; + useArgsByCollectionName[collectionName] = useArgs; + }); + _context3.next = 7; + return this.internalStore.bulkWrite(bulkPutDocs, 'rx-database-add-collection'); + case 7: + putDocsResult = _context3.sent; + _context3.next = 10; + return ensureNoStartupErrors(this); + case 10: + Object.entries(putDocsResult.error).forEach(function (_ref2) { + var _id = _ref2[0], + error = _ref2[1]; + if (error.status !== 409) { + throw (0, _rxError.newRxError)('DB12', { + database: _this2.name, + writeError: error + }); + } + var docInDb = (0, _utils.ensureNotFalsy)(error.documentInDb); + var collectionName = docInDb.data.name; + var schema = schemas[collectionName]; + // collection already exists but has different schema + if (docInDb.data.schemaHash !== schema.hash) { + throw (0, _rxError.newRxError)('DB6', { + database: _this2.name, + collection: collectionName, + previousSchemaHash: docInDb.data.schemaHash, + schemaHash: schema.hash, + previousSchema: docInDb.data.schema, + schema: (0, _utils.ensureNotFalsy)(jsonSchemas[collectionName]) + }); + } + }); + ret = {}; + _context3.next = 14; + return Promise.all(Object.keys(collectionCreators).map( /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(collectionName) { + var useArgs, collection; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + useArgs = useArgsByCollectionName[collectionName]; + _context2.next = 3; + return (0, _rxCollection.createRxCollection)(useArgs); + case 3: + collection = _context2.sent; + ret[collectionName] = collection; + + // set as getter to the database + _this2.collections[collectionName] = collection; + if (!_this2[collectionName]) { + Object.defineProperty(_this2, collectionName, { + get: function get() { + return _this2.collections[collectionName]; + } + }); + } + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return function (_x4) { + return _ref3.apply(this, arguments); + }; + }())); + case 14: + return _context3.abrupt("return", ret); + case 15: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function addCollections(_x3) { + return _addCollections.apply(this, arguments); } - } + return addCollections; + }() /** * runs the given function between idleQueue-locking */ @@ -7850,7 +6729,7 @@ var RxDatabaseBase = /*#__PURE__*/function () { * Export database to a JSON friendly format. */; _proto.exportJSON = function exportJSON(_collections) { - throw (0, _util.pluginMissing)('json-dump'); + throw (0, _utils.pluginMissing)('json-dump'); } /** @@ -7860,96 +6739,114 @@ var RxDatabaseBase = /*#__PURE__*/function () { * since data could be encrypted. */; _proto.importJSON = function importJSON(_exportedJSON) { - throw (0, _util.pluginMissing)('json-dump'); - }; - _proto.serverCouchDB = function serverCouchDB(_options) { - throw (0, _util.pluginMissing)('server-couchdb'); + throw (0, _utils.pluginMissing)('json-dump'); }; _proto.backup = function backup(_options) { - throw (0, _util.pluginMissing)('backup'); + throw (0, _utils.pluginMissing)('backup'); }; _proto.leaderElector = function leaderElector() { - throw (0, _util.pluginMissing)('leader-election'); + throw (0, _utils.pluginMissing)('leader-election'); }; _proto.isLeader = function isLeader() { - throw (0, _util.pluginMissing)('leader-election'); + throw (0, _utils.pluginMissing)('leader-election'); } /** * returns a promise which resolves when the instance becomes leader */; _proto.waitForLeadership = function waitForLeadership() { - throw (0, _util.pluginMissing)('leader-election'); + throw (0, _utils.pluginMissing)('leader-election'); }; _proto.migrationStates = function migrationStates() { - throw (0, _util.pluginMissing)('migration'); + throw (0, _utils.pluginMissing)('migration'); } /** * destroys the database-instance and all collections */; - _proto.destroy = function destroy() { - try { - var _this4 = this; - if (_this4.destroyed) { - return Promise.resolve(_util.PROMISE_RESOLVE_FALSE); - } - - // settings destroyed = true must be the first thing to do. - _this4.destroyed = true; - return Promise.resolve((0, _hooks.runAsyncPluginHooks)('preDestroyRxDatabase', _this4)).then(function () { - /** - * Complete the event stream - * to stop all subscribers who forgot to unsubscribe. - */ - _this4.eventBulks$.complete(); - DB_COUNT--; - _this4._subs.map(function (sub) { - return sub.unsubscribe(); - }); + _proto.destroy = + /*#__PURE__*/ + function () { + var _destroy = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var _this3 = this; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!this.destroyed) { + _context4.next = 2; + break; + } + return _context4.abrupt("return", _utils.PROMISE_RESOLVE_FALSE); + case 2: + // settings destroyed = true must be the first thing to do. + this.destroyed = true; + _context4.next = 5; + return (0, _hooks.runAsyncPluginHooks)('preDestroyRxDatabase', this); + case 5: + /** + * Complete the event stream + * to stop all subscribers who forgot to unsubscribe. + */ + this.eventBulks$.complete(); + DB_COUNT--; + this._subs.map(function (sub) { + return sub.unsubscribe(); + }); - /** - * Destroying the pseudo instance will throw - * because stulff is missing - * TODO we should not need the pseudo instance on runtime. - * we should generate the property list on build time. - */ - return _this4.name === 'pseudoInstance' ? _util.PROMISE_RESOLVE_FALSE : _this4.requestIdlePromise().then(function () { - return Promise.all(_this4.onDestroy.map(function (fn) { - return fn(); - })); - }) - // destroy all collections - .then(function () { - return Promise.all(Object.keys(_this4.collections).map(function (key) { - return _this4.collections[key]; - }).map(function (col) { - return col.destroy(); - })); - }) - // destroy internal storage instances - .then(function () { - return _this4.internalStore.close(); - }) - // remove combination from USED_COMBINATIONS-map - .then(function () { - return USED_DATABASE_NAMES["delete"](_this4.name); - }).then(function () { - return true; - }); - }); - } catch (e) { - return Promise.reject(e); + /** + * Destroying the pseudo instance will throw + * because stulff is missing + * TODO we should not need the pseudo instance on runtime. + * we should generate the property list on build time. + */ + if (!(this.name === 'pseudoInstance')) { + _context4.next = 10; + break; + } + return _context4.abrupt("return", _utils.PROMISE_RESOLVE_FALSE); + case 10: + return _context4.abrupt("return", this.requestIdlePromise().then(function () { + return Promise.all(_this3.onDestroy.map(function (fn) { + return fn(); + })); + }) + // destroy all collections + .then(function () { + return Promise.all(Object.keys(_this3.collections).map(function (key) { + return _this3.collections[key]; + }).map(function (col) { + return col.destroy(); + })); + }) + // destroy internal storage instances + .then(function () { + return _this3.internalStore.close(); + }) + // remove combination from USED_COMBINATIONS-map + .then(function () { + return USED_DATABASE_NAMES["delete"](_this3.name); + }).then(function () { + return true; + })); + case 11: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function destroy() { + return _destroy.apply(this, arguments); } - } + return destroy; + }() /** * deletes the database and its stored data. * Returns the names of all removed collections. */ ; _proto.remove = function remove() { - var _this5 = this; + var _this4 = this; return this.destroy().then(function () { - return removeRxDatabase(_this5.name, _this5.storage); + return removeRxDatabase(_this4.name, _this4.storage); }); }; (0, _createClass2["default"])(RxDatabaseBase, [{ @@ -7980,26 +6877,61 @@ function throwIfDatabaseNameUsed(name) { }); } } -function createRxDatabase(_ref3) { - var storage = _ref3.storage, - instanceCreationOptions = _ref3.instanceCreationOptions, - name = _ref3.name, - password = _ref3.password, - _ref3$multiInstance = _ref3.multiInstance, - multiInstance = _ref3$multiInstance === void 0 ? true : _ref3$multiInstance, - _ref3$eventReduce = _ref3.eventReduce, - eventReduce = _ref3$eventReduce === void 0 ? false : _ref3$eventReduce, - _ref3$ignoreDuplicate = _ref3.ignoreDuplicate, - ignoreDuplicate = _ref3$ignoreDuplicate === void 0 ? false : _ref3$ignoreDuplicate, - _ref3$options = _ref3.options, - options = _ref3$options === void 0 ? {} : _ref3$options, - cleanupPolicy = _ref3.cleanupPolicy, - _ref3$allowSlowCount = _ref3.allowSlowCount, - allowSlowCount = _ref3$allowSlowCount === void 0 ? false : _ref3$allowSlowCount, - _ref3$localDocuments = _ref3.localDocuments, - localDocuments = _ref3$localDocuments === void 0 ? false : _ref3$localDocuments, - _ref3$hashFunction = _ref3.hashFunction, - hashFunction = _ref3$hashFunction === void 0 ? _util.defaultHashFunction : _ref3$hashFunction; + +/** + * Creates the storage instances that are used internally in the database + * to store schemas and other configuration stuff. + */ +function createRxDatabaseStorageInstance(_x5, _x6, _x7, _x8, _x9, _x10) { + return _createRxDatabaseStorageInstance.apply(this, arguments); +} +function _createRxDatabaseStorageInstance() { + _createRxDatabaseStorageInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(databaseInstanceToken, storage, databaseName, options, multiInstance, password) { + var internalStore; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return storage.createStorageInstance({ + databaseInstanceToken: databaseInstanceToken, + databaseName: databaseName, + collectionName: _rxStorageHelper.INTERNAL_STORAGE_NAME, + schema: _rxDatabaseInternalStore.INTERNAL_STORE_SCHEMA, + options: options, + multiInstance: multiInstance, + password: password + }); + case 2: + internalStore = _context5.sent; + return _context5.abrupt("return", internalStore); + case 4: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _createRxDatabaseStorageInstance.apply(this, arguments); +} +function createRxDatabase(_ref4) { + var storage = _ref4.storage, + instanceCreationOptions = _ref4.instanceCreationOptions, + name = _ref4.name, + password = _ref4.password, + _ref4$multiInstance = _ref4.multiInstance, + multiInstance = _ref4$multiInstance === void 0 ? true : _ref4$multiInstance, + _ref4$eventReduce = _ref4.eventReduce, + eventReduce = _ref4$eventReduce === void 0 ? false : _ref4$eventReduce, + _ref4$ignoreDuplicate = _ref4.ignoreDuplicate, + ignoreDuplicate = _ref4$ignoreDuplicate === void 0 ? false : _ref4$ignoreDuplicate, + _ref4$options = _ref4.options, + options = _ref4$options === void 0 ? {} : _ref4$options, + cleanupPolicy = _ref4.cleanupPolicy, + _ref4$allowSlowCount = _ref4.allowSlowCount, + allowSlowCount = _ref4$allowSlowCount === void 0 ? false : _ref4$allowSlowCount, + _ref4$localDocuments = _ref4.localDocuments, + localDocuments = _ref4$localDocuments === void 0 ? false : _ref4$localDocuments, + _ref4$hashFunction = _ref4.hashFunction, + hashFunction = _ref4$hashFunction === void 0 ? _utils.defaultHashFunction : _ref4$hashFunction; (0, _hooks.runPluginHooks)('preCreateRxDatabase', { storage: storage, instanceCreationOptions: instanceCreationOptions, @@ -8016,7 +6948,7 @@ function createRxDatabase(_ref3) { throwIfDatabaseNameUsed(name); } USED_DATABASE_NAMES.add(name); - var databaseInstanceToken = (0, _util.randomCouchString)(10); + var databaseInstanceToken = (0, _utils.randomCouchString)(10); return createRxDatabaseStorageInstance(databaseInstanceToken, storage, name, instanceCreationOptions, multiInstance, password) /** * Creating the internal store might fail @@ -8046,6 +6978,59 @@ function createRxDatabase(_ref3) { }); }); } + +/** + * Removes the database and all its known data + * with all known collections and all internal meta data. + * + * Returns the names of the removed collections. + */ +function removeRxDatabase(_x11, _x12) { + return _removeRxDatabase.apply(this, arguments); +} +function _removeRxDatabase() { + _removeRxDatabase = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(databaseName, storage) { + var databaseInstanceToken, dbInternalsStorageInstance, collectionDocs, collectionNames, removedCollectionNames; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + databaseInstanceToken = (0, _utils.randomCouchString)(10); + _context6.next = 3; + return createRxDatabaseStorageInstance(databaseInstanceToken, storage, databaseName, {}, false); + case 3: + dbInternalsStorageInstance = _context6.sent; + _context6.next = 6; + return (0, _rxDatabaseInternalStore.getAllCollectionDocuments)(storage.statics, dbInternalsStorageInstance); + case 6: + collectionDocs = _context6.sent; + collectionNames = new Set(); + collectionDocs.forEach(function (doc) { + return collectionNames.add(doc.data.name); + }); + removedCollectionNames = Array.from(collectionNames); + _context6.next = 12; + return Promise.all(removedCollectionNames.map(function (collectionName) { + return (0, _rxCollectionHelper.removeCollectionStorages)(storage, dbInternalsStorageInstance, databaseInstanceToken, databaseName, collectionName); + })); + case 12: + _context6.next = 14; + return (0, _hooks.runAsyncPluginHooks)('postRemoveRxDatabase', { + databaseName: databaseName, + storage: storage + }); + case 14: + _context6.next = 16; + return dbInternalsStorageInstance.remove(); + case 16: + return _context6.abrupt("return", removedCollectionNames); + case 17: + case "end": + return _context6.stop(); + } + }, _callee6); + })); + return _removeRxDatabase.apply(this, arguments); +} function isRxDatabase(obj) { return obj instanceof RxDatabaseBase; } @@ -8053,14 +7038,73 @@ function dbCount() { return DB_COUNT; } -},{"./hooks":6,"./rx-collection":30,"./rx-collection-helper":29,"./rx-database-internal-store":31,"./rx-error":35,"./rx-schema":39,"./rx-storage-helper":40,"./util":44,"@babel/runtime/helpers/createClass":48,"@babel/runtime/helpers/interopRequireDefault":51,"custom-idle-queue":401,"oblivious-set":422,"rxjs":458,"rxjs/operators":683}],33:[function(require,module,exports){ +/** + * Returns true if the given RxDatabase was the first + * instance that was created on the storage with this name. + * + * Can be used for some optimizations because on the first instantiation, + * we can assume that no data was written before. + */ +function isRxDatabaseFirstTimeInstantiated(_x13) { + return _isRxDatabaseFirstTimeInstantiated.apply(this, arguments); +} +/** + * For better performance some tasks run async + * and are awaited later. + * But we still have to ensure that there have been no errors + * on database creation. + */ +function _isRxDatabaseFirstTimeInstantiated() { + _isRxDatabaseFirstTimeInstantiated = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(database) { + var tokenDoc; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return database.storageTokenDocument; + case 2: + tokenDoc = _context7.sent; + return _context7.abrupt("return", tokenDoc.data.instanceToken === database.token); + case 4: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return _isRxDatabaseFirstTimeInstantiated.apply(this, arguments); +} +function ensureNoStartupErrors(_x14) { + return _ensureNoStartupErrors.apply(this, arguments); +} +function _ensureNoStartupErrors() { + _ensureNoStartupErrors = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(rxDatabase) { + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return rxDatabase.storageToken; + case 2: + if (!rxDatabase.startupErrors[0]) { + _context8.next = 4; + break; + } + throw rxDatabase.startupErrors[0]; + case 4: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + return _ensureNoStartupErrors.apply(this, arguments); +} + +},{"./hooks":6,"./plugins/utils":12,"./rx-collection":36,"./rx-collection-helper":35,"./rx-database-internal-store":37,"./rx-error":41,"./rx-schema":45,"./rx-storage-helper":46,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/createClass":54,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"custom-idle-queue":407,"oblivious-set":420,"rxjs":423,"rxjs/operators":648}],39:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.createRxDocument = createRxDocument; -exports.createRxDocuments = createRxDocuments; +exports.createNewRxDocument = createNewRxDocument; exports.getDocumentOrmPrototype = getDocumentOrmPrototype; exports.getDocumentPrototype = getDocumentPrototype; exports.getRxDocumentConstructor = getRxDocumentConstructor; @@ -8076,46 +7120,41 @@ var _overwritable = require("./overwritable"); * In the future we should do this by chaining the __proto__ objects */ -// caches -var protoForCollection = new WeakMap(); var constructorForCollection = new WeakMap(); function getDocumentPrototype(rxCollection) { - if (!protoForCollection.has(rxCollection)) { - var schemaProto = rxCollection.schema.getDocumentPrototype(); - var ormProto = getDocumentOrmPrototype(rxCollection); - var baseProto = _rxDocument.basePrototype; - var proto = {}; - [schemaProto, ormProto, baseProto].forEach(function (obj) { - var props = Object.getOwnPropertyNames(obj); - props.forEach(function (key) { - var desc = Object.getOwnPropertyDescriptor(obj, key); + var schemaProto = rxCollection.schema.getDocumentPrototype(); + var ormProto = getDocumentOrmPrototype(rxCollection); + var baseProto = _rxDocument.basePrototype; + var proto = {}; + [schemaProto, ormProto, baseProto].forEach(function (obj) { + var props = Object.getOwnPropertyNames(obj); + props.forEach(function (key) { + var desc = Object.getOwnPropertyDescriptor(obj, key); - /** - * When enumerable is true, it will show on console.dir(instance) - * To not pollute the output, only getters and methods are enumerable - */ - var enumerable = true; - if (key.startsWith('_') || key.endsWith('_') || key.startsWith('$') || key.endsWith('$')) enumerable = false; - if (typeof desc.value === 'function') { - // when getting a function, we automatically do a .bind(this) - Object.defineProperty(proto, key, { - get: function get() { - return desc.value.bind(this); - }, - enumerable: enumerable, - configurable: false - }); - } else { - desc.enumerable = enumerable; - desc.configurable = false; - if (desc.writable) desc.writable = false; - Object.defineProperty(proto, key, desc); - } - }); + /** + * When enumerable is true, it will show on console.dir(instance) + * To not pollute the output, only getters and methods are enumerable + */ + var enumerable = true; + if (key.startsWith('_') || key.endsWith('_') || key.startsWith('$') || key.endsWith('$')) enumerable = false; + if (typeof desc.value === 'function') { + // when getting a function, we automatically do a .bind(this) + Object.defineProperty(proto, key, { + get: function get() { + return desc.value.bind(this); + }, + enumerable: enumerable, + configurable: false + }); + } else { + desc.enumerable = enumerable; + desc.configurable = false; + if (desc.writable) desc.writable = false; + Object.defineProperty(proto, key, desc); + } }); - protoForCollection.set(rxCollection, proto); - } - return protoForCollection.get(rxCollection); + }); + return proto; } function getRxDocumentConstructor(rxCollection) { if (!constructorForCollection.has(rxCollection)) { @@ -8128,33 +7167,16 @@ function getRxDocumentConstructor(rxCollection) { /** * Create a RxDocument-instance from the jsonData * and the prototype merge. - * If the document already exists in the _docCache, - * return that instead to ensure we have no duplicates. + * You should never call this method directly, + * instead you should get the document from collection._docCache.getCachedRxDocument(). */ -function createRxDocument(rxCollection, docData) { - var primary = docData[rxCollection.schema.primaryPath]; - - // return from cache if exists - var cacheDoc = rxCollection._docCache.get(primary); - if (cacheDoc) { - return cacheDoc; - } +function createNewRxDocument(rxCollection, docData) { var doc = (0, _rxDocument.createWithConstructor)(getRxDocumentConstructor(rxCollection), rxCollection, _overwritable.overwritable.deepFreezeWhenDevMode(docData)); - rxCollection._docCache.set(primary, doc); rxCollection._runHooksSync('post', 'create', docData, doc); (0, _hooks.runPluginHooks)('postCreateRxDocument', doc); return doc; } -/** - * create RxDocument from the docs-array - */ -function createRxDocuments(rxCollection, docsJSON) { - return docsJSON.map(function (json) { - return createRxDocument(rxCollection, json); - }); -} - /** * returns the prototype-object * that contains the orm-methods, @@ -8170,7 +7192,7 @@ function getDocumentOrmPrototype(rxCollection) { return proto; } -},{"./hooks":6,"./overwritable":8,"./rx-document":34}],34:[function(require,module,exports){ +},{"./hooks":6,"./overwritable":9,"./rx-document":40}],40:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -8178,197 +7200,24 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.basePrototype = void 0; +exports.beforeDocumentUpdateWrite = beforeDocumentUpdateWrite; exports.createRxDocumentConstructor = createRxDocumentConstructor; exports.createWithConstructor = createWithConstructor; exports.defineGetterSetter = defineGetterSetter; exports.isRxDocument = isRxDocument; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _objectPath = _interopRequireDefault(require("object-path")); -var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _hooks = require("./hooks"); var _rxChangeEvent = require("./rx-change-event"); var _overwritable = require("./overwritable"); var _rxSchemaHelper = require("./rx-schema-helper"); var _rxStorageHelper = require("./rx-storage-helper"); -function _catch(body, recover) { - try { - var result = body(); - } catch (e) { - return recover(e); - } - if (result && result.then) { - return result.then(void 0, recover); - } - return result; -} -function _settle(pact, state, value) { - if (!pact.s) { - if (value instanceof _Pact) { - if (value.s) { - if (state & 1) { - state = value.s; - } - value = value.v; - } else { - value.o = _settle.bind(null, pact, state); - return; - } - } - if (value && value.then) { - value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2)); - return; - } - pact.s = state; - pact.v = value; - var observer = pact.o; - if (observer) { - observer(pact); - } - } -} -var _Pact = /*#__PURE__*/function () { - function _Pact() {} - _Pact.prototype.then = function (onFulfilled, onRejected) { - var result = new _Pact(); - var state = this.s; - if (state) { - var callback = state & 1 ? onFulfilled : onRejected; - if (callback) { - try { - _settle(result, 1, callback(this.v)); - } catch (e) { - _settle(result, 2, e); - } - return result; - } else { - return this; - } - } - this.o = function (_this) { - try { - var value = _this.v; - if (_this.s & 1) { - _settle(result, 1, onFulfilled ? onFulfilled(value) : value); - } else if (onRejected) { - _settle(result, 1, onRejected(value)); - } else { - _settle(result, 2, value); - } - } catch (e) { - _settle(result, 2, e); - } - }; - return result; - }; - return _Pact; -}(); -function _isSettledPact(thenable) { - return thenable instanceof _Pact && thenable.s & 1; -} -function _for(test, update, body) { - var stage; - for (;;) { - var shouldContinue = test(); - if (_isSettledPact(shouldContinue)) { - shouldContinue = shouldContinue.v; - } - if (!shouldContinue) { - return result; - } - if (shouldContinue.then) { - stage = 0; - break; - } - var result = body(); - if (result && result.then) { - if (_isSettledPact(result)) { - result = result.s; - } else { - stage = 1; - break; - } - } - if (update) { - var updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - stage = 2; - break; - } - } - } - var pact = new _Pact(); - var reject = _settle.bind(null, pact, 2); - (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject); - return pact; - function _resumeAfterBody(value) { - result = value; - do { - if (update) { - updateValue = update(); - if (updateValue && updateValue.then && !_isSettledPact(updateValue)) { - updateValue.then(_resumeAfterUpdate).then(void 0, reject); - return; - } - } - shouldContinue = test(); - if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) { - _settle(pact, 1, result); - return; - } - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - return; - } - result = body(); - if (_isSettledPact(result)) { - result = result.v; - } - } while (!result || !result.then); - result.then(_resumeAfterBody).then(void 0, reject); - } - function _resumeAfterTest(shouldContinue) { - if (shouldContinue) { - result = body(); - if (result && result.then) { - result.then(_resumeAfterBody).then(void 0, reject); - } else { - _resumeAfterBody(result); - } - } else { - _settle(pact, 1, result); - } - } - function _resumeAfterUpdate() { - if (shouldContinue = test()) { - if (shouldContinue.then) { - shouldContinue.then(_resumeAfterTest).then(void 0, reject); - } else { - _resumeAfterTest(shouldContinue); - } - } else { - _settle(pact, 1, result); - } - } -} +var _incrementalWrite = require("./incremental-write"); var basePrototype = { - /** - * TODO - * instead of appliying the _this-hack - * we should make these accessors functions instead of getters. - */ - get _data() { - var _this = this; - /** - * Might be undefined when vuejs-devtools are used - * @link https://github.com/pubkey/rxdb/issues/1126 - */ - if (!_this.isInstanceOfRxDocument) { - return undefined; - } - return _this._dataSync$.getValue(); - }, get primaryPath() { var _this = this; if (!_this.isInstanceOfRxDocument) { @@ -8395,7 +7244,7 @@ var basePrototype = { if (!_this.isInstanceOfRxDocument) { return undefined; } - return _this._dataSync$.pipe((0, _operators.map)(function (d) { + return _this.$.pipe((0, _operators.map)(function (d) { return d._deleted; })); }, @@ -8406,62 +7255,54 @@ var basePrototype = { } return _this._data._deleted; }, + getLatest: function getLatest() { + var latestDocData = this.collection._docCache.getLatestDocumentData(this.primary); + return this.collection._docCache.getCachedRxDocument(latestDocData); + }, /** * returns the observable which emits the plain-data of this document */ get $() { + var _this2 = this; var _this = this; - return _this._dataSync$.asObservable().pipe((0, _operators.map)(function (docData) { - return _overwritable.overwritable.deepFreezeWhenDevMode(docData); - })); - }, - _handleChangeEvent: function _handleChangeEvent(changeEvent) { - if (changeEvent.documentId !== this.primary) { - return; - } - - // ensure that new _rev is higher then current - var docData = (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); - var newRevNr = (0, _util.getHeightOfRevision)(docData._rev); - var currentRevNr = (0, _util.getHeightOfRevision)(this._data._rev); - if (currentRevNr > newRevNr) return; - switch (changeEvent.operation) { - case 'INSERT': - break; - case 'UPDATE': - this._dataSync$.next(changeEvent.documentData); - break; - case 'DELETE': - // remove from docCache to assure new upserted RxDocuments will be a new instance - this.collection._docCache["delete"](this.primary); - this._dataSync$.next(changeEvent.documentData); - break; - } + return _this.collection.$.pipe((0, _operators.filter)(function (changeEvent) { + return !changeEvent.isLocal; + }), (0, _operators.filter)(function (changeEvent) { + return changeEvent.documentId === _this2.primary; + }), (0, _operators.map)(function (changeEvent) { + return (0, _rxChangeEvent.getDocumentDataOfRxChangeEvent)(changeEvent); + }), (0, _operators.startWith)(_this.collection._docCache.getLatestDocumentData(this.primary)), (0, _operators.distinctUntilChanged)(function (prev, curr) { + return prev._rev === curr._rev; + }), (0, _operators.shareReplay)(_utils.RXJS_SHARE_REPLAY_DEFAULTS)); }, /** * returns observable of the value of the given path */ get$: function get$(path) { - if (path.includes('.item.')) { - throw (0, _rxError.newRxError)('DOC1', { - path: path - }); - } - if (path === this.primaryPath) throw (0, _rxError.newRxError)('DOC2'); + if (_overwritable.overwritable.isDevMode()) { + if (path.includes('.item.')) { + throw (0, _rxError.newRxError)('DOC1', { + path: path + }); + } + if (path === this.primaryPath) { + throw (0, _rxError.newRxError)('DOC2'); + } - // final fields cannot be modified and so also not observed - if (this.collection.schema.finalFields.includes(path)) { - throw (0, _rxError.newRxError)('DOC3', { - path: path - }); - } - var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); - if (!schemaObj) { - throw (0, _rxError.newRxError)('DOC4', { - path: path - }); + // final fields cannot be modified and so also not observed + if (this.collection.schema.finalFields.includes(path)) { + throw (0, _rxError.newRxError)('DOC3', { + path: path + }); + } + var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); + if (!schemaObj) { + throw (0, _rxError.newRxError)('DOC4', { + path: path + }); + } } - return this._dataSync$.pipe((0, _operators.map)(function (data) { + return this.$.pipe((0, _operators.map)(function (data) { return _objectPath["default"].get(data, path); }), (0, _operators.distinctUntilChanged)()); }, @@ -8472,7 +7313,7 @@ var basePrototype = { var schemaObj = (0, _rxSchemaHelper.getSchemaByObjectPath)(this.collection.schema.jsonSchema, path); var value = this.get(path); if (!value) { - return _util.PROMISE_RESOLVE_NULL; + return _utils.PROMISE_RESOLVE_NULL; } if (!schemaObj) { throw (0, _rxError.newRxError)('DOC5', { @@ -8494,7 +7335,7 @@ var basePrototype = { }); } if (schemaObj.type === 'array') { - return refCollection.findByIds(value).then(function (res) { + return refCollection.findByIds(value).exec().then(function (res) { var valuesIterator = res.values(); return Array.from(valuesIterator); }); @@ -8518,14 +7359,14 @@ var basePrototype = { * TODO find a way to deep-freeze together with defineGetterSetter * so we do not have to do a deep clone here. */ - valueObj = (0, _util.clone)(valueObj); + valueObj = (0, _utils.clone)(valueObj); defineGetterSetter(this.collection.schema, valueObj, objPath, this); return valueObj; }, toJSON: function toJSON() { var withMetaFields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!withMetaFields) { - var data = (0, _util.flatClone)(this._data); + var data = (0, _utils.flatClone)(this._data); delete data._rev; delete data._attachments; delete data._deleted; @@ -8537,7 +7378,7 @@ var basePrototype = { }, toMutableJSON: function toMutableJSON() { var withMetaFields = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - return (0, _util.clone)(this.toJSON(withMetaFields)); + return (0, _utils.clone)(this.toJSON(withMetaFields)); }, /** * updates document @@ -8545,99 +7386,81 @@ var basePrototype = { * @param updateObj mongodb-like syntax */ update: function update(_updateObj) { - throw (0, _util.pluginMissing)('update'); + throw (0, _utils.pluginMissing)('update'); + }, + incrementalUpdate: function incrementalUpdate(_updateObj) { + throw (0, _utils.pluginMissing)('update'); }, updateCRDT: function updateCRDT(_updateObj) { - throw (0, _util.pluginMissing)('crdt'); + throw (0, _utils.pluginMissing)('crdt'); }, putAttachment: function putAttachment() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, getAttachment: function getAttachment() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, allAttachments: function allAttachments() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, get allAttachments$() { - throw (0, _util.pluginMissing)('attachments'); + throw (0, _utils.pluginMissing)('attachments'); }, + modify: function () { + var _modify = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(mutationFunction, + // used by some plugins that wrap the method + _context) { + var oldData, newData; + return _regenerator["default"].wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + oldData = this._data; + _context2.next = 3; + return (0, _incrementalWrite.modifierFromPublicToInternal)(mutationFunction)(oldData); + case 3: + newData = _context2.sent; + return _context2.abrupt("return", this._saveData(newData, oldData)); + case 5: + case "end": + return _context2.stop(); + } + }, _callee, this); + })); + function modify(_x, _x2) { + return _modify.apply(this, arguments); + } + return modify; + }(), /** - * runs an atomic update over the document + * runs an incremental update over the document * @param function that takes the document-data and returns a new data-object */ - atomicUpdate: function atomicUpdate(mutationFunction, + incrementalModify: function incrementalModify(mutationFunction, // used by some plugins that wrap the method _context) { - var _this2 = this; - return new Promise(function (res, rej) { - _this2._atomicQueue = _this2._atomicQueue.then(function () { - try { - var _temp5 = function _temp5(_result3) { - if (_exit) return _result3; - res(_this2); - }; - var _exit = false; - var done = false; - // we need a hacky while loop to stay incide the chain-link of _atomicQueue - // while still having the option to run a retry on conflicts - var _temp4 = _for(function () { - return !_exit && !done; - }, void 0, function () { - function _temp3(_result) { - if (_exit) return _result; - var _temp = _catch(function () { - return Promise.resolve(_this2._saveData(newData, oldData)).then(function () { - done = true; - }); - }, function (err) { - var useError = err.parameters && err.parameters.error ? err.parameters.error : err; - /** - * conflicts cannot happen by just using RxDB in one process - * There are two ways they still can appear which is - * replication and multi-tab usage - * Because atomicUpdate has a mutation function, - * we can just re-run the mutation until there is no conflict - */ - var isConflict = (0, _rxError.isBulkWriteConflictError)(useError); - if (isConflict) {} else { - rej(useError); - _exit = true; - } - }); - if (_temp && _temp.then) return _temp.then(function () {}); - } - var oldData = _this2._dataSync$.getValue(); - // always await because mutationFunction might be async - var newData; - var _temp2 = _catch(function () { - return Promise.resolve(mutationFunction((0, _util.clone)(oldData), _this2)).then(function (_mutationFunction) { - newData = _mutationFunction; - if (_this2.collection) { - newData = _this2.collection.schema.fillObjectWithDefaults(newData); - } - }); - }, function (err) { - rej(err); - _exit = true; - }); - return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2); - }); - return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4)); - } catch (e) { - return Promise.reject(e); - } - }); + var _this3 = this; + return this.collection.incrementalWriteQueue.addWrite(this._data, (0, _incrementalWrite.modifierFromPublicToInternal)(mutationFunction)).then(function (result) { + return _this3.collection._docCache.getCachedRxDocument(result); }); }, + patch: function patch(_patch) { + var oldData = this._data; + var newData = (0, _utils.clone)(oldData); + Object.entries(_patch).forEach(function (_ref) { + var k = _ref[0], + v = _ref[1]; + newData[k] = v; + }); + return this._saveData(newData, oldData); + }, /** * patches the given properties */ - atomicPatch: function atomicPatch(patch) { - return this.atomicUpdate(function (docData) { - Object.entries(patch).forEach(function (_ref) { - var k = _ref[0], - v = _ref[1]; + incrementalPatch: function incrementalPatch(patch) { + return this.incrementalModify(function (docData) { + Object.entries(patch).forEach(function (_ref2) { + var k = _ref2[0], + v = _ref2[1]; docData[k] = v; }); return docData; @@ -8647,49 +7470,55 @@ var basePrototype = { * saves the new document-data * and handles the events */ - _saveData: function _saveData(newData, oldData) { - try { - var _this3 = this; - newData = (0, _util.flatClone)(newData); - - // deleted documents cannot be changed - if (_this3._data._deleted) { - throw (0, _rxError.newRxError)('DOC11', { - id: _this3.primary, - document: _this3 - }); - } - - /** - * Meta values must always be merged - * instead of overwritten. - * This ensures that different plugins do not overwrite - * each others meta properties. - */ - newData._meta = Object.assign({}, oldData._meta, newData._meta); - - // ensure modifications are ok - if (_overwritable.overwritable.isDevMode()) { - _this3.collection.schema.validateChange(oldData, newData); - } - return Promise.resolve(_this3.collection._runHooks('pre', 'save', newData, _this3)).then(function () { - return Promise.resolve(_this3.collection.storageInstance.bulkWrite([{ - previous: oldData, - document: newData - }], 'rx-document-save-data')).then(function (writeResult) { - var isError = writeResult.error[_this3.primary]; - (0, _rxStorageHelper.throwIfIsStorageWriteError)(_this3.collection, _this3.primary, newData, isError); - return _this3.collection._runHooks('post', 'save', newData, _this3); - }); - }); - } catch (e) { - return Promise.reject(e); + _saveData: function () { + var _saveData2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(newData, oldData) { + var writeResult, isError; + return _regenerator["default"].wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + newData = (0, _utils.flatClone)(newData); + + // deleted documents cannot be changed + if (!this._data._deleted) { + _context3.next = 3; + break; + } + throw (0, _rxError.newRxError)('DOC11', { + id: this.primary, + document: this + }); + case 3: + _context3.next = 5; + return beforeDocumentUpdateWrite(this.collection, newData, oldData); + case 5: + _context3.next = 7; + return this.collection.storageInstance.bulkWrite([{ + previous: oldData, + document: newData + }], 'rx-document-save-data'); + case 7: + writeResult = _context3.sent; + isError = writeResult.error[this.primary]; + (0, _rxStorageHelper.throwIfIsStorageWriteError)(this.collection, this.primary, newData, isError); + _context3.next = 12; + return this.collection._runHooks('post', 'save', newData, this); + case 12: + return _context3.abrupt("return", this.collection._docCache.getCachedRxDocument((0, _utils.getFromObjectOrThrow)(writeResult.success, this.primary))); + case 13: + case "end": + return _context3.stop(); + } + }, _callee2, this); + })); + function _saveData(_x3, _x4) { + return _saveData2.apply(this, arguments); } - }, + return _saveData; + }(), /** - * remove the document, - * this not not equal to a pouchdb.remove(), - * instead we keep the values and only set _deleted: true + * Remove the document. + * Notice that there is no hard delete, + * instead deleted documents get flagged with _deleted=true. */ remove: function remove() { var _this4 = this; @@ -8700,27 +7529,77 @@ var basePrototype = { id: this.primary })); } - var deletedData = (0, _util.flatClone)(this._data); - return collection._runHooks('pre', 'remove', deletedData, this).then(function () { - try { - deletedData._deleted = true; - return Promise.resolve(collection.storageInstance.bulkWrite([{ - previous: _this4._data, - document: deletedData - }], 'rx-document-remove')).then(function (writeResult) { - var isError = writeResult.error[_this4.primary]; - (0, _rxStorageHelper.throwIfIsStorageWriteError)(collection, _this4.primary, deletedData, isError); - return (0, _util.ensureNotFalsy)(writeResult.success[_this4.primary]); - }); - } catch (e) { - return Promise.reject(e); - } - }).then(function () { + var deletedData = (0, _utils.flatClone)(this._data); + var removedDocData; + return collection._runHooks('pre', 'remove', deletedData, this).then( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var writeResult, isError; + return _regenerator["default"].wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + deletedData._deleted = true; + _context4.next = 3; + return collection.storageInstance.bulkWrite([{ + previous: _this4._data, + document: deletedData + }], 'rx-document-remove'); + case 3: + writeResult = _context4.sent; + isError = writeResult.error[_this4.primary]; + (0, _rxStorageHelper.throwIfIsStorageWriteError)(collection, _this4.primary, deletedData, isError); + return _context4.abrupt("return", (0, _utils.getFromObjectOrThrow)(writeResult.success, _this4.primary)); + case 7: + case "end": + return _context4.stop(); + } + }, _callee3); + }))).then(function (removed) { + removedDocData = removed; return _this4.collection._runHooks('post', 'remove', deletedData, _this4); }).then(function () { - return _this4; + return _this4.collection._docCache.getCachedRxDocument(removedDocData); }); }, + incrementalRemove: function incrementalRemove() { + var _this5 = this; + return this.incrementalModify( /*#__PURE__*/function () { + var _ref4 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(docData) { + return _regenerator["default"].wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return _this5.collection._runHooks('pre', 'remove', docData, _this5); + case 2: + docData._deleted = true; + return _context5.abrupt("return", docData); + case 4: + case "end": + return _context5.stop(); + } + }, _callee4); + })); + return function (_x5) { + return _ref4.apply(this, arguments); + }; + }()).then( /*#__PURE__*/function () { + var _ref5 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(newDoc) { + return _regenerator["default"].wrap(function _callee5$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return _this5.collection._runHooks('post', 'remove', newDoc._data, newDoc); + case 2: + return _context6.abrupt("return", newDoc); + case 3: + case "end": + return _context6.stop(); + } + }, _callee5); + })); + return function (_x6) { + return _ref5.apply(this, arguments); + }; + }()); + }, destroy: function destroy() { throw (0, _rxError.newRxError)('DOC14'); } @@ -8728,12 +7607,11 @@ var basePrototype = { exports.basePrototype = basePrototype; function createRxDocumentConstructor() { var proto = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : basePrototype; - var constructor = function RxDocumentConstructor(collection, jsonData) { + var constructor = function RxDocumentConstructor(collection, docData) { this.collection = collection; // assume that this is always equal to the doc-data in the database - this._dataSync$ = new _rxjs.BehaviorSubject(jsonData); - this._atomicQueue = _util.PROMISE_RESOLVE_VOID; + this._data = docData; /** * because of the prototype-merge, @@ -8752,7 +7630,7 @@ function defineGetterSetter(schema, valueObj) { if (typeof pathProperties === 'undefined') return; if (pathProperties.properties) pathProperties = pathProperties.properties; Object.keys(pathProperties).forEach(function (key) { - var fullPath = (0, _util.trimDots)(objPath + '.' + key); + var fullPath = (0, _utils.trimDots)(objPath + '.' + key); // getter - value valueObj.__defineGetter__(key, function () { @@ -8794,10 +7672,6 @@ function defineGetterSetter(schema, valueObj) { }); } function createWithConstructor(constructor, collection, jsonData) { - var primary = jsonData[collection.schema.primaryPath]; - if (primary && primary.startsWith('_design')) { - return null; - } var doc = new constructor(collection, jsonData); (0, _hooks.runPluginHooks)('createRxDocument', doc); return doc; @@ -8806,8 +7680,23 @@ function isRxDocument(obj) { if (typeof obj === 'undefined') return false; return !!obj.isInstanceOfRxDocument; } +function beforeDocumentUpdateWrite(collection, newData, oldData) { + /** + * Meta values must always be merged + * instead of overwritten. + * This ensures that different plugins do not overwrite + * each others meta properties. + */ + newData._meta = Object.assign({}, oldData._meta, newData._meta); + + // ensure modifications are ok + if (_overwritable.overwritable.isDevMode()) { + collection.schema.validateChange(oldData, newData); + } + return collection._runHooks('pre', 'save', newData); +} -},{"./hooks":6,"./overwritable":8,"./rx-change-event":28,"./rx-error":35,"./rx-schema-helper":38,"./rx-storage-helper":40,"./util":44,"@babel/runtime/helpers/interopRequireDefault":51,"object-path":421,"rxjs":458,"rxjs/operators":683}],35:[function(require,module,exports){ +},{"./hooks":6,"./incremental-write":7,"./overwritable":9,"./plugins/utils":12,"./rx-change-event":34,"./rx-error":41,"./rx-schema-helper":44,"./rx-storage-helper":46,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"object-path":419,"rxjs/operators":648}],41:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -8818,6 +7707,7 @@ exports.RxTypeError = exports.RxError = void 0; exports.isBulkWriteConflictError = isBulkWriteConflictError; exports.newRxError = newRxError; exports.newRxTypeError = newRxTypeError; +exports.rxStorageWriteErrorToRxError = rxStorageWriteErrorToRxError; var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper")); @@ -8850,6 +7740,8 @@ function messageForError(message, code, parameters) { } var RxError = /*#__PURE__*/function (_Error) { (0, _inheritsLoose2["default"])(RxError, _Error); + // always true, use this to detect if its an rxdb-error + function RxError(code, message) { var _this; var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -8881,6 +7773,8 @@ var RxError = /*#__PURE__*/function (_Error) { exports.RxError = RxError; var RxTypeError = /*#__PURE__*/function (_TypeError) { (0, _inheritsLoose2["default"])(RxTypeError, _TypeError); + // always true, use this to detect if its an rxdb-error + function RxTypeError(code, message) { var _this2; var parameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; @@ -8922,14 +7816,26 @@ function newRxTypeError(code, parameters) { * return false if it is another error. */ function isBulkWriteConflictError(err) { - if (err.status === 409) { + if (err && err.status === 409) { return err; } else { return false; } } +var STORAGE_WRITE_ERROR_CODE_TO_MESSAGE = { + 409: 'document write conflict', + 422: 'schema validation error', + 510: 'attachment data missing' +}; +function rxStorageWriteErrorToRxError(err) { + return newRxError('COL20', { + name: STORAGE_WRITE_ERROR_CODE_TO_MESSAGE[err.status], + document: err.documentId, + writeError: err + }); +} -},{"./overwritable":8,"@babel/runtime/helpers/createClass":48,"@babel/runtime/helpers/inheritsLoose":50,"@babel/runtime/helpers/interopRequireDefault":51,"@babel/runtime/helpers/wrapNativeSuper":58}],36:[function(require,module,exports){ +},{"./overwritable":9,"@babel/runtime/helpers/createClass":54,"@babel/runtime/helpers/inheritsLoose":56,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/helpers/wrapNativeSuper":65}],42:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -8938,14 +7844,14 @@ Object.defineProperty(exports, "__esModule", { exports.normalizeMangoQuery = normalizeMangoQuery; var _queryPlanner = require("./query-planner"); var _rxSchemaHelper = require("./rx-schema-helper"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * Normalize the query to ensure we have all fields set * and queries that represent the same query logic are detected as equal by the caching. */ function normalizeMangoQuery(schema, mangoQuery) { var primaryKey = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(schema.primaryKey); - var normalizedMangoQuery = (0, _util.clone)(mangoQuery); + var normalizedMangoQuery = (0, _utils.clone)(mangoQuery); if (typeof normalizedMangoQuery.skip !== 'number') { normalizedMangoQuery.skip = 0; } @@ -8984,7 +7890,7 @@ function normalizeMangoQuery(schema, mangoQuery) { * the primaryKey is inside of it. */ if (normalizedMangoQuery.index) { - var indexAr = Array.isArray(normalizedMangoQuery.index) ? normalizedMangoQuery.index.slice(0) : [normalizedMangoQuery.index]; + var indexAr = (0, _utils.toArray)(normalizedMangoQuery.index); if (!indexAr.includes(primaryKey)) { indexAr.push(primaryKey); } @@ -9037,7 +7943,7 @@ function normalizeMangoQuery(schema, mangoQuery) { var currentFieldsAmount = -1; var currentBestIndexForSort; schema.indexes.forEach(function (index) { - var useIndex = (0, _util.isMaybeReadonlyArray)(index) ? index : [index]; + var useIndex = (0, _utils.isMaybeReadonlyArray)(index) ? index : [index]; var firstWrongIndex = useIndex.findIndex(function (indexField) { return !fieldsWithLogicalOperator.has(indexField); }); @@ -9065,7 +7971,7 @@ function normalizeMangoQuery(schema, mangoQuery) { } } else { var isPrimaryInSort = normalizedMangoQuery.sort.find(function (p) { - return (0, _util.firstPropertyNameOfObject)(p) === primaryKey; + return (0, _utils.firstPropertyNameOfObject)(p) === primaryKey; }); if (!isPrimaryInSort) { var _normalizedMangoQuery; @@ -9076,7 +7982,7 @@ function normalizeMangoQuery(schema, mangoQuery) { return normalizedMangoQuery; } -},{"./query-planner":20,"./rx-schema-helper":38,"./util":44}],37:[function(require,module,exports){ +},{"./plugins/utils":12,"./query-planner":26,"./rx-schema-helper":44}],43:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -9088,67 +7994,19 @@ exports._getDefaultQuery = _getDefaultQuery; exports.createRxQuery = createRxQuery; exports.isFindOneByIdQuery = isFindOneByIdQuery; exports.isInstanceOf = isInstanceOf; -exports.queryCollection = void 0; +exports.queryCollection = queryCollection; exports.tunnelQueryCache = tunnelQueryCache; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _hooks = require("./hooks"); -var _rxDocumentPrototypeMerge = require("./rx-document-prototype-merge"); var _eventReduce = require("./event-reduce"); var _queryCache = require("./query-cache"); var _rxQueryHelper = require("./rx-query-helper"); -/** - * Runs the query over the storage instance - * of the collection. - * Does some optimizations to ensuer findById is used - * when specific queries are used. - */ -var queryCollection = function queryCollection(rxQuery) { - try { - var docs = []; - var _collection = rxQuery.collection; - - /** - * Optimizations shortcut. - * If query is find-one-document-by-id, - * then we do not have to use the slow query() method - * but instead can use findDocumentsById() - */ - var _temp = function () { - if (rxQuery.isFindOneByIdQuery) { - var docId = rxQuery.isFindOneByIdQuery; - return Promise.resolve(_collection.storageInstance.findDocumentsById([docId], false)).then(function (docsMap) { - var docData = docsMap[docId]; - if (docData) { - docs.push(docData); - } - }); - } else { - var preparedQuery = rxQuery.getPreparedQuery(); - return Promise.resolve(_collection.storageInstance.query(preparedQuery)).then(function (queryResult) { - docs = queryResult.documents; - }); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return docs; - }) : docs); - } catch (e) { - return Promise.reject(e); - } -}; -/** - * Returns true if the given query - * selects exactly one document by its id. - * Used to optimize performance because these kind of - * queries do not have to run over an index and can use get-by-id instead. - * Returns false if no query of that kind. - * Returns the document id otherwise. - */ -exports.queryCollection = queryCollection; var _queryCount = 0; var newQueryID = function newQueryID() { return ++_queryCount; @@ -9172,7 +8030,7 @@ var RxQueryBase = /*#__PURE__*/function () { function RxQueryBase(op, mangoQuery, collection) { this.id = newQueryID(); this._execOverDatabaseCount = 0; - this._creationTime = (0, _util.now)(); + this._creationTime = (0, _utils.now)(); this._lastEnsureEqual = 0; this.other = {}; this.uncached = false; @@ -9181,7 +8039,7 @@ var RxQueryBase = /*#__PURE__*/function () { this._latestChangeEvent = -1; this._lastExecStart = 0; this._lastExecEnd = 0; - this._ensureEqualQueue = _util.PROMISE_RESOLVE_FALSE; + this._ensureEqualQueue = _utils.PROMISE_RESOLVE_FALSE; this.op = op; this.mangoQuery = mangoQuery; this.collection = collection; @@ -9193,40 +8051,46 @@ var RxQueryBase = /*#__PURE__*/function () { var _proto = RxQueryBase.prototype; /** * set the new result-data as result-docs of the query - * @param newResultData json-docs that were received from pouchdb + * @param newResultData json-docs that were received from the storage */ _proto._setResultData = function _setResultData(newResultData) { + var _this = this; if (typeof newResultData === 'number') { this._result = { docsData: [], + docsMap: new Map(), docsDataMap: new Map(), count: newResultData, docs: [], - time: (0, _util.now)() + time: (0, _utils.now)() }; return; + } else if (newResultData instanceof Map) { + newResultData = Array.from(newResultData.values()); } - var docs = (0, _rxDocumentPrototypeMerge.createRxDocuments)(this.collection, newResultData); + var docsDataMap = new Map(); + var docsMap = new Map(); + var docs = newResultData.map(function (docData) { + return _this.collection._docCache.getCachedRxDocument(docData); + }); /** * Instead of using the newResultData in the result cache, * we directly use the objects that are stored in the RxDocument * to ensure we do not store the same data twice and fill up the memory. */ - var primPath = this.collection.schema.primaryPath; - var docsDataMap = new Map(); var docsData = docs.map(function (doc) { - var docData = doc._dataSync$.getValue(); - var id = docData[primPath]; - docsDataMap.set(id, docData); - return docData; + docsDataMap.set(doc.primary, doc._data); + docsMap.set(doc.primary, doc); + return doc._data; }); this._result = { docsData: docsData, + docsMap: docsMap, docsDataMap: docsDataMap, count: docsData.length, docs: docs, - time: (0, _util.now)() + time: (0, _utils.now)() }; } @@ -9234,37 +8098,95 @@ var RxQueryBase = /*#__PURE__*/function () { * executes the query on the database * @return results-array with document-data */; - _proto._execOverDatabase = function _execOverDatabase() { - var _this = this; - this._execOverDatabaseCount = this._execOverDatabaseCount + 1; - this._lastExecStart = (0, _util.now)(); - if (this.op === 'count') { - var preparedQuery = this.getPreparedQuery(); - return this.collection.storageInstance.count(preparedQuery).then(function (result) { - if (result.mode === 'slow' && !_this.collection.database.allowSlowCount) { - throw (0, _rxError.newRxError)('QU14', { - collection: _this.collection, - queryObj: _this.mangoQuery - }); - } else { - return result.count; + _proto._execOverDatabase = + /*#__PURE__*/ + function () { + var _execOverDatabase2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _this2 = this; + var preparedQuery, result, ids, ret, mustBeQueried, docs, docsPromise; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + this._execOverDatabaseCount = this._execOverDatabaseCount + 1; + this._lastExecStart = (0, _utils.now)(); + if (!(this.op === 'count')) { + _context.next = 12; + break; + } + preparedQuery = this.getPreparedQuery(); + _context.next = 6; + return this.collection.storageInstance.count(preparedQuery); + case 6: + result = _context.sent; + if (!(result.mode === 'slow' && !this.collection.database.allowSlowCount)) { + _context.next = 11; + break; + } + throw (0, _rxError.newRxError)('QU14', { + collection: this.collection, + queryObj: this.mangoQuery + }); + case 11: + return _context.abrupt("return", result.count); + case 12: + if (!(this.op === 'findByIds')) { + _context.next = 23; + break; + } + ids = (0, _utils.ensureNotFalsy)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in; + ret = new Map(); + mustBeQueried = []; // first try to fill from docCache + ids.forEach(function (id) { + var docData = _this2.collection._docCache.getLatestDocumentDataIfExists(id); + if (docData) { + if (!docData._deleted) { + var doc = _this2.collection._docCache.getCachedRxDocument(docData); + ret.set(id, doc); + } + } else { + mustBeQueried.push(id); + } + }); + // everything which was not in docCache must be fetched from the storage + if (!(mustBeQueried.length > 0)) { + _context.next = 22; + break; + } + _context.next = 20; + return this.collection.storageInstance.findDocumentsById(mustBeQueried, false); + case 20: + docs = _context.sent; + Object.values(docs).forEach(function (docData) { + var doc = _this2.collection._docCache.getCachedRxDocument(docData); + ret.set(doc.primary, doc); + }); + case 22: + return _context.abrupt("return", ret); + case 23: + docsPromise = queryCollection(this); + return _context.abrupt("return", docsPromise.then(function (docs) { + _this2._lastExecEnd = (0, _utils.now)(); + return docs; + })); + case 25: + case "end": + return _context.stop(); } - }); + }, _callee, this); + })); + function _execOverDatabase() { + return _execOverDatabase2.apply(this, arguments); } - var docsPromise = queryCollection(this); - return docsPromise.then(function (docs) { - _this._lastExecEnd = (0, _util.now)(); - return docs; - }); - } - + return _execOverDatabase; + }() /** * Execute the query * To have an easier implementations, * just subscribe and use the first result - */; + */ + ; _proto.exec = function exec(throwIfMissing) { - var _this2 = this; + var _this3 = this; if (throwIfMissing && this.op !== 'findOne') { throw (0, _rxError.newRxError)('QU9', { collection: this.collection.name, @@ -9279,13 +8201,13 @@ var RxQueryBase = /*#__PURE__*/function () { * will be thrown at this execution context and not in the background. */ return _ensureEqual(this).then(function () { - return (0, _rxjs.firstValueFrom)(_this2.$); + return (0, _rxjs.firstValueFrom)(_this3.$); }).then(function (result) { if (!result && throwIfMissing) { throw (0, _rxError.newRxError)('QU10', { - collection: _this2.collection.name, - query: _this2.mangoQuery, - op: _this2.op + collection: _this3.collection.name, + query: _this3.mangoQuery, + op: _this3.op }); } else { return result; @@ -9302,12 +8224,12 @@ var RxQueryBase = /*#__PURE__*/function () { * @overwrites itself with the actual value */ _proto.toString = function toString() { - var stringObj = (0, _util.sortObject)({ + var stringObj = (0, _utils.sortObject)({ op: this.op, query: this.mangoQuery, other: this.other }, true); - var value = JSON.stringify(stringObj, _util.stringifyFilter); + var value = JSON.stringify(stringObj, _utils.stringifyFilter); this.toString = function () { return value; }; @@ -9323,7 +8245,7 @@ var RxQueryBase = /*#__PURE__*/function () { var hookInput = { rxQuery: this, // can be mutated by the hooks so we have to deep clone first. - mangoQuery: (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _util.clone)(this.mangoQuery)) + mangoQuery: (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _utils.clone)(this.mangoQuery)) }; (0, _hooks.runPluginHooks)('prePrepareQuery', hookInput); var value = this.collection.database.storage.statics.prepareQuery(this.collection.schema.jsonSchema, hookInput.mangoQuery); @@ -9350,9 +8272,7 @@ var RxQueryBase = /*#__PURE__*/function () { * @return promise with deleted documents */; _proto.remove = function remove() { - var ret; return this.exec().then(function (docs) { - ret = docs; if (Array.isArray(docs)) { // TODO use a bulk operation instead of running .remove() on each document return Promise.all(docs.map(function (doc) { @@ -9361,8 +8281,6 @@ var RxQueryBase = /*#__PURE__*/function () { } else { return docs.remove(); } - }).then(function () { - return ret; }); } @@ -9374,28 +8292,28 @@ var RxQueryBase = /*#__PURE__*/function () { * @overwritten by plugin (optional) */ _proto.update = function update(_updateObj) { - throw (0, _util.pluginMissing)('update'); + throw (0, _utils.pluginMissing)('update'); } // we only set some methods of query-builder here // because the others depend on these ones ; _proto.where = function where(_queryObj) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; _proto.sort = function sort(_params) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; _proto.skip = function skip(_amount) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; _proto.limit = function limit(_amount) { - throw (0, _util.pluginMissing)('query-builder'); + throw (0, _utils.pluginMissing)('query-builder'); }; (0, _createClass2["default"])(RxQueryBase, [{ key: "$", get: function get() { - var _this3 = this; + var _this4 = this; if (!this._$) { var results$ = this.collection.$.pipe( /** @@ -9412,17 +8330,17 @@ var RxQueryBase = /*#__PURE__*/function () { (0, _operators.startWith)(null), // ensure query results are up to date. (0, _operators.mergeMap)(function () { - return _ensureEqual(_this3); + return _ensureEqual(_this4); }), // use the current result set, written by _ensureEqual(). (0, _operators.map)(function () { - return _this3._result; + return _this4._result; }), // do not run stuff above for each new subscriber, only once. - (0, _operators.shareReplay)(_util.RXJS_SHARE_REPLAY_DEFAULTS), + (0, _operators.shareReplay)(_utils.RXJS_SHARE_REPLAY_DEFAULTS), // do not proceed if result set has not changed. (0, _operators.distinctUntilChanged)(function (prev, curr) { - if (prev && prev.time === (0, _util.ensureNotFalsy)(curr).time) { + if (prev && prev.time === (0, _utils.ensureNotFalsy)(curr).time) { return true; } else { return false; @@ -9435,12 +8353,14 @@ var RxQueryBase = /*#__PURE__*/function () { * depending on query type */ (0, _operators.map)(function (result) { - var useResult = (0, _util.ensureNotFalsy)(result); - if (_this3.op === 'count') { + var useResult = (0, _utils.ensureNotFalsy)(result); + if (_this4.op === 'count') { return useResult.count; - } else if (_this3.op === 'findOne') { + } else if (_this4.op === 'findOne') { // findOne()-queries emit RxDocument or null return useResult.docs.length === 0 ? null : useResult.docs[0]; + } else if (_this4.op === 'findByIds') { + return useResult.docsMap; } else { // find()-queries emit RxDocument[] // Flat copy the array so it won't matter if the user modifies it. @@ -9471,8 +8391,8 @@ var RxQueryBase = /*#__PURE__*/function () { * so that it does not contain modifications from the hooks * like the key compression. */ - var usePreparedQuery = this.collection.database.storage.statics.prepareQuery(schema, (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _util.clone)(this.mangoQuery))); - return (0, _util.overwriteGetterForCaching)(this, 'queryMatcher', this.collection.database.storage.statics.getQueryMatcher(schema, usePreparedQuery)); + var usePreparedQuery = this.collection.database.storage.statics.prepareQuery(schema, (0, _rxQueryHelper.normalizeMangoQuery)(this.collection.schema.jsonSchema, (0, _utils.clone)(this.mangoQuery))); + return (0, _utils.overwriteGetterForCaching)(this, 'queryMatcher', this.collection.database.storage.statics.getQueryMatcher(schema, usePreparedQuery)); } }, { key: "asRxQuery", @@ -9531,7 +8451,7 @@ function _isResultsInSync(rxQuery) { function _ensureEqual(rxQuery) { // Optimisation shortcut if (rxQuery.collection.database.destroyed || _isResultsInSync(rxQuery)) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } rxQuery._ensureEqualQueue = rxQuery._ensureEqualQueue.then(function () { return __ensureEqual(rxQuery); @@ -9544,7 +8464,7 @@ function _ensureEqual(rxQuery) { * @return true if results have changed */ function __ensureEqual(rxQuery) { - rxQuery._lastEnsureEqual = (0, _util.now)(); + rxQuery._lastEnsureEqual = (0, _utils.now)(); /** * Optimisation shortcuts @@ -9554,7 +8474,7 @@ function __ensureEqual(rxQuery) { rxQuery.collection.database.destroyed || // nothing happened since last run _isResultsInSync(rxQuery)) { - return _util.PROMISE_RESOLVE_FALSE; + return _utils.PROMISE_RESOLVE_FALSE; } var ret = false; var mustReExec = false; // if this becomes true, a whole execution over the database is made @@ -9576,7 +8496,7 @@ function __ensureEqual(rxQuery) { var runChangeEvents = rxQuery.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(missedChangeEvents); if (rxQuery.op === 'count') { // 'count' query - var previousCount = (0, _util.ensureNotFalsy)(rxQuery._result).count; + var previousCount = (0, _utils.ensureNotFalsy)(rxQuery._result).count; var newCount = previousCount; runChangeEvents.forEach(function (cE) { var didMatchBefore = cE.previousDocumentData && rxQuery.doesDocumentDataMatch(cE.previousDocumentData); @@ -9622,7 +8542,7 @@ function __ensureEqual(rxQuery) { } return ret; } - if (!rxQuery._result || !(0, _util.areRxDocumentArraysEqual)(rxQuery.collection.schema.primaryPath, newResultData, rxQuery._result.docsData)) { + if (!rxQuery._result || !(0, _utils.areRxDocumentArraysEqual)(rxQuery.collection.schema.primaryPath, newResultData, rxQuery._result.docsData)) { ret = true; // true because results changed rxQuery._setResultData(newResultData); } @@ -9632,12 +8552,82 @@ function __ensureEqual(rxQuery) { return Promise.resolve(ret); // true if results have changed } +/** + * Runs the query over the storage instance + * of the collection. + * Does some optimizations to ensuer findById is used + * when specific queries are used. + */ +function queryCollection(_x) { + return _queryCollection.apply(this, arguments); +} +/** + * Returns true if the given query + * selects exactly one document by its id. + * Used to optimize performance because these kind of + * queries do not have to run over an index and can use get-by-id instead. + * Returns false if no query of that kind. + * Returns the document id otherwise. + */ +function _queryCollection() { + _queryCollection = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(rxQuery) { + var docs, collection, docId, docData, docsMap, preparedQuery, queryResult; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + docs = []; + collection = rxQuery.collection; + /** + * Optimizations shortcut. + * If query is find-one-document-by-id, + * then we do not have to use the slow query() method + * but instead can use findDocumentsById() + */ + if (!rxQuery.isFindOneByIdQuery) { + _context2.next = 13; + break; + } + docId = rxQuery.isFindOneByIdQuery; // first try to fill from docCache + docData = rxQuery.collection._docCache.getLatestDocumentDataIfExists(docId); + if (docData) { + _context2.next = 10; + break; + } + _context2.next = 8; + return collection.storageInstance.findDocumentsById([docId], false); + case 8: + docsMap = _context2.sent; + docData = docsMap[docId]; + case 10: + if (docData) { + docs.push(docData); + } + _context2.next = 18; + break; + case 13: + preparedQuery = rxQuery.getPreparedQuery(); + _context2.next = 16; + return collection.storageInstance.query(preparedQuery); + case 16: + queryResult = _context2.sent; + docs = queryResult.documents; + case 18: + return _context2.abrupt("return", docs); + case 19: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _queryCollection.apply(this, arguments); +} function isFindOneByIdQuery(primaryPath, query) { if (!query.skip && query.selector && Object.keys(query.selector).length === 1 && query.selector[primaryPath]) { - if (typeof query.selector[primaryPath] === 'string') { - return query.selector[primaryPath]; - } else if (Object.keys(query.selector[primaryPath]).length === 1 && typeof query.selector[primaryPath].$eq === 'string') { - return query.selector[primaryPath].$eq; + var value = query.selector[primaryPath]; + if (typeof value === 'string') { + return value; + } else if (Object.keys(value).length === 1 && typeof value.$eq === 'string') { + return value.$eq; } } return false; @@ -9646,7 +8636,7 @@ function isInstanceOf(obj) { return obj instanceof RxQueryBase; } -},{"./event-reduce":5,"./hooks":6,"./query-cache":19,"./rx-document-prototype-merge":33,"./rx-error":35,"./rx-query-helper":36,"./util":44,"@babel/runtime/helpers/createClass":48,"@babel/runtime/helpers/interopRequireDefault":51,"rxjs":458,"rxjs/operators":683}],38:[function(require,module,exports){ +},{"./event-reduce":5,"./hooks":6,"./plugins/utils":12,"./query-cache":25,"./rx-error":41,"./rx-query-helper":42,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/createClass":54,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"rxjs":423,"rxjs/operators":648}],44:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -9664,7 +8654,7 @@ exports.getSchemaByObjectPath = getSchemaByObjectPath; exports.normalizeRxJsonSchema = normalizeRxJsonSchema; var _objectPath = _interopRequireDefault(require("object-path")); var _rxError = require("./rx-error"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * Helper function to create a valid RxJsonSchema * with a given version. @@ -9691,12 +8681,12 @@ function getSchemaByObjectPath(rxJsonSchema, path) { var usePath = path; usePath = usePath.replace(/\./g, '.properties.'); usePath = 'properties.' + usePath; - usePath = (0, _util.trimDots)(usePath); + usePath = (0, _utils.trimDots)(usePath); var ret = _objectPath["default"].get(rxJsonSchema, usePath); return ret; } function fillPrimaryKey(primaryPath, jsonSchema, documentData) { - var cloned = (0, _util.flatClone)(documentData); + var cloned = (0, _utils.flatClone)(documentData); var newPrimary = getComposedPrimaryKeyOfDocumentData(jsonSchema, documentData); var existingPrimary = documentData[primaryPath]; if (existingPrimary && existingPrimary !== newPrimary) { @@ -9755,18 +8745,7 @@ function getComposedPrimaryKeyOfDocumentData(jsonSchema, documentData) { * @return RxJsonSchema - ordered and filled */ function normalizeRxJsonSchema(jsonSchema) { - // TODO do we need the deep clone() here? - var normalizedSchema = (0, _util.sortObject)((0, _util.clone)(jsonSchema)); - - // indexes must NOT be sorted because sort order is important here. - if (jsonSchema.indexes) { - normalizedSchema.indexes = Array.from(jsonSchema.indexes); - } - - // primaryKey.fields must NOT be sorted because sort order is important here. - if (typeof normalizedSchema.primaryKey === 'object' && typeof jsonSchema.primaryKey === 'object') { - normalizedSchema.primaryKey.fields = jsonSchema.primaryKey.fields; - } + var normalizedSchema = (0, _utils.sortObject)(jsonSchema, true); return normalizedSchema; } @@ -9775,9 +8754,9 @@ function normalizeRxJsonSchema(jsonSchema) { * @return cloned schemaObj */ function fillWithDefaultSettings(schemaObj) { - schemaObj = (0, _util.flatClone)(schemaObj); + schemaObj = (0, _utils.flatClone)(schemaObj); var primaryPath = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey); - schemaObj.properties = (0, _util.flatClone)(schemaObj.properties); + schemaObj.properties = (0, _utils.flatClone)(schemaObj.properties); // additionalProperties is always false schemaObj.additionalProperties = false; @@ -9845,7 +8824,7 @@ function fillWithDefaultSettings(schemaObj) { */ if (schemaObj.indexes) { schemaObj.indexes = schemaObj.indexes.map(function (index) { - var arIndex = (0, _util.isMaybeReadonlyArray)(index) ? index.slice(0) : [index]; + var arIndex = (0, _utils.isMaybeReadonlyArray)(index) ? index.slice(0) : [index]; if (!arIndex.includes(primaryPath)) { var modifiedIndex = arIndex.slice(0); modifiedIndex.push(primaryPath); @@ -9868,7 +8847,7 @@ var RX_META_SCHEMA = { /** * We use 1 as minimum so that the value is never falsy. */ - minimum: _util.RX_META_LWT_MINIMUM, + minimum: _utils.RX_META_LWT_MINIMUM, maximum: 1000000000000000, multipleOf: 0.01 } @@ -9918,7 +8897,7 @@ var DEFAULT_CHECKPOINT_SCHEMA = { }; exports.DEFAULT_CHECKPOINT_SCHEMA = DEFAULT_CHECKPOINT_SCHEMA; -},{"./rx-error":35,"./util":44,"@babel/runtime/helpers/interopRequireDefault":51,"object-path":421}],39:[function(require,module,exports){ +},{"./plugins/utils":12,"./rx-error":41,"@babel/runtime/helpers/interopRequireDefault":57,"object-path":419}],45:[function(require,module,exports){ "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); @@ -9933,7 +8912,7 @@ exports.isInstanceOf = isInstanceOf; exports.toTypedRxJsonSchema = toTypedRxJsonSchema; var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal")); -var _util = require("./util"); +var _utils = require("./plugins/utils"); var _rxError = require("./rx-error"); var _hooks = require("./hooks"); var _rxDocument = require("./rx-document"); @@ -9973,7 +8952,7 @@ var RxSchema = /*#__PURE__*/function () { * fills all unset fields with default-values if set */; _proto.fillObjectWithDefaults = function fillObjectWithDefaults(obj) { - obj = (0, _util.flatClone)(obj); + obj = (0, _utils.flatClone)(obj); Object.entries(this.defaultValues).filter(function (_ref) { var k = _ref[0]; return !obj.hasOwnProperty(k) || typeof obj[k] === 'undefined'; @@ -9992,7 +8971,7 @@ var RxSchema = /*#__PURE__*/function () { _proto.getDocumentPrototype = function getDocumentPrototype() { var proto = {}; (0, _rxDocument.defineGetterSetter)(this, proto, ''); - (0, _util.overwriteGetterForCaching)(this, 'getDocumentPrototype', function () { + (0, _utils.overwriteGetterForCaching)(this, 'getDocumentPrototype', function () { return proto; }); return proto; @@ -10017,7 +8996,7 @@ var RxSchema = /*#__PURE__*/function () { v = _ref4[1]; return values[k] = v["default"]; }); - return (0, _util.overwriteGetterForCaching)(this, 'defaultValues', values); + return (0, _utils.overwriteGetterForCaching)(this, 'defaultValues', values); } /** @@ -10026,7 +9005,7 @@ var RxSchema = /*#__PURE__*/function () { }, { key: "hash", get: function get() { - return (0, _util.overwriteGetterForCaching)(this, 'hash', (0, _util.fastUnsecureHash)(JSON.stringify(this.jsonSchema))); + return (0, _utils.overwriteGetterForCaching)(this, 'hash', (0, _utils.fastUnsecureHash)(JSON.stringify(this.jsonSchema))); } }]); return RxSchema; @@ -10034,7 +9013,7 @@ var RxSchema = /*#__PURE__*/function () { exports.RxSchema = RxSchema; function getIndexes(jsonSchema) { return (jsonSchema.indexes || []).map(function (index) { - return (0, _util.isMaybeReadonlyArray)(index) ? index : [index]; + return (0, _utils.isMaybeReadonlyArray)(index) ? index : [index]; }); } @@ -10072,9 +9051,10 @@ function toTypedRxJsonSchema(schema) { return schema; } -},{"./hooks":6,"./overwritable":8,"./rx-document":34,"./rx-error":35,"./rx-schema-helper":38,"./util":44,"@babel/runtime/helpers/createClass":48,"@babel/runtime/helpers/interopRequireDefault":51,"fast-deep-equal":411}],40:[function(require,module,exports){ +},{"./hooks":6,"./overwritable":9,"./plugins/utils":12,"./rx-document":40,"./rx-error":41,"./rx-schema-helper":44,"@babel/runtime/helpers/createClass":54,"@babel/runtime/helpers/interopRequireDefault":57,"fast-deep-equal":416}],46:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -10085,7 +9065,7 @@ exports.ensureRxStorageInstanceParamsAreCorrect = ensureRxStorageInstanceParamsA exports.flatCloneDocWithMeta = flatCloneDocWithMeta; exports.getAttachmentSize = getAttachmentSize; exports.getNewestOfDocumentStates = getNewestOfDocumentStates; -exports.getSingleDocument = void 0; +exports.getSingleDocument = getSingleDocument; exports.getUniqueDeterministicEventKey = getUniqueDeterministicEventKey; exports.getWrappedStorageInstance = getWrappedStorageInstance; exports.hasEncryption = hasEncryption; @@ -10094,59 +9074,90 @@ exports.storageChangeEventToRxChangeEvent = storageChangeEventToRxChangeEvent; exports.stripAttachmentsDataFromDocument = stripAttachmentsDataFromDocument; exports.stripAttachmentsDataFromRow = stripAttachmentsDataFromRow; exports.throwIfIsStorageWriteError = throwIfIsStorageWriteError; -exports.writeSingle = void 0; +exports.writeSingle = writeSingle; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _overwritable = require("./overwritable"); var _rxError = require("./rx-error"); var _rxSchemaHelper = require("./rx-schema-helper"); -var _util = require("./util"); +var _utils = require("./plugins/utils"); /** * Helper functions for accessing the RxStorage instances. */ + +var INTERNAL_STORAGE_NAME = '_rxdb_internal'; +exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; +var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; +exports.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = RX_DATABASE_LOCAL_DOCS_STORAGE_NAME; +function getSingleDocument(_x, _x2) { + return _getSingleDocument.apply(this, arguments); +} /** * Writes a single document, * throws RxStorageBulkWriteError on failure */ -var writeSingle = function writeSingle(instance, writeRow, context) { - try { - return Promise.resolve(instance.bulkWrite([writeRow], context)).then(function (writeResult) { - if (Object.keys(writeResult.error).length > 0) { - var error = (0, _util.firstPropertyValueOfObject)(writeResult.error); - throw error; - } else { - var ret = (0, _util.firstPropertyValueOfObject)(writeResult.success); - return ret; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; +function _getSingleDocument() { + _getSingleDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(storageInstance, documentId) { + var results, doc; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return storageInstance.findDocumentsById([documentId], false); + case 2: + results = _context.sent; + doc = results[documentId]; + if (!doc) { + _context.next = 8; + break; + } + return _context.abrupt("return", doc); + case 8: + return _context.abrupt("return", null); + case 9: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _getSingleDocument.apply(this, arguments); +} +function writeSingle(_x3, _x4, _x5) { + return _writeSingle.apply(this, arguments); +} /** * Checkpoints must be stackable over another. * This is required form some RxStorage implementations * like the sharding plugin, where a checkpoint only represents * the document state from some, but not all shards. */ -exports.writeSingle = writeSingle; -var getSingleDocument = function getSingleDocument(storageInstance, documentId) { - try { - return Promise.resolve(storageInstance.findDocumentsById([documentId], false)).then(function (results) { - var doc = results[documentId]; - if (doc) { - return doc; - } else { - return null; - } - }); - } catch (e) { - return Promise.reject(e); - } -}; -exports.getSingleDocument = getSingleDocument; -var INTERNAL_STORAGE_NAME = '_rxdb_internal'; -exports.INTERNAL_STORAGE_NAME = INTERNAL_STORAGE_NAME; -var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; -exports.RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = RX_DATABASE_LOCAL_DOCS_STORAGE_NAME; +function _writeSingle() { + _writeSingle = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(instance, writeRow, context) { + var writeResult, error, ret; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return instance.bulkWrite([writeRow], context); + case 2: + writeResult = _context2.sent; + if (!(Object.keys(writeResult.error).length > 0)) { + _context2.next = 8; + break; + } + error = (0, _utils.firstPropertyValueOfObject)(writeResult.error); + throw error; + case 8: + ret = (0, _utils.firstPropertyValueOfObject)(writeResult.success); + return _context2.abrupt("return", ret); + case 10: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _writeSingle.apply(this, arguments); +} function stackCheckpoints(checkpoints) { return Object.assign.apply(Object, [{}].concat(checkpoints)); } @@ -10169,10 +9180,17 @@ function storageChangeEventToRxChangeEvent(isLocal, rxStorageChangeEvent, rxColl function throwIfIsStorageWriteError(collection, documentId, writeData, error) { if (error) { if (error.status === 409) { - throw (0, _rxError.newRxError)('COL19', { + throw (0, _rxError.newRxError)('CONFLICT', { collection: collection.name, id: documentId, - error: error, + writeError: error, + data: writeData + }); + } else if (error.status === 422) { + throw (0, _rxError.newRxError)('VD2', { + collection: collection.name, + id: documentId, + writeError: error, data: writeData }); } else { @@ -10194,7 +9212,7 @@ function getNewestOfDocumentStates(primaryPath, docs) { ret = doc; } }); - return (0, _util.ensureNotFalsy)(ret); + return (0, _utils.ensureNotFalsy)(ret); } /** @@ -10227,7 +9245,7 @@ bulkWriteRows, context) { var errors = {}; var changedDocumentIds = []; var eventBulk = { - id: (0, _util.randomCouchString)(10), + id: (0, _utils.randomCouchString)(10), events: [], checkpoint: null, context: context @@ -10235,7 +9253,7 @@ bulkWriteRows, context) { var attachmentsAdd = []; var attachmentsRemove = []; var attachmentsUpdate = []; - var startTime = (0, _util.now)(); + var startTime = (0, _utils.now)(); var docsByIdIsMap = typeof docsInDb.get === 'function'; bulkWriteRows.forEach(function (writeRow) { var id = writeRow.document[primaryPath]; @@ -10255,7 +9273,8 @@ bulkWriteRows, context) { documentId: id, isError: true, status: 510, - writeRow: writeRow + writeRow: writeRow, + attachmentId: attachmentId }; errors[id] = attachmentError; } else { @@ -10282,7 +9301,7 @@ bulkWriteRows, context) { documentData: hasAttachments ? stripAttachmentsDataFromDocument(writeRow.document) : writeRow.document, previousDocumentData: hasAttachments && writeRow.previous ? stripAttachmentsDataFromDocument(writeRow.previous) : writeRow.previous, startTime: startTime, - endTime: (0, _util.now)() + endTime: (0, _utils.now)() }); } } else { @@ -10332,7 +9351,8 @@ bulkWriteRows, context) { documentInDb: documentInDb, isError: true, status: 510, - writeRow: writeRow + writeRow: writeRow, + attachmentId: attachmentId }; } return true; @@ -10384,7 +9404,7 @@ bulkWriteRows, context) { previousEventDocumentData = writeRow.previous; } else if (writeDoc._deleted) { operation = 'DELETE'; - eventDocumentData = (0, _util.ensureNotFalsy)(writeRow.document); + eventDocumentData = (0, _utils.ensureNotFalsy)(writeRow.document); previousEventDocumentData = writeRow.previous; } else { throw (0, _rxError.newRxError)('SNH', { @@ -10397,11 +9417,11 @@ bulkWriteRows, context) { eventBulk.events.push({ eventId: getUniqueDeterministicEventKey(storageInstance, primaryPath, writeRow), documentId: id, - documentData: (0, _util.ensureNotFalsy)(eventDocumentData), + documentData: (0, _utils.ensureNotFalsy)(eventDocumentData), previousDocumentData: previousEventDocumentData, operation: operation, startTime: startTime, - endTime: (0, _util.now)() + endTime: (0, _utils.now)() }); } }); @@ -10435,14 +9455,14 @@ function attachmentWriteDataToNormalData(writeData) { return writeData; } var ret = { - digest: (0, _util.defaultHashFunction)(data), + digest: (0, _utils.defaultHashFunction)(data), length: getAttachmentSize(data), type: writeData.type }; return ret; } function stripAttachmentsDataFromDocument(doc) { - var useDoc = (0, _util.flatClone)(doc); + var useDoc = (0, _utils.flatClone)(doc); useDoc._attachments = {}; Object.entries(doc._attachments).forEach(function (_ref4) { var attachmentId = _ref4[0], @@ -10459,8 +9479,8 @@ function stripAttachmentsDataFromDocument(doc) { * during replication etc. */ function flatCloneDocWithMeta(doc) { - var ret = (0, _util.flatClone)(doc); - ret._meta = (0, _util.flatClone)(doc._meta); + var ret = (0, _utils.flatClone)(doc); + ret._meta = (0, _utils.flatClone)(doc._meta); return ret; } @@ -10477,7 +9497,6 @@ function getUniqueDeterministicEventKey(storageInstance, primaryPath, writeRow) var eventKey = storageInstance.databaseName + '|' + storageInstance.collectionName + '|' + docId + '|' + '|' + binary + '|' + writeRow.document._rev; return eventKey; } - /** * Wraps the normal storageInstance of a RxCollection * to ensure that all access is properly using the hooks @@ -10493,8 +9512,8 @@ rxJsonSchema) { _overwritable.overwritable.deepFreezeWhenDevMode(rxJsonSchema); var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(rxJsonSchema.primaryKey); function transformDocumentDataFromRxDBToRxStorage(writeRow) { - var data = (0, _util.flatClone)(writeRow.document); - data._meta = (0, _util.flatClone)(data._meta); + var data = (0, _utils.flatClone)(writeRow.document); + data._meta = (0, _utils.flatClone)(data._meta); /** * Do some checks in dev-mode @@ -10544,20 +9563,21 @@ rxJsonSchema) { }); } } - data._meta.lwt = (0, _util.now)(); + data._meta.lwt = (0, _utils.now)(); /** * Yes we really want to set the revision here. * If you make a plugin that relies on having its own revision * stored into the storage, use this.originalStorageInstance.bulkWrite() instead. */ - data._rev = (0, _util.createRevision)(database.hashFunction, data, writeRow.previous); + data._rev = (0, _utils.createRevision)(database.token, writeRow.previous); return { document: data, previous: writeRow.previous }; } var ret = { + originalStorageInstance: storageInstance, schema: storageInstance.schema, internals: storageInstance.internals, collectionName: storageInstance.collectionName, @@ -10579,22 +9599,22 @@ rxJsonSchema) { * @link https://github.com/pubkey/rxdb/pull/3839 */.then(function (writeResult) { var reInsertErrors = Object.values(writeResult.error).filter(function (error) { - if (error.status === 409 && !error.writeRow.previous && !error.writeRow.document._deleted && (0, _util.ensureNotFalsy)(error.documentInDb)._deleted) { + if (error.status === 409 && !error.writeRow.previous && !error.writeRow.document._deleted && (0, _utils.ensureNotFalsy)(error.documentInDb)._deleted) { return true; } return false; }); if (reInsertErrors.length > 0) { var useWriteResult = { - error: (0, _util.flatClone)(writeResult.error), - success: (0, _util.flatClone)(writeResult.success) + error: (0, _utils.flatClone)(writeResult.error), + success: (0, _utils.flatClone)(writeResult.success) }; var reInserts = reInsertErrors.map(function (error) { delete useWriteResult.error[error.documentId]; return { previous: error.documentInDb, document: Object.assign({}, error.writeRow.document, { - _rev: (0, _util.createRevision)(database.hashFunction, error.writeRow.document, error.documentInDb) + _rev: (0, _utils.createRevision)(database.token, error.documentInDb) }) }; }); @@ -10631,7 +9651,7 @@ rxJsonSchema) { }, getChangedDocumentsSince: function getChangedDocumentsSince(limit, checkpoint) { return database.lockedRun(function () { - return storageInstance.getChangedDocumentsSince((0, _util.ensureNotFalsy)(limit), checkpoint); + return storageInstance.getChangedDocumentsSince((0, _utils.ensureNotFalsy)(limit), checkpoint); }); }, cleanup: function cleanup(minDeletedTime) { @@ -10660,11 +9680,11 @@ rxJsonSchema) { return storageInstance.resolveConflictResultionTask(taskSolution); } var doc = Object.assign({}, taskSolution.output.documentData, { - _meta: (0, _util.getDefaultRxDocumentMeta)(), - _rev: (0, _util.getDefaultRevision)(), + _meta: (0, _utils.getDefaultRxDocumentMeta)(), + _rev: (0, _utils.getDefaultRevision)(), _attachments: {} }); - var documentData = (0, _util.flatClone)(doc); + var documentData = (0, _utils.flatClone)(doc); delete documentData._meta; delete documentData._rev; delete documentData._attachments; @@ -10677,7 +9697,6 @@ rxJsonSchema) { }); } }; - ret.originalStorageInstance = storageInstance; return ret; } @@ -10710,9 +9729,10 @@ function hasEncryption(jsonSchema) { } } -},{"./overwritable":8,"./rx-error":35,"./rx-schema-helper":38,"./util":44}],41:[function(require,module,exports){ +},{"./overwritable":9,"./plugins/utils":12,"./rx-error":41,"./rx-schema-helper":44,"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66}],47:[function(require,module,exports){ "use strict"; +var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); @@ -10720,6 +9740,8 @@ exports.BROADCAST_CHANNEL_BY_TOKEN = void 0; exports.addRxStorageMultiInstanceSupport = addRxStorageMultiInstanceSupport; exports.getBroadcastChannelReference = getBroadcastChannelReference; exports.removeBroadcastChannelReference = removeBroadcastChannelReference; +var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); +var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); var _broadcastChannel = require("broadcast-channel"); @@ -10816,1343 +9838,835 @@ providedBroadcastChannel) { return changesFromOtherInstances$.asObservable().pipe((0, _operators.mergeWith)(oldChangestream$)); }; var oldClose = instance.close.bind(instance); - instance.close = function () { - try { - closed = true; - sub.unsubscribe(); - broadcastChannel.removeEventListener('message', eventListener); - var _temp = function () { - if (!providedBroadcastChannel) { - return Promise.resolve(removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance)).then(function () {}); - } - }(); - return Promise.resolve(_temp && _temp.then ? _temp.then(function () { - return oldClose(); - }) : oldClose()); - } catch (e) { - return Promise.reject(e); - } - }; + instance.close = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + closed = true; + sub.unsubscribe(); + broadcastChannel.removeEventListener('message', eventListener); + if (providedBroadcastChannel) { + _context.next = 6; + break; + } + _context.next = 6; + return removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance); + case 6: + return _context.abrupt("return", oldClose()); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); var oldRemove = instance.remove.bind(instance); - instance.remove = function () { - try { - closed = true; - sub.unsubscribe(); - broadcastChannel.removeEventListener('message', eventListener); - var _temp2 = function () { - if (!providedBroadcastChannel) { - return Promise.resolve(removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance)).then(function () {}); - } - }(); - return Promise.resolve(_temp2 && _temp2.then ? _temp2.then(function () { - return oldRemove(); - }) : oldRemove()); - } catch (e) { - return Promise.reject(e); - } - }; + instance.remove = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + closed = true; + sub.unsubscribe(); + broadcastChannel.removeEventListener('message', eventListener); + if (providedBroadcastChannel) { + _context2.next = 6; + break; + } + _context2.next = 6; + return removeBroadcastChannelReference(instanceCreationParams.databaseInstanceToken, instance); + case 6: + return _context2.abrupt("return", oldRemove()); + case 7: + case "end": + return _context2.stop(); + } + }, _callee2); + })); } -},{"broadcast-channel":82,"rxjs":458,"rxjs/operators":683}],42:[function(require,module,exports){ +},{"@babel/runtime/helpers/asyncToGenerator":52,"@babel/runtime/helpers/interopRequireDefault":57,"@babel/runtime/regenerator":66,"broadcast-channel":89,"rxjs":423,"rxjs/operators":648}],48:[function(require,module,exports){ "use strict"; -},{}],43:[function(require,module,exports){ +},{}],49:[function(require,module,exports){ "use strict"; -},{}],44:[function(require,module,exports){ -(function (Buffer){(function (){ +},{}],50:[function(require,module,exports){ "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RX_META_LWT_MINIMUM = exports.RXJS_SHARE_REPLAY_DEFAULTS = exports.RANDOM_STRING = exports.PROMISE_RESOLVE_VOID = exports.PROMISE_RESOLVE_TRUE = exports.PROMISE_RESOLVE_NULL = exports.PROMISE_RESOLVE_FALSE = void 0; -exports.adapterObject = adapterObject; -exports.areRxDocumentArraysEqual = areRxDocumentArraysEqual; -exports.arrayBufferToBase64 = arrayBufferToBase64; -exports.arrayFilterNotEmpty = arrayFilterNotEmpty; -exports.b64DecodeUnicode = b64DecodeUnicode; -exports.b64EncodeUnicode = b64EncodeUnicode; -exports.batchArray = batchArray; -exports.clone = exports.blobBufferUtil = void 0; -exports.createRevision = createRevision; -exports.deepFreeze = deepFreeze; -exports.defaultHashFunction = defaultHashFunction; -exports.ensureInteger = ensureInteger; -exports.ensureNotFalsy = ensureNotFalsy; -exports.errorToPlainJson = errorToPlainJson; -exports.fastUnsecureHash = fastUnsecureHash; -exports.firstPropertyNameOfObject = firstPropertyNameOfObject; -exports.firstPropertyValueOfObject = firstPropertyValueOfObject; -exports.flatClone = flatClone; -exports.flattenObject = flattenObject; -exports.getDefaultRevision = getDefaultRevision; -exports.getDefaultRxDocumentMeta = getDefaultRxDocumentMeta; -exports.getFromMapOrThrow = getFromMapOrThrow; -exports.getFromObjectOrThrow = getFromObjectOrThrow; -exports.getHeightOfRevision = getHeightOfRevision; -exports.getSortDocumentsByLastWriteTimeComparator = getSortDocumentsByLastWriteTimeComparator; -exports.isFolderPath = isFolderPath; -exports.isMaybeReadonlyArray = isMaybeReadonlyArray; -exports.lastOfArray = lastOfArray; -exports.nextTick = nextTick; -exports.now = now; -exports.objectPathMonad = objectPathMonad; -exports.overwriteGetterForCaching = overwriteGetterForCaching; -exports.parseRevision = parseRevision; -exports.pluginMissing = pluginMissing; -exports.promiseSeries = promiseSeries; -exports.promiseWait = promiseWait; -exports.randomCouchString = randomCouchString; -exports.removeOneFromArrayIfMatches = removeOneFromArrayIfMatches; -exports.requestIdleCallbackIfAvailable = requestIdleCallbackIfAvailable; -exports.requestIdlePromise = requestIdlePromise; -exports.runXTimes = runXTimes; -exports.shuffleArray = shuffleArray; -exports.sortDocumentsByLastWriteTime = sortDocumentsByLastWriteTime; -exports.sortObject = sortObject; -exports.stringifyFilter = stringifyFilter; -exports.toPromise = toPromise; -exports.trimDots = trimDots; -exports.ucfirst = ucfirst; -var _jsBase = require("js-base64"); -/** - * Returns an error that indicates that a plugin is missing - * We do not throw a RxError because this should not be handled - * programmatically but by using the correct import - */ -function pluginMissing(pluginKey) { - var keyParts = pluginKey.split('-'); - var pluginName = 'RxDB'; - keyParts.forEach(function (part) { - pluginName += ucfirst(part); - }); - pluginName += 'Plugin'; - return new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { " + pluginName + " } from 'rxdb/plugins/" + pluginKey + "';\n addRxPlugin(" + pluginName + ");\n "); +require("./noConflict"); + +var _global = _interopRequireDefault(require("core-js/library/fn/global")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +if (_global["default"]._babelPolyfill && typeof console !== "undefined" && console.warn) { + console.warn("@babel/polyfill is loaded more than once on this page. This is probably not desirable/intended " + "and may have consequences if different versions of the polyfills are applied sequentially. " + "If you do need to load the polyfill more than once, use @babel/polyfill/noConflict " + "instead to bypass the warning."); } -/** - * This is a very fast hash method - * but it is not cryptographically secure. - * For each run it will append a number between 0 and 2147483647 (=biggest 32 bit int). - * @link http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery - * @return a string as hash-result - */ -function fastUnsecureHash(inputString, -// used to test the polyfill -doNotUseTextEncoder) { - var hashValue = 0, - i, - chr, - len; +_global["default"]._babelPolyfill = true; +},{"./noConflict":51,"core-js/library/fn/global":115}],51:[function(require,module,exports){ +"use strict"; - /** - * For better performance we first transform all - * chars into their ascii numbers at once. - * - * This is what makes the murmurhash implementation such fast. - * @link https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L4 - */ - var encoded; +require("core-js/es6"); - /** - * All modern browsers support the TextEncoder - * @link https://caniuse.com/textencoder - * But to make RxDB work in other JavaScript runtimes, - * like when using it in flutter or QuickJS, we need to - * make it work even when there is no TextEncoder. - */ - if (typeof TextEncoder !== 'undefined' && !doNotUseTextEncoder) { - encoded = new TextEncoder().encode(inputString); - } else { - encoded = []; - for (var j = 0; j < inputString.length; j++) { - encoded.push(inputString.charCodeAt(j)); - } - } - for (i = 0, len = inputString.length; i < len; i++) { - chr = encoded[i]; - hashValue = (hashValue << 5) - hashValue + chr; - hashValue |= 0; // Convert to 32bit integer - } +require("core-js/fn/array/includes"); - if (hashValue < 0) { - hashValue = hashValue * -1; - } +require("core-js/fn/array/flat-map"); - /** - * To make the output smaller - * but still have it to represent the same value, - * we use the biggest radix of 36 instead of just - * transforming it into a hex string. - */ - return hashValue.toString(36); -} +require("core-js/fn/string/pad-start"); -/** - * Default hash method used to create revision hashes - * that do not have to be cryptographically secure. - * IMPORTANT: Changing the default hashing method - * requires a BREAKING change! - */ -function defaultHashFunction(input) { - return fastUnsecureHash(input); -} +require("core-js/fn/string/pad-end"); -/** - * Returns the current unix time in milliseconds (with two decmials!) - * Because the accuracy of getTime() in javascript is bad, - * and we cannot rely on performance.now() on all platforms, - * this method implements a way to never return the same value twice. - * This ensures that when now() is called often, we do not loose the information - * about which call came first and which came after. - * - * We had to move from having no decimals, to having two decimal - * because it turned out that some storages are such fast that - * calling this method too often would return 'the future'. - */ -var _lastNow = 0; -/** - * Returns the current time in milliseconds, - * also ensures to not return the same value twice. - */ -function now() { - var ret = new Date().getTime(); - ret = ret + 0.01; - if (ret <= _lastNow) { - ret = _lastNow + 0.01; - } +require("core-js/fn/string/trim-start"); - /** - * Strip the returned number to max two decimals. - * In theory we would not need this but - * in practice JavaScript has no such good number precision - * so rounding errors could add another decimal place. - */ - var twoDecimals = parseFloat(ret.toFixed(2)); - _lastNow = twoDecimals; - return twoDecimals; -} +require("core-js/fn/string/trim-end"); -/** - * returns a promise that resolves on the next tick - */ -function nextTick() { - return new Promise(function (res) { - return setTimeout(res, 0); - }); -} -function promiseWait() { - var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - return new Promise(function (res) { - return setTimeout(res, ms); - }); -} -function toPromise(maybePromise) { - if (maybePromise && typeof maybePromise.then === 'function') { - // is promise - return maybePromise; +require("core-js/fn/symbol/async-iterator"); + +require("core-js/fn/object/get-own-property-descriptors"); + +require("core-js/fn/object/values"); + +require("core-js/fn/object/entries"); + +require("core-js/fn/promise/finally"); + +require("core-js/web"); + +require("regenerator-runtime/runtime"); +},{"core-js/es6":103,"core-js/fn/array/flat-map":104,"core-js/fn/array/includes":105,"core-js/fn/object/entries":106,"core-js/fn/object/get-own-property-descriptors":107,"core-js/fn/object/values":108,"core-js/fn/promise/finally":109,"core-js/fn/string/pad-end":110,"core-js/fn/string/pad-start":111,"core-js/fn/string/trim-end":112,"core-js/fn/string/trim-start":113,"core-js/fn/symbol/async-iterator":114,"core-js/web":406,"regenerator-runtime/runtime":422}],52:[function(require,module,exports){ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); } else { - return Promise.resolve(maybePromise); + Promise.resolve(value).then(_next, _throw); } } -var PROMISE_RESOLVE_TRUE = Promise.resolve(true); -exports.PROMISE_RESOLVE_TRUE = PROMISE_RESOLVE_TRUE; -var PROMISE_RESOLVE_FALSE = Promise.resolve(false); -exports.PROMISE_RESOLVE_FALSE = PROMISE_RESOLVE_FALSE; -var PROMISE_RESOLVE_NULL = Promise.resolve(null); -exports.PROMISE_RESOLVE_NULL = PROMISE_RESOLVE_NULL; -var PROMISE_RESOLVE_VOID = Promise.resolve(); -exports.PROMISE_RESOLVE_VOID = PROMISE_RESOLVE_VOID; -function requestIdlePromise() { - var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - if (typeof window === 'object' && window['requestIdleCallback']) { - return new Promise(function (res) { - return window['requestIdleCallback'](res, { - timeout: timeout - }); +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + _next(undefined); }); - } else { - return promiseWait(0); - } + }; } - -/** - * like Promise.all() but runs in series instead of parallel - * @link https://github.com/egoist/promise.series/blob/master/index.js - * @param tasks array with functions that return a promise - */ -function promiseSeries(tasks, initial) { - return tasks.reduce(function (current, next) { - return current.then(next); - }, Promise.resolve(initial)); -} - -/** - * run the callback if requestIdleCallback available - * do nothing if not - * @link https://developer.mozilla.org/de/docs/Web/API/Window/requestIdleCallback - */ -function requestIdleCallbackIfAvailable(fun) { - if (typeof window === 'object' && window['requestIdleCallback']) window['requestIdleCallback'](fun); -} - -/** - * uppercase first char - */ -function ucfirst(str) { - str += ''; - var f = str.charAt(0).toUpperCase(); - return f + str.substr(1); -} - -/** - * removes trailing and ending dots from the string - */ -function trimDots(str) { - // start - while (str.charAt(0) === '.') str = str.substr(1); - - // end - while (str.slice(-1) === '.') str = str.slice(0, -1); - return str; -} -function runXTimes(xTimes, fn) { - new Array(xTimes).fill(0).forEach(function (_v, idx) { - return fn(idx); - }); -} -function ensureNotFalsy(obj) { - if (!obj) { - throw new Error('ensureNotFalsy() is falsy'); +module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],53:[function(require,module,exports){ +var setPrototypeOf = require("./setPrototypeOf.js"); +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct.bind(), module.exports.__esModule = true, module.exports["default"] = module.exports; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; } - return obj; + return _construct.apply(null, arguments); } -function ensureInteger(obj) { - if (!Number.isInteger(obj)) { - throw new Error('ensureInteger() is falsy'); +module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./isNativeReflectConstruct.js":59,"./setPrototypeOf.js":61}],54:[function(require,module,exports){ +var toPropertyKey = require("./toPropertyKey.js"); +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor); } - return obj; } - -/** - * deep-sort an object so its attributes are in lexical order. - * Also sorts the arrays inside of the object if no-array-sort not set - */ -function sortObject(obj) { - var noArraySort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (!obj) return obj; // do not sort null, false or undefined - - // array - if (!noArraySort && Array.isArray(obj)) { - return obj.sort(function (a, b) { - if (typeof a === 'string' && typeof b === 'string') return a.localeCompare(b); - if (typeof a === 'object') return 1;else return -1; - }).map(function (i) { - return sortObject(i, noArraySort); - }); - } - - // object - // array is also of type object - if (typeof obj === 'object' && !Array.isArray(obj)) { - if (obj instanceof RegExp) { - return obj; - } - var out = {}; - Object.keys(obj).sort(function (a, b) { - return a.localeCompare(b); - }).forEach(function (key) { - out[key] = sortObject(obj[key], noArraySort); - }); - return out; - } - - // everything else - return obj; +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; } - -/** - * used to JSON.stringify() objects that contain a regex - * @link https://stackoverflow.com/a/33416684 thank you Fabian Jakobs! - */ -function stringifyFilter(key, value) { - if (value instanceof RegExp) { - return value.toString(); - } - return value; +module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./toPropertyKey.js":63}],55:[function(require,module,exports){ +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _getPrototypeOf(o); } - -/** - * get a random string which can be used with couchdb - * @link http://stackoverflow.com/a/1349426/3443137 - */ -function randomCouchString() { - var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; - var text = ''; - var possible = 'abcdefghijklmnopqrstuvwxyz'; - for (var i = 0; i < length; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } - return text; +module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],56:[function(require,module,exports){ +var setPrototypeOf = require("./setPrototypeOf.js"); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); } - -/** - * A random string that is never inside of any storage - */ -var RANDOM_STRING = 'Fz7SZXPmYJujkzjY1rpXWvlWBqoGAfAX'; -exports.RANDOM_STRING = RANDOM_STRING; -function lastOfArray(ar) { - return ar[ar.length - 1]; +module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./setPrototypeOf.js":61}],57:[function(require,module,exports){ +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; } - -/** - * shuffle the given array - */ -function shuffleArray(arr) { - return arr.sort(function () { - return Math.random() - 0.5; - }); +module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],58:[function(require,module,exports){ +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -/** - * Split array with items into smaller arrays with items - * @link https://stackoverflow.com/a/7273794/3443137 - */ -function batchArray(array, batchSize) { - array = array.slice(0); - var ret = []; - while (array.length) { - var batch = array.splice(0, batchSize); - ret.push(batch); +module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],59:[function(require,module,exports){ +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; } - return ret; } - -/** - * @link https://stackoverflow.com/a/15996017 - */ -function removeOneFromArrayIfMatches(ar, condition) { - ar = ar.slice(); - var i = ar.length; - var done = false; - while (i-- && !done) { - if (condition(ar[i])) { - done = true; - ar.splice(i, 1); - } +module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],60:[function(require,module,exports){ +var _typeof = require("./typeof.js")["default"]; +function _regeneratorRuntime() { + "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ + module.exports = _regeneratorRuntime = function _regeneratorRuntime() { + return exports; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + var exports = {}, + Op = Object.prototype, + hasOwn = Op.hasOwnProperty, + defineProperty = Object.defineProperty || function (obj, key, desc) { + obj[key] = desc.value; + }, + $Symbol = "function" == typeof Symbol ? Symbol : {}, + iteratorSymbol = $Symbol.iterator || "@@iterator", + asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", + toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + function define(obj, key, value) { + return Object.defineProperty(obj, key, { + value: value, + enumerable: !0, + configurable: !0, + writable: !0 + }), obj[key]; } - return ar; -} - -/** - * transforms the given adapter into a pouch-compatible object - */ -function adapterObject(adapter) { - var adapterObj = { - db: adapter - }; - if (typeof adapter === 'string') { - adapterObj = { - adapter: adapter, - db: undefined + try { + define({}, ""); + } catch (err) { + define = function define(obj, key, value) { + return obj[key] = value; }; } - return adapterObj; -} - -/** - * Deep clone a plain json object. - * Does not work with recursive stuff - * or non-plain-json. - * IMPORANT: Performance of this is very important, - * do not change it without running performance tests! - * - * @link https://github.com/zxdong262/deep-copy/blob/master/src/index.ts - */ -function deepClone(src) { - if (!src) { - return src; - } - if (src === null || typeof src !== 'object') { - return src; + function wrap(innerFn, outerFn, self, tryLocsList) { + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, + generator = Object.create(protoGenerator.prototype), + context = new Context(tryLocsList || []); + return defineProperty(generator, "_invoke", { + value: makeInvokeMethod(innerFn, self, context) + }), generator; } - if (Array.isArray(src)) { - var ret = new Array(src.length); - var i = ret.length; - while (i--) { - ret[i] = deepClone(src[i]); + function tryCatch(fn, obj, arg) { + try { + return { + type: "normal", + arg: fn.call(obj, arg) + }; + } catch (err) { + return { + type: "throw", + arg: err + }; } - return ret; } - var dest = {}; - // eslint-disable-next-line guard-for-in - for (var key in src) { - // TODO we should not be required to deep clone RegEx objects, - // this must be fixed in RxDB. - if (src[key] instanceof RegExp) { - dest[key] = src[key]; - } else { - dest[key] = deepClone(src[key]); - } + exports.wrap = wrap; + var ContinueSentinel = {}; + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + var getProto = Object.getPrototypeOf, + NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function (method) { + define(prototype, method, function (arg) { + return this._invoke(method, arg); + }); + }); } - return dest; -} -var clone = deepClone; - -/** - * does a flat copy on the objects, - * is about 3 times faster then using deepClone - * @link https://jsperf.com/object-rest-spread-vs-clone/2 - */ -exports.clone = clone; -function flatClone(obj) { - return Object.assign({}, obj); -} - -/** - * @link https://stackoverflow.com/a/11509718/3443137 - */ -function firstPropertyNameOfObject(obj) { - return Object.keys(obj)[0]; -} -function firstPropertyValueOfObject(obj) { - var key = Object.keys(obj)[0]; - return obj[key]; -} - -/** - * returns a flattened object - * @link https://gist.github.com/penguinboy/762197 - */ -function flattenObject(ob) { - var toReturn = {}; - for (var i in ob) { - if (!ob.hasOwnProperty(i)) continue; - if (typeof ob[i] === 'object') { - var flatObject = flattenObject(ob[i]); - for (var _x in flatObject) { - if (!flatObject.hasOwnProperty(_x)) continue; - toReturn[i + '.' + _x] = flatObject[_x]; + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if ("throw" !== record.type) { + var result = record.arg, + value = result.value; + return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { + invoke("next", value, resolve, reject); + }, function (err) { + invoke("throw", err, resolve, reject); + }) : PromiseImpl.resolve(value).then(function (unwrapped) { + result.value = unwrapped, resolve(result); + }, function (error) { + return invoke("throw", error, resolve, reject); + }); } - } else { - toReturn[i] = ob[i]; + reject(record.arg); } + var previousPromise; + defineProperty(this, "_invoke", { + value: function value(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function (resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); + } + }); } - return toReturn; -} -function parseRevision(revision) { - var split = revision.split('-'); - return { - height: parseInt(split[0], 10), - hash: split[1] - }; -} -function getHeightOfRevision(revision) { - return parseRevision(revision).height; -} - -/** - * Creates the next write revision for a given document. - */ -function createRevision(hashFunction, docData, previousDocData) { - var previousRevision = previousDocData ? previousDocData._rev : null; - var previousRevisionHeigth = previousRevision ? parseRevision(previousRevision).height : 0; - var newRevisionHeight = previousRevisionHeigth + 1; - var docWithoutRev = Object.assign({}, docData, { - _rev: undefined, - _rev_tree: undefined, - /** - * All _meta properties MUST NOT be part of the - * revision hash. - * Plugins might temporarily store data in the _meta - * field and strip it away when the document is replicated - * or written to another storage. - */ - _meta: undefined - }); - - /** - * The revision height must be part of the hash - * as the last parameter of the document data. - * This is required to ensure we never ever create - * two different document states that have the same revision - * hash. Even writing the exact same document data - * must have to result in a different hash so that - * the replication can known if the state just looks equal - * or if it is really exactly the equal state in data and time. - */ - delete docWithoutRev._rev; - docWithoutRev._rev = previousDocData ? newRevisionHeight : 1; - var diggestString = JSON.stringify(docWithoutRev); - var revisionHash = hashFunction(diggestString); - return newRevisionHeight + '-' + revisionHash; -} - -/** - * Faster way to check the equalness of document lists - * compared to doing a deep-equal. - * Here we only check the ids and revisions. - */ -function areRxDocumentArraysEqual(primaryPath, ar1, ar2) { - if (ar1.length !== ar2.length) { - return false; + function makeInvokeMethod(innerFn, self, context) { + var state = "suspendedStart"; + return function (method, arg) { + if ("executing" === state) throw new Error("Generator is already running"); + if ("completed" === state) { + if ("throw" === method) throw arg; + return doneResult(); + } + for (context.method = method, context.arg = arg;;) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { + if ("suspendedStart" === state) throw state = "completed", context.arg; + context.dispatchException(context.arg); + } else "return" === context.method && context.abrupt("return", context.arg); + state = "executing"; + var record = tryCatch(innerFn, self, context); + if ("normal" === record.type) { + if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; + return { + value: record.arg, + done: context.done + }; + } + "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); + } + }; } - var i = 0; - var len = ar1.length; - while (i < len) { - var row1 = ar1[i]; - var row2 = ar2[i]; - i++; - if (row1._rev !== row2._rev || row1[primaryPath] !== row2[primaryPath]) { - return false; + function maybeInvokeDelegate(delegate, context) { + var methodName = context.method, + method = delegate.iterator[methodName]; + if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; + var record = tryCatch(method, delegate.iterator, context.arg); + if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; + var info = record.arg; + return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); + } + function pushTryEntry(locs) { + var entry = { + tryLoc: locs[0] + }; + 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); + } + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal", delete record.arg, entry.completion = record; + } + function Context(tryLocsList) { + this.tryEntries = [{ + tryLoc: "root" + }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); + } + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) return iteratorMethod.call(iterable); + if ("function" == typeof iterable.next) return iterable; + if (!isNaN(iterable.length)) { + var i = -1, + next = function next() { + for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; + return next.value = undefined, next.done = !0, next; + }; + return next.next = next; + } } + return { + next: doneResult + }; } - return true; -} - -/** - * overwrites the getter with the actual value - * Mostly used for caching stuff on the first run - */ -function overwriteGetterForCaching(obj, getterName, value) { - Object.defineProperty(obj, getterName, { - get: function get() { - return value; + function doneResult() { + return { + value: undefined, + done: !0 + }; + } + return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { + value: GeneratorFunctionPrototype, + configurable: !0 + }), defineProperty(GeneratorFunctionPrototype, "constructor", { + value: GeneratorFunction, + configurable: !0 + }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { + var ctor = "function" == typeof genFun && genFun.constructor; + return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); + }, exports.mark = function (genFun) { + return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; + }, exports.awrap = function (arg) { + return { + __await: arg + }; + }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { + void 0 === PromiseImpl && (PromiseImpl = Promise); + var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); + return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { + return result.done ? result.value : iter.next(); + }); + }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { + return this; + }), define(Gp, "toString", function () { + return "[object Generator]"; + }), exports.keys = function (val) { + var object = Object(val), + keys = []; + for (var key in object) keys.push(key); + return keys.reverse(), function next() { + for (; keys.length;) { + var key = keys.pop(); + if (key in object) return next.value = key, next.done = !1, next; + } + return next.done = !0, next; + }; + }, exports.values = values, Context.prototype = { + constructor: Context, + reset: function reset(skipTempReset) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); + }, + stop: function stop() { + this.done = !0; + var rootRecord = this.tryEntries[0].completion; + if ("throw" === rootRecord.type) throw rootRecord.arg; + return this.rval; + }, + dispatchException: function dispatchException(exception) { + if (this.done) throw exception; + var context = this; + function handle(loc, caught) { + return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; + } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i], + record = entry.completion; + if ("root" === entry.tryLoc) return handle("end"); + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"), + hasFinally = hasOwn.call(entry, "finallyLoc"); + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } else if (hasCatch) { + if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); + } else { + if (!hasFinally) throw new Error("try statement without catch or finally"); + if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); + } + } + } + }, + abrupt: function abrupt(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); + var record = finallyEntry ? finallyEntry.completion : {}; + return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); + }, + complete: function complete(record, afterLoc) { + if ("throw" === record.type) throw record.arg; + return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; + }, + finish: function finish(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; + } + }, + "catch": function _catch(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if ("throw" === record.type) { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function delegateYield(iterable, resultName, nextLoc) { + return this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } - }); - return value; + }, exports; } - -/** - * returns true if the given name is likely a folder path - */ -function isFolderPath(name) { - // do not check, if foldername is given - if (name.includes('/') || - // unix - name.includes('\\') // windows - ) { - return true; - } else { - return false; +module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./typeof.js":64}],61:[function(require,module,exports){ +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _setPrototypeOf(o, p); +} +module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],62:[function(require,module,exports){ +var _typeof = require("./typeof.js")["default"]; +function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); } + return (hint === "string" ? String : Number)(input); } -function getFromMapOrThrow(map, key) { - var val = map.get(key); - if (typeof val === 'undefined') { - throw new Error('missing value from map ' + key); - } - return val; -} -function getFromObjectOrThrow(obj, key) { - var val = obj[key]; - if (!val) { - throw new Error('missing value from object ' + key); - } - return val; +module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./typeof.js":64}],63:[function(require,module,exports){ +var _typeof = require("./typeof.js")["default"]; +var toPrimitive = require("./toPrimitive.js"); +function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); } +module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./toPrimitive.js":62,"./typeof.js":64}],64:[function(require,module,exports){ +function _typeof(obj) { + "@babel/helpers - typeof"; -/** - * returns true if the supplied argument is either an Array or a Readonly> - */ -function isMaybeReadonlyArray(x) { - // While this looks strange, it's a workaround for an issue in TypeScript: - // https://github.com/microsoft/TypeScript/issues/17002 - // - // The problem is that `Array.isArray` as a type guard returns `false` for a readonly array, - // but at runtime the object is an array and the runtime call to `Array.isArray` would return `true`. - // The type predicate here allows for both `Array` and `Readonly>` to pass a type check while - // still performing runtime type inspection. - return Array.isArray(x); + return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj); } - -/** - * Use this in array.filter() to remove all empty slots - * and have the correct typings afterwards. - * @link https://stackoverflow.com/a/46700791/3443137 - */ -function arrayFilterNotEmpty(value) { - if (value === null || value === undefined) { - return false; - } - return true; +module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{}],65:[function(require,module,exports){ +var getPrototypeOf = require("./getPrototypeOf.js"); +var setPrototypeOf = require("./setPrototypeOf.js"); +var isNativeFunction = require("./isNativeFunction.js"); +var construct = require("./construct.js"); +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + _cache.set(Class, Wrapper); + } + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }, module.exports.__esModule = true, module.exports["default"] = module.exports; + return _wrapNativeSuper(Class); } +module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; +},{"./construct.js":53,"./getPrototypeOf.js":55,"./isNativeFunction.js":58,"./setPrototypeOf.js":61}],66:[function(require,module,exports){ +// TODO(Babel 8): Remove this file. -/** - * NO! We cannot just use btoa() and atob() - * because they do not work correctly with binary data. - * @link https://stackoverflow.com/q/30106476/3443137 - */ +var runtime = require("../helpers/regeneratorRuntime")(); +module.exports = runtime; -/** - * atob() and btoa() do not work well with non ascii chars, - * so we have to use these helper methods instead. - * @link https://stackoverflow.com/a/30106551/3443137 - */ -// Encoding UTF8 -> base64 -function b64EncodeUnicode(str) { - return (0, _jsBase.encode)(str); +// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } } -// Decoding base64 -> UTF8 -function b64DecodeUnicode(str) { - return (0, _jsBase.decode)(str); -} +},{"../helpers/regeneratorRuntime":60}],67:[function(require,module,exports){ +"use strict"; -/** - * @link https://stackoverflow.com/a/9458996/3443137 - */ -function arrayBufferToBase64(buffer) { - var binary = ''; - var bytes = new Uint8Array(buffer); - var len = bytes.byteLength; - for (var i = 0; i < len; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.pushAtSortPosition = pushAtSortPosition; /** - * This is an abstraction over the Blob/Buffer data structure. - * We need this because it behaves different in different JavaScript runtimes. - * Since RxDB 13.0.0 we switch to Blob-only because Node.js does not support - * the Blob data structure which is also supported by the browsers. + * copied and adapted from npm 'binary-search-insert' + * @link https://www.npmjs.com/package/binary-search-insert */ -var blobBufferUtil = { +function pushAtSortPosition(array, item, compareFunction, noCopy) { + var ret = noCopy ? array : array.slice(0); + var high = ret.length - 1; + var low = 0; + var mid = 0; /** - * depending if we are on node or browser, - * we have to use Buffer(node) or Blob(browser) + * Optimization shortcut. */ - createBlobBuffer: function createBlobBuffer(data, type) { - var blobBuffer = new Blob([data], { - type: type - }); - return blobBuffer; - }, + + if (ret.length === 0) { + ret.push(item); + return [ret, 0]; + } /** - * depending if we are on node or browser, - * we have to use Buffer(node) or Blob(browser) + * So we do not have to ghet the ret[mid] doc again + * at the last we store it here. */ - createBlobBufferFromBase64: function createBlobBufferFromBase64(base64String, type) { - try { - return Promise.resolve(fetch("data:" + type + ";base64," + base64String)).then(function (base64Response) { - return Promise.resolve(base64Response.blob()); - }); - } catch (e) { - return Promise.reject(e); - } - }, - isBlobBuffer: function isBlobBuffer(data) { - if (data instanceof Blob || typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) { - return true; + + + var lastMidDoc; + + while (low <= high) { + // https://github.com/darkskyapp/binary-search + // http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html + mid = low + (high - low >> 1); + lastMidDoc = ret[mid]; + + if (compareFunction(lastMidDoc, item) <= 0.0) { + // searching too low + low = mid + 1; } else { - return false; - } - }, - toString: function toString(blobBuffer) { - /** - * in the electron-renderer we have a typed array insteaf of a blob - * so we have to transform it. - * @link https://github.com/pubkey/rxdb/issues/1371 - */ - var blobBufferType = Object.prototype.toString.call(blobBuffer); - if (blobBufferType === '[object Uint8Array]') { - blobBuffer = new Blob([blobBuffer]); - } - if (typeof blobBuffer === 'string') { - return Promise.resolve(blobBuffer); + // searching too high + high = mid - 1; } - return blobBuffer.text(); - }, - toBase64String: function toBase64String(blobBuffer) { - try { - if (typeof blobBuffer === 'string') { - return Promise.resolve(blobBuffer); - } + } - /** - * in the electron-renderer we have a typed array insteaf of a blob - * so we have to transform it. - * @link https://github.com/pubkey/rxdb/issues/1371 - */ - var blobBufferType = Object.prototype.toString.call(blobBuffer); - if (blobBufferType === '[object Uint8Array]') { - blobBuffer = new Blob([blobBuffer]); - } - return Promise.resolve(fetch(URL.createObjectURL(blobBuffer)).then(function (res) { - return res.arrayBuffer(); - })).then(arrayBufferToBase64); - } catch (e) { - return Promise.reject(e); - } - }, - size: function size(blobBuffer) { - return blobBuffer.size; + if (compareFunction(lastMidDoc, item) <= 0.0) { + mid++; } -}; + /** + * Insert at correct position + */ -/** - * Using shareReplay() without settings will not unsubscribe - * if there are no more subscribers. - * So we use these defaults. - * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95 - */ -exports.blobBufferUtil = blobBufferUtil; -var RXJS_SHARE_REPLAY_DEFAULTS = { - bufferSize: 1, - refCount: true -}; -/** - * We use 1 as minimum so that the value is never falsy. - * This const is used in several places because querying - * with a value lower then the minimum could give false results. - */ -exports.RXJS_SHARE_REPLAY_DEFAULTS = RXJS_SHARE_REPLAY_DEFAULTS; -var RX_META_LWT_MINIMUM = 1; -exports.RX_META_LWT_MINIMUM = RX_META_LWT_MINIMUM; -function getDefaultRxDocumentMeta() { - return { - /** - * Set this to 1 to not waste performance - * while calling new Date().. - * The storage wrappers will anyway update - * the lastWrite time while calling transformDocumentDataFromRxDBToRxStorage() - */ - lwt: RX_META_LWT_MINIMUM - }; + ret.splice(mid, 0, item); + return [ret, mid]; } +},{}],68:[function(require,module,exports){ +'use strict' -/** - * Returns a revision that is not valid. - * Use this to have correct typings - * while the storage wrapper anyway will overwrite the revision. - */ -function getDefaultRevision() { - /** - * Use a non-valid revision format, - * to ensure that the RxStorage will throw - * when the revision is not replaced downstream. - */ - return ''; -} -function getSortDocumentsByLastWriteTimeComparator(primaryPath) { - return function (a, b) { - if (a._meta.lwt === b._meta.lwt) { - if (b[primaryPath] < a[primaryPath]) { - return 1; - } else { - return -1; - } - } else { - return a._meta.lwt - b._meta.lwt; - } - }; -} -function sortDocumentsByLastWriteTime(primaryPath, docs) { - return docs.sort(getSortDocumentsByLastWriteTimeComparator(primaryPath)); -} - -/** - * To get specific nested path values from objects, - * RxDB normally uses the 'object-path' npm module. - * But when performance is really relevant, this is not fast enough. - * Instead we use a monad that can prepare some stuff up front - * and we can re-use the generated function. - */ +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray -function objectPathMonad(objectPath) { - var split = objectPath.split('.'); +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - /** - * Performance shortcut, - * if no nested path is used, - * directly return the field of the object. - */ - if (split.length === 1) { - return function (obj) { - return obj[objectPath]; - }; - } - return function (obj) { - var currentVal = obj; - var t = 0; - while (t < split.length) { - var subPath = split[t]; - currentVal = currentVal[subPath]; - if (typeof currentVal === 'undefined') { - return currentVal; - } - t++; - } - return currentVal; - }; -} -function deepFreeze(o) { - Object.freeze(o); - Object.getOwnPropertyNames(o).forEach(function (prop) { - if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === 'object' || typeof o[prop] === 'function') && !Object.isFrozen(o[prop])) { - deepFreeze(o[prop]); - } - }); - return o; -} -function errorToPlainJson(err) { - var ret = { - name: err.name, - message: err.message, - stack: err.stack, - rxdb: err.rxdb - }; - return ret; +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i } -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":96,"js-base64":420}],45:[function(require,module,exports){ -"use strict"; +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 -require("./noConflict"); +function getLens (b64) { + var len = b64.length -var _global = _interopRequireDefault(require("core-js/library/fn/global")); + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len -if (_global["default"]._babelPolyfill && typeof console !== "undefined" && console.warn) { - console.warn("@babel/polyfill is loaded more than once on this page. This is probably not desirable/intended " + "and may have consequences if different versions of the polyfills are applied sequentially. " + "If you do need to load the polyfill more than once, use @babel/polyfill/noConflict " + "instead to bypass the warning."); -} + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) -_global["default"]._babelPolyfill = true; -},{"./noConflict":46,"core-js/library/fn/global":109}],46:[function(require,module,exports){ -"use strict"; + return [validLen, placeHoldersLen] +} -require("core-js/es6"); +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} -require("core-js/fn/array/includes"); +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} -require("core-js/fn/array/flat-map"); +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] -require("core-js/fn/string/pad-start"); + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) -require("core-js/fn/string/pad-end"); + var curByte = 0 -require("core-js/fn/string/trim-start"); + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen -require("core-js/fn/string/trim-end"); + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } -require("core-js/fn/symbol/async-iterator"); + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } -require("core-js/fn/object/get-own-property-descriptors"); + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } -require("core-js/fn/object/values"); + return arr +} -require("core-js/fn/object/entries"); +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} -require("core-js/fn/promise/finally"); +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} -require("core-js/web"); +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 -require("regenerator-runtime/runtime"); -},{"core-js/es6":97,"core-js/fn/array/flat-map":98,"core-js/fn/array/includes":99,"core-js/fn/object/entries":100,"core-js/fn/object/get-own-property-descriptors":101,"core-js/fn/object/values":102,"core-js/fn/promise/finally":103,"core-js/fn/string/pad-end":104,"core-js/fn/string/pad-start":105,"core-js/fn/string/trim-end":106,"core-js/fn/string/trim-start":107,"core-js/fn/symbol/async-iterator":108,"core-js/web":400,"regenerator-runtime/runtime":457}],47:[function(require,module,exports){ -var setPrototypeOf = require("./setPrototypeOf.js"); -var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); -function _construct(Parent, args, Class) { - if (isNativeReflectConstruct()) { - module.exports = _construct = Reflect.construct.bind(), module.exports.__esModule = true, module.exports["default"] = module.exports; - } else { - module.exports = _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) setPrototypeOf(instance, Class.prototype); - return instance; - }, module.exports.__esModule = true, module.exports["default"] = module.exports; + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } - return _construct.apply(null, arguments); -} -module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{"./isNativeReflectConstruct.js":53,"./setPrototypeOf.js":54}],48:[function(require,module,exports){ -var toPropertyKey = require("./toPropertyKey.js"); -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor); + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) } + + return parts.join('') } -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { - writable: false - }); - return Constructor; -} -module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{"./toPropertyKey.js":56}],49:[function(require,module,exports){ -function _getPrototypeOf(o) { - module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }, module.exports.__esModule = true, module.exports["default"] = module.exports; - return _getPrototypeOf(o); -} -module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{}],50:[function(require,module,exports){ -var setPrototypeOf = require("./setPrototypeOf.js"); -function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - setPrototypeOf(subClass, superClass); -} -module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{"./setPrototypeOf.js":54}],51:[function(require,module,exports){ -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - "default": obj - }; -} -module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{}],52:[function(require,module,exports){ -function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} -module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{}],53:[function(require,module,exports){ -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } -} -module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{}],54:[function(require,module,exports){ -function _setPrototypeOf(o, p) { - module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }, module.exports.__esModule = true, module.exports["default"] = module.exports; - return _setPrototypeOf(o, p); -} -module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{}],55:[function(require,module,exports){ -var _typeof = require("./typeof.js")["default"]; -function _toPrimitive(input, hint) { - if (_typeof(input) !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (_typeof(res) !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{"./typeof.js":57}],56:[function(require,module,exports){ -var _typeof = require("./typeof.js")["default"]; -var toPrimitive = require("./toPrimitive.js"); -function _toPropertyKey(arg) { - var key = toPrimitive(arg, "string"); - return _typeof(key) === "symbol" ? key : String(key); -} -module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{"./toPrimitive.js":55,"./typeof.js":57}],57:[function(require,module,exports){ -function _typeof(obj) { - "@babel/helpers - typeof"; - - return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { - return typeof obj; - } : function (obj) { - return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj); -} -module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{}],58:[function(require,module,exports){ -var getPrototypeOf = require("./getPrototypeOf.js"); -var setPrototypeOf = require("./setPrototypeOf.js"); -var isNativeFunction = require("./isNativeFunction.js"); -var construct = require("./construct.js"); -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !isNativeFunction(Class)) return Class; - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - _cache.set(Class, Wrapper); - } - function Wrapper() { - return construct(Class, arguments, getPrototypeOf(this).constructor); - } - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return setPrototypeOf(Wrapper, Class); - }, module.exports.__esModule = true, module.exports["default"] = module.exports; - return _wrapNativeSuper(Class); -} -module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; -},{"./construct.js":47,"./getPrototypeOf.js":49,"./isNativeFunction.js":52,"./setPrototypeOf.js":54}],59:[function(require,module,exports){ -'use strict'; -module.exports = argsArray; - -function argsArray(fun) { - return function () { - var len = arguments.length; - if (len) { - var args = []; - var i = -1; - while (++i < len) { - args[i] = arguments[i]; - } - return fun.call(this, args); - } else { - return fun.call(this, []); - } - }; -} -},{}],60:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.pushAtSortPosition = pushAtSortPosition; - -/** - * copied and adapted from npm 'binary-search-insert' - * @link https://www.npmjs.com/package/binary-search-insert - */ -function pushAtSortPosition(array, item, compareFunction, noCopy) { - var ret = noCopy ? array : array.slice(0); - var high = ret.length - 1; - var low = 0; - var mid = 0; - /** - * Optimization shortcut. - */ - - if (ret.length === 0) { - ret.push(item); - return [ret, 0]; - } - /** - * So we do not have to ghet the ret[mid] doc again - * at the last we store it here. - */ - - - var lastMidDoc; - - while (low <= high) { - // https://github.com/darkskyapp/binary-search - // http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html - mid = low + (high - low >> 1); - lastMidDoc = ret[mid]; - - if (compareFunction(lastMidDoc, item) <= 0.0) { - // searching too low - low = mid + 1; - } else { - // searching too high - high = mid - 1; - } - } - - if (compareFunction(lastMidDoc, item) <= 0.0) { - mid++; - } - /** - * Insert at correct position - */ - - - ret.splice(mid, 0, item); - return [ret, mid]; -} -},{}],61:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],62:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AbstractNode = void 0; -var util_1 = require("./util"); -var find_similar_node_1 = require("./find-similar-node"); -var AbstractNode = /** @class */ (function () { - function AbstractNode(level, rootNode, type) { - this.level = level; - this.id = (0, util_1.nextNodeId)(); - this.deleted = false; - this.type = type; - this.rootNode = rootNode; - if (rootNode) { - this.rootNode.addNode(this); - } +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractNode = void 0; +var util_1 = require("./util"); +var find_similar_node_1 = require("./find-similar-node"); +var AbstractNode = /** @class */ (function () { + function AbstractNode(level, rootNode, type) { + this.level = level; + this.id = (0, util_1.nextNodeId)(); + this.deleted = false; + this.type = type; + this.rootNode = rootNode; + if (rootNode) { + this.rootNode.addNode(this); + } } AbstractNode.prototype.isEqualToOtherNode = function (otherNode, // optimisation shortcut, is faster if own string already known @@ -12313,7 +10827,7 @@ var AbstractNode = /** @class */ (function () { }()); exports.AbstractNode = AbstractNode; -},{"./find-similar-node":67,"./util":80}],63:[function(require,module,exports){ +},{"./find-similar-node":74,"./util":87}],70:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ensureNodesNotStrictEqual = exports.Branches = void 0; @@ -12390,7 +10904,7 @@ function ensureNodesNotStrictEqual(node1, node2) { } exports.ensureNodesNotStrictEqual = ensureNodesNotStrictEqual; -},{}],64:[function(require,module,exports){ +},{}],71:[function(require,module,exports){ "use strict"; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; @@ -12467,7 +10981,7 @@ function createBddFromTruthTable(truthTable) { } exports.createBddFromTruthTable = createBddFromTruthTable; -},{"./internal-node":69,"./leaf-node":70,"./root-node":79,"./util":80}],65:[function(require,module,exports){ +},{"./internal-node":76,"./leaf-node":77,"./root-node":86,"./util":87}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getNodesRecursive = exports.ensureCorrectBdd = void 0; @@ -12571,7 +11085,7 @@ function getNodesRecursive(node, set) { } exports.getNodesRecursive = getNodesRecursive; -},{}],66:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fillTruthTable = void 0; @@ -12598,7 +11112,7 @@ function fillTruthTable(truthTable, inputLength, value) { } exports.fillTruthTable = fillTruthTable; -},{"./util":80}],67:[function(require,module,exports){ +},{"./util":87}],74:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findSimilarNode = void 0; @@ -12621,7 +11135,7 @@ function findSimilarNode(own, others) { } exports.findSimilarNode = findSimilarNode; -},{}],68:[function(require,module,exports){ +},{}],75:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -12648,7 +11162,7 @@ __exportStar(require("./parents"), exports); __exportStar(require("./root-node"), exports); __exportStar(require("./util"), exports); -},{"./abstract-node":62,"./branches":63,"./create-bdd-from-truth-table":64,"./ensure-correct-bdd":65,"./fill-truth-table":66,"./find-similar-node":67,"./internal-node":69,"./leaf-node":70,"./minimal-string/index":73,"./optimize-brute-force":77,"./parents":78,"./root-node":79,"./util":80}],69:[function(require,module,exports){ +},{"./abstract-node":69,"./branches":70,"./create-bdd-from-truth-table":71,"./ensure-correct-bdd":72,"./fill-truth-table":73,"./find-similar-node":74,"./internal-node":76,"./leaf-node":77,"./minimal-string/index":80,"./optimize-brute-force":84,"./parents":85,"./root-node":86,"./util":87}],76:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { @@ -12714,7 +11228,7 @@ var InternalNode = /** @class */ (function (_super) { }(abstract_node_1.AbstractNode)); exports.InternalNode = InternalNode; -},{"./abstract-node":62,"./branches":63,"./parents":78}],70:[function(require,module,exports){ +},{"./abstract-node":69,"./branches":70,"./parents":85}],77:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { @@ -12767,7 +11281,7 @@ var LeafNode = /** @class */ (function (_super) { }(abstract_node_1.AbstractNode)); exports.LeafNode = LeafNode; -},{"./abstract-node":62,"./parents":78,"./util":80}],71:[function(require,module,exports){ +},{"./abstract-node":69,"./parents":85,"./util":87}],78:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.nodeToString = exports.bddToMinimalString = void 0; @@ -12828,7 +11342,7 @@ function nodeToString(node, idByNode, lastCode) { } exports.nodeToString = nodeToString; -},{"./string-format":76}],72:[function(require,module,exports){ +},{"./string-format":83}],79:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.nodeToSimpleBddNode = exports.bddToSimpleBdd = void 0; @@ -12853,7 +11367,7 @@ function nodeToSimpleBddNode(node) { } exports.nodeToSimpleBddNode = nodeToSimpleBddNode; -},{}],73:[function(require,module,exports){ +},{}],80:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -12872,7 +11386,7 @@ __exportStar(require("./resolve-with-simple-bdd"), exports); __exportStar(require("./string-format"), exports); __exportStar(require("./bdd-to-simple-bdd"), exports); -},{"./bdd-to-minimal-string":71,"./bdd-to-simple-bdd":72,"./minimal-string-to-simple-bdd":74,"./resolve-with-simple-bdd":75,"./string-format":76}],74:[function(require,module,exports){ +},{"./bdd-to-minimal-string":78,"./bdd-to-simple-bdd":79,"./minimal-string-to-simple-bdd":81,"./resolve-with-simple-bdd":82,"./string-format":83}],81:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.minimalStringToSimpleBdd = void 0; @@ -12931,7 +11445,7 @@ function minimalStringToSimpleBdd(str) { } exports.minimalStringToSimpleBdd = minimalStringToSimpleBdd; -},{"../util":80,"./string-format":76}],75:[function(require,module,exports){ +},{"../util":87,"./string-format":83}],82:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveWithSimpleBdd = void 0; @@ -12953,7 +11467,7 @@ function resolveWithSimpleBdd(simpleBdd, fns, input) { } exports.resolveWithSimpleBdd = resolveWithSimpleBdd; -},{"../util":80}],76:[function(require,module,exports){ +},{"../util":87}],83:[function(require,module,exports){ "use strict"; /* let t = 0; @@ -13015,7 +11529,7 @@ function getNextCharId(lastCode) { } exports.getNextCharId = getNextCharId; -},{}],77:[function(require,module,exports){ +},{}],84:[function(require,module,exports){ "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -13254,7 +11768,7 @@ function getArrayWithIndexes(size) { } exports.getArrayWithIndexes = getArrayWithIndexes; -},{"./create-bdd-from-truth-table":64,"./util":80}],78:[function(require,module,exports){ +},{"./create-bdd-from-truth-table":71,"./util":87}],85:[function(require,module,exports){ "use strict"; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; @@ -13324,7 +11838,7 @@ var Parents = /** @class */ (function () { }()); exports.Parents = Parents; -},{}],79:[function(require,module,exports){ +},{}],86:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { @@ -13536,7 +12050,7 @@ var RootNode = /** @class */ (function (_super) { }(abstract_node_1.AbstractNode)); exports.RootNode = RootNode; -},{"./abstract-node":62,"./branches":63,"./minimal-string":73,"./util":80}],80:[function(require,module,exports){ +},{"./abstract-node":69,"./branches":70,"./minimal-string":80,"./util":87}],87:[function(require,module,exports){ "use strict"; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; @@ -13682,7 +12196,7 @@ function splitStringToChunks(str, chunkSize) { } exports.splitStringToChunks = splitStringToChunks; -},{}],81:[function(require,module,exports){ +},{}],88:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -13960,7 +12474,7 @@ function _stopListening(channel) { channel.method.onMessage(channel._state, null, time); } } -},{"./method-chooser.js":85,"./options.js":90,"./util.js":91}],82:[function(require,module,exports){ +},{"./method-chooser.js":92,"./options.js":97,"./util.js":98}],89:[function(require,module,exports){ "use strict"; var _index = require("./index.js"); @@ -13980,7 +12494,7 @@ module.exports = { enforceOptions: _index.enforceOptions, beLeader: _index.beLeader }; -},{"./index.js":83}],83:[function(require,module,exports){ +},{"./index.js":90}],90:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -14024,7 +12538,7 @@ Object.defineProperty(exports, "enforceOptions", { }); var _broadcastChannel = require("./broadcast-channel.js"); var _leaderElection = require("./leader-election.js"); -},{"./broadcast-channel.js":81,"./leader-election.js":84}],84:[function(require,module,exports){ +},{"./broadcast-channel.js":88,"./leader-election.js":91}],91:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -14355,7 +12869,7 @@ function createLeaderElection(channel, options) { channel._leaderElector = elector; return elector; } -},{"./util.js":91,"unload":93}],85:[function(require,module,exports){ +},{"./util.js":98,"unload":100}],92:[function(require,module,exports){ "use strict"; var _typeof = require("@babel/runtime/helpers/typeof"); @@ -14408,7 +12922,7 @@ function chooseMethod(options) { return m.type; })));else return useMethod; } -},{"./methods/indexed-db.js":86,"./methods/localstorage.js":87,"./methods/native.js":88,"./methods/simulate.js":89,"@babel/runtime/helpers/typeof":57}],86:[function(require,module,exports){ +},{"./methods/indexed-db.js":93,"./methods/localstorage.js":94,"./methods/native.js":95,"./methods/simulate.js":96,"@babel/runtime/helpers/typeof":64}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -14781,7 +13295,7 @@ var IndexedDBMethod = { microSeconds: microSeconds }; exports.IndexedDBMethod = IndexedDBMethod; -},{"../options.js":90,"../util.js":91,"oblivious-set":422}],87:[function(require,module,exports){ +},{"../options.js":97,"../util.js":98,"oblivious-set":420}],94:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -14954,7 +13468,7 @@ var LocalstorageMethod = { microSeconds: microSeconds }; exports.LocalstorageMethod = LocalstorageMethod; -},{"../options.js":90,"../util.js":91,"oblivious-set":422}],88:[function(require,module,exports){ +},{"../options.js":97,"../util.js":98,"oblivious-set":420}],95:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15030,7 +13544,7 @@ var NativeMethod = { microSeconds: microSeconds }; exports.NativeMethod = NativeMethod; -},{"../util.js":91}],89:[function(require,module,exports){ +},{"../util.js":98}],96:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15099,7 +13613,7 @@ var SimulateMethod = { microSeconds: microSeconds }; exports.SimulateMethod = SimulateMethod; -},{"../util.js":91}],90:[function(require,module,exports){ +},{"../util.js":98}],97:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15139,7 +13653,7 @@ function fillOptionsWithDefaults() { if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true; return options; } -},{}],91:[function(require,module,exports){ +},{}],98:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15202,7 +13716,7 @@ function microSeconds() { return ms * 1000; } } -},{}],92:[function(require,module,exports){ +},{}],99:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -15254,7 +13768,7 @@ function addBrowser(fn) { * @link https://stackoverflow.com/a/26193516/3443137 */ } -},{}],93:[function(require,module,exports){ +},{}],100:[function(require,module,exports){ (function (process){(function (){ "use strict"; @@ -15315,7 +13829,7 @@ function getSize() { return LISTENERS.size; } }).call(this)}).call(this,require('_process')) -},{"./browser.js":92,"./node.js":94,"_process":456}],94:[function(require,module,exports){ +},{"./browser.js":99,"./node.js":101,"_process":421}],101:[function(require,module,exports){ (function (process){(function (){ "use strict"; @@ -15354,9 +13868,7 @@ function addNode(fn) { }); } }).call(this)}).call(this,require('_process')) -},{"_process":456}],95:[function(require,module,exports){ - -},{}],96:[function(require,module,exports){ +},{"_process":421}],102:[function(require,module,exports){ (function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. @@ -17137,7 +15649,7 @@ function numberIsNaN (obj) { } }).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":61,"buffer":96,"ieee754":412}],97:[function(require,module,exports){ +},{"base64-js":68,"buffer":102,"ieee754":417}],103:[function(require,module,exports){ require('../modules/es6.symbol'); require('../modules/es6.object.create'); require('../modules/es6.object.define-property'); @@ -17278,74 +15790,74 @@ require('../modules/es6.reflect.set'); require('../modules/es6.reflect.set-prototype-of'); module.exports = require('../modules/_core'); -},{"../modules/_core":146,"../modules/es6.array.copy-within":248,"../modules/es6.array.every":249,"../modules/es6.array.fill":250,"../modules/es6.array.filter":251,"../modules/es6.array.find":253,"../modules/es6.array.find-index":252,"../modules/es6.array.for-each":254,"../modules/es6.array.from":255,"../modules/es6.array.index-of":256,"../modules/es6.array.is-array":257,"../modules/es6.array.iterator":258,"../modules/es6.array.join":259,"../modules/es6.array.last-index-of":260,"../modules/es6.array.map":261,"../modules/es6.array.of":262,"../modules/es6.array.reduce":264,"../modules/es6.array.reduce-right":263,"../modules/es6.array.slice":265,"../modules/es6.array.some":266,"../modules/es6.array.sort":267,"../modules/es6.array.species":268,"../modules/es6.date.now":269,"../modules/es6.date.to-iso-string":270,"../modules/es6.date.to-json":271,"../modules/es6.date.to-primitive":272,"../modules/es6.date.to-string":273,"../modules/es6.function.bind":274,"../modules/es6.function.has-instance":275,"../modules/es6.function.name":276,"../modules/es6.map":277,"../modules/es6.math.acosh":278,"../modules/es6.math.asinh":279,"../modules/es6.math.atanh":280,"../modules/es6.math.cbrt":281,"../modules/es6.math.clz32":282,"../modules/es6.math.cosh":283,"../modules/es6.math.expm1":284,"../modules/es6.math.fround":285,"../modules/es6.math.hypot":286,"../modules/es6.math.imul":287,"../modules/es6.math.log10":288,"../modules/es6.math.log1p":289,"../modules/es6.math.log2":290,"../modules/es6.math.sign":291,"../modules/es6.math.sinh":292,"../modules/es6.math.tanh":293,"../modules/es6.math.trunc":294,"../modules/es6.number.constructor":295,"../modules/es6.number.epsilon":296,"../modules/es6.number.is-finite":297,"../modules/es6.number.is-integer":298,"../modules/es6.number.is-nan":299,"../modules/es6.number.is-safe-integer":300,"../modules/es6.number.max-safe-integer":301,"../modules/es6.number.min-safe-integer":302,"../modules/es6.number.parse-float":303,"../modules/es6.number.parse-int":304,"../modules/es6.number.to-fixed":305,"../modules/es6.number.to-precision":306,"../modules/es6.object.assign":307,"../modules/es6.object.create":308,"../modules/es6.object.define-properties":309,"../modules/es6.object.define-property":310,"../modules/es6.object.freeze":311,"../modules/es6.object.get-own-property-descriptor":312,"../modules/es6.object.get-own-property-names":313,"../modules/es6.object.get-prototype-of":314,"../modules/es6.object.is":318,"../modules/es6.object.is-extensible":315,"../modules/es6.object.is-frozen":316,"../modules/es6.object.is-sealed":317,"../modules/es6.object.keys":319,"../modules/es6.object.prevent-extensions":320,"../modules/es6.object.seal":321,"../modules/es6.object.set-prototype-of":322,"../modules/es6.object.to-string":323,"../modules/es6.parse-float":324,"../modules/es6.parse-int":325,"../modules/es6.promise":326,"../modules/es6.reflect.apply":327,"../modules/es6.reflect.construct":328,"../modules/es6.reflect.define-property":329,"../modules/es6.reflect.delete-property":330,"../modules/es6.reflect.enumerate":331,"../modules/es6.reflect.get":334,"../modules/es6.reflect.get-own-property-descriptor":332,"../modules/es6.reflect.get-prototype-of":333,"../modules/es6.reflect.has":335,"../modules/es6.reflect.is-extensible":336,"../modules/es6.reflect.own-keys":337,"../modules/es6.reflect.prevent-extensions":338,"../modules/es6.reflect.set":340,"../modules/es6.reflect.set-prototype-of":339,"../modules/es6.regexp.constructor":341,"../modules/es6.regexp.exec":342,"../modules/es6.regexp.flags":343,"../modules/es6.regexp.match":344,"../modules/es6.regexp.replace":345,"../modules/es6.regexp.search":346,"../modules/es6.regexp.split":347,"../modules/es6.regexp.to-string":348,"../modules/es6.set":349,"../modules/es6.string.anchor":350,"../modules/es6.string.big":351,"../modules/es6.string.blink":352,"../modules/es6.string.bold":353,"../modules/es6.string.code-point-at":354,"../modules/es6.string.ends-with":355,"../modules/es6.string.fixed":356,"../modules/es6.string.fontcolor":357,"../modules/es6.string.fontsize":358,"../modules/es6.string.from-code-point":359,"../modules/es6.string.includes":360,"../modules/es6.string.italics":361,"../modules/es6.string.iterator":362,"../modules/es6.string.link":363,"../modules/es6.string.raw":364,"../modules/es6.string.repeat":365,"../modules/es6.string.small":366,"../modules/es6.string.starts-with":367,"../modules/es6.string.strike":368,"../modules/es6.string.sub":369,"../modules/es6.string.sup":370,"../modules/es6.string.trim":371,"../modules/es6.symbol":372,"../modules/es6.typed.array-buffer":373,"../modules/es6.typed.data-view":374,"../modules/es6.typed.float32-array":375,"../modules/es6.typed.float64-array":376,"../modules/es6.typed.int16-array":377,"../modules/es6.typed.int32-array":378,"../modules/es6.typed.int8-array":379,"../modules/es6.typed.uint16-array":380,"../modules/es6.typed.uint32-array":381,"../modules/es6.typed.uint8-array":382,"../modules/es6.typed.uint8-clamped-array":383,"../modules/es6.weak-map":384,"../modules/es6.weak-set":385}],98:[function(require,module,exports){ +},{"../modules/_core":152,"../modules/es6.array.copy-within":254,"../modules/es6.array.every":255,"../modules/es6.array.fill":256,"../modules/es6.array.filter":257,"../modules/es6.array.find":259,"../modules/es6.array.find-index":258,"../modules/es6.array.for-each":260,"../modules/es6.array.from":261,"../modules/es6.array.index-of":262,"../modules/es6.array.is-array":263,"../modules/es6.array.iterator":264,"../modules/es6.array.join":265,"../modules/es6.array.last-index-of":266,"../modules/es6.array.map":267,"../modules/es6.array.of":268,"../modules/es6.array.reduce":270,"../modules/es6.array.reduce-right":269,"../modules/es6.array.slice":271,"../modules/es6.array.some":272,"../modules/es6.array.sort":273,"../modules/es6.array.species":274,"../modules/es6.date.now":275,"../modules/es6.date.to-iso-string":276,"../modules/es6.date.to-json":277,"../modules/es6.date.to-primitive":278,"../modules/es6.date.to-string":279,"../modules/es6.function.bind":280,"../modules/es6.function.has-instance":281,"../modules/es6.function.name":282,"../modules/es6.map":283,"../modules/es6.math.acosh":284,"../modules/es6.math.asinh":285,"../modules/es6.math.atanh":286,"../modules/es6.math.cbrt":287,"../modules/es6.math.clz32":288,"../modules/es6.math.cosh":289,"../modules/es6.math.expm1":290,"../modules/es6.math.fround":291,"../modules/es6.math.hypot":292,"../modules/es6.math.imul":293,"../modules/es6.math.log10":294,"../modules/es6.math.log1p":295,"../modules/es6.math.log2":296,"../modules/es6.math.sign":297,"../modules/es6.math.sinh":298,"../modules/es6.math.tanh":299,"../modules/es6.math.trunc":300,"../modules/es6.number.constructor":301,"../modules/es6.number.epsilon":302,"../modules/es6.number.is-finite":303,"../modules/es6.number.is-integer":304,"../modules/es6.number.is-nan":305,"../modules/es6.number.is-safe-integer":306,"../modules/es6.number.max-safe-integer":307,"../modules/es6.number.min-safe-integer":308,"../modules/es6.number.parse-float":309,"../modules/es6.number.parse-int":310,"../modules/es6.number.to-fixed":311,"../modules/es6.number.to-precision":312,"../modules/es6.object.assign":313,"../modules/es6.object.create":314,"../modules/es6.object.define-properties":315,"../modules/es6.object.define-property":316,"../modules/es6.object.freeze":317,"../modules/es6.object.get-own-property-descriptor":318,"../modules/es6.object.get-own-property-names":319,"../modules/es6.object.get-prototype-of":320,"../modules/es6.object.is":324,"../modules/es6.object.is-extensible":321,"../modules/es6.object.is-frozen":322,"../modules/es6.object.is-sealed":323,"../modules/es6.object.keys":325,"../modules/es6.object.prevent-extensions":326,"../modules/es6.object.seal":327,"../modules/es6.object.set-prototype-of":328,"../modules/es6.object.to-string":329,"../modules/es6.parse-float":330,"../modules/es6.parse-int":331,"../modules/es6.promise":332,"../modules/es6.reflect.apply":333,"../modules/es6.reflect.construct":334,"../modules/es6.reflect.define-property":335,"../modules/es6.reflect.delete-property":336,"../modules/es6.reflect.enumerate":337,"../modules/es6.reflect.get":340,"../modules/es6.reflect.get-own-property-descriptor":338,"../modules/es6.reflect.get-prototype-of":339,"../modules/es6.reflect.has":341,"../modules/es6.reflect.is-extensible":342,"../modules/es6.reflect.own-keys":343,"../modules/es6.reflect.prevent-extensions":344,"../modules/es6.reflect.set":346,"../modules/es6.reflect.set-prototype-of":345,"../modules/es6.regexp.constructor":347,"../modules/es6.regexp.exec":348,"../modules/es6.regexp.flags":349,"../modules/es6.regexp.match":350,"../modules/es6.regexp.replace":351,"../modules/es6.regexp.search":352,"../modules/es6.regexp.split":353,"../modules/es6.regexp.to-string":354,"../modules/es6.set":355,"../modules/es6.string.anchor":356,"../modules/es6.string.big":357,"../modules/es6.string.blink":358,"../modules/es6.string.bold":359,"../modules/es6.string.code-point-at":360,"../modules/es6.string.ends-with":361,"../modules/es6.string.fixed":362,"../modules/es6.string.fontcolor":363,"../modules/es6.string.fontsize":364,"../modules/es6.string.from-code-point":365,"../modules/es6.string.includes":366,"../modules/es6.string.italics":367,"../modules/es6.string.iterator":368,"../modules/es6.string.link":369,"../modules/es6.string.raw":370,"../modules/es6.string.repeat":371,"../modules/es6.string.small":372,"../modules/es6.string.starts-with":373,"../modules/es6.string.strike":374,"../modules/es6.string.sub":375,"../modules/es6.string.sup":376,"../modules/es6.string.trim":377,"../modules/es6.symbol":378,"../modules/es6.typed.array-buffer":379,"../modules/es6.typed.data-view":380,"../modules/es6.typed.float32-array":381,"../modules/es6.typed.float64-array":382,"../modules/es6.typed.int16-array":383,"../modules/es6.typed.int32-array":384,"../modules/es6.typed.int8-array":385,"../modules/es6.typed.uint16-array":386,"../modules/es6.typed.uint32-array":387,"../modules/es6.typed.uint8-array":388,"../modules/es6.typed.uint8-clamped-array":389,"../modules/es6.weak-map":390,"../modules/es6.weak-set":391}],104:[function(require,module,exports){ require('../../modules/es7.array.flat-map'); module.exports = require('../../modules/_core').Array.flatMap; -},{"../../modules/_core":146,"../../modules/es7.array.flat-map":386}],99:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.array.flat-map":392}],105:[function(require,module,exports){ require('../../modules/es7.array.includes'); module.exports = require('../../modules/_core').Array.includes; -},{"../../modules/_core":146,"../../modules/es7.array.includes":387}],100:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.array.includes":393}],106:[function(require,module,exports){ require('../../modules/es7.object.entries'); module.exports = require('../../modules/_core').Object.entries; -},{"../../modules/_core":146,"../../modules/es7.object.entries":388}],101:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.object.entries":394}],107:[function(require,module,exports){ require('../../modules/es7.object.get-own-property-descriptors'); module.exports = require('../../modules/_core').Object.getOwnPropertyDescriptors; -},{"../../modules/_core":146,"../../modules/es7.object.get-own-property-descriptors":389}],102:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.object.get-own-property-descriptors":395}],108:[function(require,module,exports){ require('../../modules/es7.object.values'); module.exports = require('../../modules/_core').Object.values; -},{"../../modules/_core":146,"../../modules/es7.object.values":390}],103:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.object.values":396}],109:[function(require,module,exports){ 'use strict'; require('../../modules/es6.promise'); require('../../modules/es7.promise.finally'); module.exports = require('../../modules/_core').Promise['finally']; -},{"../../modules/_core":146,"../../modules/es6.promise":326,"../../modules/es7.promise.finally":391}],104:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es6.promise":332,"../../modules/es7.promise.finally":397}],110:[function(require,module,exports){ require('../../modules/es7.string.pad-end'); module.exports = require('../../modules/_core').String.padEnd; -},{"../../modules/_core":146,"../../modules/es7.string.pad-end":392}],105:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.string.pad-end":398}],111:[function(require,module,exports){ require('../../modules/es7.string.pad-start'); module.exports = require('../../modules/_core').String.padStart; -},{"../../modules/_core":146,"../../modules/es7.string.pad-start":393}],106:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.string.pad-start":399}],112:[function(require,module,exports){ require('../../modules/es7.string.trim-right'); module.exports = require('../../modules/_core').String.trimRight; -},{"../../modules/_core":146,"../../modules/es7.string.trim-right":395}],107:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.string.trim-right":401}],113:[function(require,module,exports){ require('../../modules/es7.string.trim-left'); module.exports = require('../../modules/_core').String.trimLeft; -},{"../../modules/_core":146,"../../modules/es7.string.trim-left":394}],108:[function(require,module,exports){ +},{"../../modules/_core":152,"../../modules/es7.string.trim-left":400}],114:[function(require,module,exports){ require('../../modules/es7.symbol.async-iterator'); module.exports = require('../../modules/_wks-ext').f('asyncIterator'); -},{"../../modules/_wks-ext":245,"../../modules/es7.symbol.async-iterator":396}],109:[function(require,module,exports){ +},{"../../modules/_wks-ext":251,"../../modules/es7.symbol.async-iterator":402}],115:[function(require,module,exports){ require('../modules/es7.global'); module.exports = require('../modules/_core').global; -},{"../modules/_core":112,"../modules/es7.global":126}],110:[function(require,module,exports){ +},{"../modules/_core":118,"../modules/es7.global":132}],116:[function(require,module,exports){ module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; -},{}],111:[function(require,module,exports){ +},{}],117:[function(require,module,exports){ var isObject = require('./_is-object'); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; -},{"./_is-object":122}],112:[function(require,module,exports){ +},{"./_is-object":128}],118:[function(require,module,exports){ var core = module.exports = { version: '2.6.12' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef -},{}],113:[function(require,module,exports){ +},{}],119:[function(require,module,exports){ // optional / simple context binding var aFunction = require('./_a-function'); module.exports = function (fn, that, length) { @@ -17367,13 +15879,13 @@ module.exports = function (fn, that, length) { }; }; -},{"./_a-function":110}],114:[function(require,module,exports){ +},{"./_a-function":116}],120:[function(require,module,exports){ // Thank's IE8 for his funny defineProperty module.exports = !require('./_fails')(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); -},{"./_fails":117}],115:[function(require,module,exports){ +},{"./_fails":123}],121:[function(require,module,exports){ var isObject = require('./_is-object'); var document = require('./_global').document; // typeof document.createElement is 'object' in old IE @@ -17382,7 +15894,7 @@ module.exports = function (it) { return is ? document.createElement(it) : {}; }; -},{"./_global":118,"./_is-object":122}],116:[function(require,module,exports){ +},{"./_global":124,"./_is-object":128}],122:[function(require,module,exports){ var global = require('./_global'); var core = require('./_core'); var ctx = require('./_ctx'); @@ -17446,7 +15958,7 @@ $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; -},{"./_core":112,"./_ctx":113,"./_global":118,"./_has":119,"./_hide":120}],117:[function(require,module,exports){ +},{"./_core":118,"./_ctx":119,"./_global":124,"./_has":125,"./_hide":126}],123:[function(require,module,exports){ module.exports = function (exec) { try { return !!exec(); @@ -17455,7 +15967,7 @@ module.exports = function (exec) { } }; -},{}],118:[function(require,module,exports){ +},{}],124:[function(require,module,exports){ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self @@ -17463,13 +15975,13 @@ var global = module.exports = typeof window != 'undefined' && window.Math == Mat : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef -},{}],119:[function(require,module,exports){ +},{}],125:[function(require,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; -},{}],120:[function(require,module,exports){ +},{}],126:[function(require,module,exports){ var dP = require('./_object-dp'); var createDesc = require('./_property-desc'); module.exports = require('./_descriptors') ? function (object, key, value) { @@ -17479,17 +15991,17 @@ module.exports = require('./_descriptors') ? function (object, key, value) { return object; }; -},{"./_descriptors":114,"./_object-dp":123,"./_property-desc":124}],121:[function(require,module,exports){ +},{"./_descriptors":120,"./_object-dp":129,"./_property-desc":130}],127:[function(require,module,exports){ module.exports = !require('./_descriptors') && !require('./_fails')(function () { return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7; }); -},{"./_descriptors":114,"./_dom-create":115,"./_fails":117}],122:[function(require,module,exports){ +},{"./_descriptors":120,"./_dom-create":121,"./_fails":123}],128:[function(require,module,exports){ module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; -},{}],123:[function(require,module,exports){ +},{}],129:[function(require,module,exports){ var anObject = require('./_an-object'); var IE8_DOM_DEFINE = require('./_ie8-dom-define'); var toPrimitive = require('./_to-primitive'); @@ -17507,7 +16019,7 @@ exports.f = require('./_descriptors') ? Object.defineProperty : function defineP return O; }; -},{"./_an-object":111,"./_descriptors":114,"./_ie8-dom-define":121,"./_to-primitive":125}],124:[function(require,module,exports){ +},{"./_an-object":117,"./_descriptors":120,"./_ie8-dom-define":127,"./_to-primitive":131}],130:[function(require,module,exports){ module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), @@ -17517,7 +16029,7 @@ module.exports = function (bitmap, value) { }; }; -},{}],125:[function(require,module,exports){ +},{}],131:[function(require,module,exports){ // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = require('./_is-object'); // instead of the ES6 spec version, we didn't implement @@toPrimitive case @@ -17531,22 +16043,22 @@ module.exports = function (it, S) { throw TypeError("Can't convert object to primitive value"); }; -},{"./_is-object":122}],126:[function(require,module,exports){ +},{"./_is-object":128}],132:[function(require,module,exports){ // https://github.com/tc39/proposal-global var $export = require('./_export'); $export($export.G, { global: require('./_global') }); -},{"./_export":116,"./_global":118}],127:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"dup":110}],128:[function(require,module,exports){ +},{"./_export":122,"./_global":124}],133:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],134:[function(require,module,exports){ var cof = require('./_cof'); module.exports = function (it, msg) { if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); return +it; }; -},{"./_cof":142}],129:[function(require,module,exports){ +},{"./_cof":148}],135:[function(require,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = require('./_wks')('unscopables'); var ArrayProto = Array.prototype; @@ -17555,7 +16067,7 @@ module.exports = function (key) { ArrayProto[UNSCOPABLES][key] = true; }; -},{"./_hide":166,"./_wks":246}],130:[function(require,module,exports){ +},{"./_hide":172,"./_wks":252}],136:[function(require,module,exports){ 'use strict'; var at = require('./_string-at')(true); @@ -17565,16 +16077,16 @@ module.exports = function (S, index, unicode) { return index + (unicode ? at(S, index).length : 1); }; -},{"./_string-at":223}],131:[function(require,module,exports){ +},{"./_string-at":229}],137:[function(require,module,exports){ module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; -},{}],132:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"./_is-object":175,"dup":111}],133:[function(require,module,exports){ +},{}],138:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./_is-object":181,"dup":117}],139:[function(require,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = require('./_to-object'); @@ -17602,7 +16114,7 @@ module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* } return O; }; -},{"./_to-absolute-index":231,"./_to-length":235,"./_to-object":236}],134:[function(require,module,exports){ +},{"./_to-absolute-index":237,"./_to-length":241,"./_to-object":242}],140:[function(require,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = require('./_to-object'); @@ -17619,7 +16131,7 @@ module.exports = function fill(value /* , start = 0, end = @length */) { return O; }; -},{"./_to-absolute-index":231,"./_to-length":235,"./_to-object":236}],135:[function(require,module,exports){ +},{"./_to-absolute-index":237,"./_to-length":241,"./_to-object":242}],141:[function(require,module,exports){ // false -> Array#indexOf // true -> Array#includes var toIObject = require('./_to-iobject'); @@ -17644,7 +16156,7 @@ module.exports = function (IS_INCLUDES) { }; }; -},{"./_to-absolute-index":231,"./_to-iobject":234,"./_to-length":235}],136:[function(require,module,exports){ +},{"./_to-absolute-index":237,"./_to-iobject":240,"./_to-length":241}],142:[function(require,module,exports){ // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter @@ -17690,7 +16202,7 @@ module.exports = function (TYPE, $create) { }; }; -},{"./_array-species-create":139,"./_ctx":148,"./_iobject":171,"./_to-length":235,"./_to-object":236}],137:[function(require,module,exports){ +},{"./_array-species-create":145,"./_ctx":154,"./_iobject":177,"./_to-length":241,"./_to-object":242}],143:[function(require,module,exports){ var aFunction = require('./_a-function'); var toObject = require('./_to-object'); var IObject = require('./_iobject'); @@ -17720,7 +16232,7 @@ module.exports = function (that, callbackfn, aLen, memo, isRight) { return memo; }; -},{"./_a-function":127,"./_iobject":171,"./_to-length":235,"./_to-object":236}],138:[function(require,module,exports){ +},{"./_a-function":133,"./_iobject":177,"./_to-length":241,"./_to-object":242}],144:[function(require,module,exports){ var isObject = require('./_is-object'); var isArray = require('./_is-array'); var SPECIES = require('./_wks')('species'); @@ -17738,7 +16250,7 @@ module.exports = function (original) { } return C === undefined ? Array : C; }; -},{"./_is-array":173,"./_is-object":175,"./_wks":246}],139:[function(require,module,exports){ +},{"./_is-array":179,"./_is-object":181,"./_wks":252}],145:[function(require,module,exports){ // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = require('./_array-species-constructor'); @@ -17746,7 +16258,7 @@ module.exports = function (original, length) { return new (speciesConstructor(original))(length); }; -},{"./_array-species-constructor":138}],140:[function(require,module,exports){ +},{"./_array-species-constructor":144}],146:[function(require,module,exports){ 'use strict'; var aFunction = require('./_a-function'); var isObject = require('./_is-object'); @@ -17773,7 +16285,7 @@ module.exports = Function.bind || function bind(that /* , ...args */) { return bound; }; -},{"./_a-function":127,"./_invoke":170,"./_is-object":175}],141:[function(require,module,exports){ +},{"./_a-function":133,"./_invoke":176,"./_is-object":181}],147:[function(require,module,exports){ // getting tag from 19.1.3.6 Object.prototype.toString() var cof = require('./_cof'); var TAG = require('./_wks')('toStringTag'); @@ -17798,14 +16310,14 @@ module.exports = function (it) { : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; -},{"./_cof":142,"./_wks":246}],142:[function(require,module,exports){ +},{"./_cof":148,"./_wks":252}],148:[function(require,module,exports){ var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; -},{}],143:[function(require,module,exports){ +},{}],149:[function(require,module,exports){ 'use strict'; var dP = require('./_object-dp').f; var create = require('./_object-create'); @@ -17951,7 +16463,7 @@ module.exports = { } }; -},{"./_an-instance":131,"./_ctx":148,"./_descriptors":152,"./_for-of":162,"./_iter-define":179,"./_iter-step":181,"./_meta":188,"./_object-create":192,"./_object-dp":193,"./_redefine-all":211,"./_set-species":217,"./_validate-collection":243}],144:[function(require,module,exports){ +},{"./_an-instance":137,"./_ctx":154,"./_descriptors":158,"./_for-of":168,"./_iter-define":185,"./_iter-step":187,"./_meta":194,"./_object-create":198,"./_object-dp":199,"./_redefine-all":217,"./_set-species":223,"./_validate-collection":249}],150:[function(require,module,exports){ 'use strict'; var redefineAll = require('./_redefine-all'); var getWeak = require('./_meta').getWeak; @@ -18038,7 +16550,7 @@ module.exports = { ufstore: uncaughtFrozenStore }; -},{"./_an-instance":131,"./_an-object":132,"./_array-methods":136,"./_for-of":162,"./_has":165,"./_is-object":175,"./_meta":188,"./_redefine-all":211,"./_validate-collection":243}],145:[function(require,module,exports){ +},{"./_an-instance":137,"./_an-object":138,"./_array-methods":142,"./_for-of":168,"./_has":171,"./_is-object":181,"./_meta":194,"./_redefine-all":217,"./_validate-collection":249}],151:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var $export = require('./_export'); @@ -18125,9 +16637,9 @@ module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { return C; }; -},{"./_an-instance":131,"./_export":156,"./_fails":158,"./_for-of":162,"./_global":164,"./_inherit-if-required":169,"./_is-object":175,"./_iter-detect":180,"./_meta":188,"./_redefine":212,"./_redefine-all":211,"./_set-to-string-tag":218}],146:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"dup":112}],147:[function(require,module,exports){ +},{"./_an-instance":137,"./_export":162,"./_fails":164,"./_for-of":168,"./_global":170,"./_inherit-if-required":175,"./_is-object":181,"./_iter-detect":186,"./_meta":194,"./_redefine":218,"./_redefine-all":217,"./_set-to-string-tag":224}],152:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],153:[function(require,module,exports){ 'use strict'; var $defineProperty = require('./_object-dp'); var createDesc = require('./_property-desc'); @@ -18137,9 +16649,9 @@ module.exports = function (object, index, value) { else object[index] = value; }; -},{"./_object-dp":193,"./_property-desc":210}],148:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"./_a-function":127,"dup":113}],149:[function(require,module,exports){ +},{"./_object-dp":199,"./_property-desc":216}],154:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./_a-function":133,"dup":119}],155:[function(require,module,exports){ 'use strict'; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var fails = require('./_fails'); @@ -18167,7 +16679,7 @@ module.exports = (fails(function () { ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } : $toISOString; -},{"./_fails":158}],150:[function(require,module,exports){ +},{"./_fails":164}],156:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); var toPrimitive = require('./_to-primitive'); @@ -18178,24 +16690,24 @@ module.exports = function (hint) { return toPrimitive(anObject(this), hint != NUMBER); }; -},{"./_an-object":132,"./_to-primitive":237}],151:[function(require,module,exports){ +},{"./_an-object":138,"./_to-primitive":243}],157:[function(require,module,exports){ // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; -},{}],152:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"./_fails":158,"dup":114}],153:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./_global":164,"./_is-object":175,"dup":115}],154:[function(require,module,exports){ +},{}],158:[function(require,module,exports){ +arguments[4][120][0].apply(exports,arguments) +},{"./_fails":164,"dup":120}],159:[function(require,module,exports){ +arguments[4][121][0].apply(exports,arguments) +},{"./_global":170,"./_is-object":181,"dup":121}],160:[function(require,module,exports){ // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); -},{}],155:[function(require,module,exports){ +},{}],161:[function(require,module,exports){ // all enumerable object keys, includes symbols var getKeys = require('./_object-keys'); var gOPS = require('./_object-gops'); @@ -18212,7 +16724,7 @@ module.exports = function (it) { } return result; }; -},{"./_object-gops":198,"./_object-keys":201,"./_object-pie":202}],156:[function(require,module,exports){ +},{"./_object-gops":204,"./_object-keys":207,"./_object-pie":208}],162:[function(require,module,exports){ var global = require('./_global'); var core = require('./_core'); var hide = require('./_hide'); @@ -18257,7 +16769,7 @@ $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; -},{"./_core":146,"./_ctx":148,"./_global":164,"./_hide":166,"./_redefine":212}],157:[function(require,module,exports){ +},{"./_core":152,"./_ctx":154,"./_global":170,"./_hide":172,"./_redefine":218}],163:[function(require,module,exports){ var MATCH = require('./_wks')('match'); module.exports = function (KEY) { var re = /./; @@ -18271,9 +16783,9 @@ module.exports = function (KEY) { } return true; }; -},{"./_wks":246}],158:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"dup":117}],159:[function(require,module,exports){ +},{"./_wks":252}],164:[function(require,module,exports){ +arguments[4][123][0].apply(exports,arguments) +},{"dup":123}],165:[function(require,module,exports){ 'use strict'; require('./es6.regexp.exec'); var redefine = require('./_redefine'); @@ -18371,7 +16883,7 @@ module.exports = function (KEY, length, exec) { } }; -},{"./_defined":151,"./_fails":158,"./_hide":166,"./_redefine":212,"./_regexp-exec":214,"./_wks":246,"./es6.regexp.exec":342}],160:[function(require,module,exports){ +},{"./_defined":157,"./_fails":164,"./_hide":172,"./_redefine":218,"./_regexp-exec":220,"./_wks":252,"./es6.regexp.exec":348}],166:[function(require,module,exports){ 'use strict'; // 21.2.5.3 get RegExp.prototype.flags var anObject = require('./_an-object'); @@ -18386,7 +16898,7 @@ module.exports = function () { return result; }; -},{"./_an-object":132}],161:[function(require,module,exports){ +},{"./_an-object":138}],167:[function(require,module,exports){ 'use strict'; // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray var isArray = require('./_is-array'); @@ -18427,7 +16939,7 @@ function flattenIntoArray(target, original, source, sourceLen, start, depth, map module.exports = flattenIntoArray; -},{"./_ctx":148,"./_is-array":173,"./_is-object":175,"./_to-length":235,"./_wks":246}],162:[function(require,module,exports){ +},{"./_ctx":154,"./_is-array":179,"./_is-object":181,"./_to-length":241,"./_wks":252}],168:[function(require,module,exports){ var ctx = require('./_ctx'); var call = require('./_iter-call'); var isArrayIter = require('./_is-array-iter'); @@ -18454,22 +16966,22 @@ var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) exports.BREAK = BREAK; exports.RETURN = RETURN; -},{"./_an-object":132,"./_ctx":148,"./_is-array-iter":172,"./_iter-call":177,"./_to-length":235,"./core.get-iterator-method":247}],163:[function(require,module,exports){ +},{"./_an-object":138,"./_ctx":154,"./_is-array-iter":178,"./_iter-call":183,"./_to-length":241,"./core.get-iterator-method":253}],169:[function(require,module,exports){ module.exports = require('./_shared')('native-function-to-string', Function.toString); -},{"./_shared":220}],164:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],165:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"dup":119}],166:[function(require,module,exports){ -arguments[4][120][0].apply(exports,arguments) -},{"./_descriptors":152,"./_object-dp":193,"./_property-desc":210,"dup":120}],167:[function(require,module,exports){ +},{"./_shared":226}],170:[function(require,module,exports){ +arguments[4][124][0].apply(exports,arguments) +},{"dup":124}],171:[function(require,module,exports){ +arguments[4][125][0].apply(exports,arguments) +},{"dup":125}],172:[function(require,module,exports){ +arguments[4][126][0].apply(exports,arguments) +},{"./_descriptors":158,"./_object-dp":199,"./_property-desc":216,"dup":126}],173:[function(require,module,exports){ var document = require('./_global').document; module.exports = document && document.documentElement; -},{"./_global":164}],168:[function(require,module,exports){ -arguments[4][121][0].apply(exports,arguments) -},{"./_descriptors":152,"./_dom-create":153,"./_fails":158,"dup":121}],169:[function(require,module,exports){ +},{"./_global":170}],174:[function(require,module,exports){ +arguments[4][127][0].apply(exports,arguments) +},{"./_descriptors":158,"./_dom-create":159,"./_fails":164,"dup":127}],175:[function(require,module,exports){ var isObject = require('./_is-object'); var setPrototypeOf = require('./_set-proto').set; module.exports = function (that, target, C) { @@ -18480,7 +16992,7 @@ module.exports = function (that, target, C) { } return that; }; -},{"./_is-object":175,"./_set-proto":216}],170:[function(require,module,exports){ +},{"./_is-object":181,"./_set-proto":222}],176:[function(require,module,exports){ // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; @@ -18498,7 +17010,7 @@ module.exports = function (fn, args, that) { } return fn.apply(that, args); }; -},{}],171:[function(require,module,exports){ +},{}],177:[function(require,module,exports){ // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = require('./_cof'); // eslint-disable-next-line no-prototype-builtins @@ -18506,7 +17018,7 @@ module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; -},{"./_cof":142}],172:[function(require,module,exports){ +},{"./_cof":148}],178:[function(require,module,exports){ // check on default Array iterator var Iterators = require('./_iterators'); var ITERATOR = require('./_wks')('iterator'); @@ -18516,14 +17028,14 @@ module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; -},{"./_iterators":182,"./_wks":246}],173:[function(require,module,exports){ +},{"./_iterators":188,"./_wks":252}],179:[function(require,module,exports){ // 7.2.2 IsArray(argument) var cof = require('./_cof'); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; -},{"./_cof":142}],174:[function(require,module,exports){ +},{"./_cof":148}],180:[function(require,module,exports){ // 20.1.2.3 Number.isInteger(number) var isObject = require('./_is-object'); var floor = Math.floor; @@ -18531,9 +17043,9 @@ module.exports = function isInteger(it) { return !isObject(it) && isFinite(it) && floor(it) === it; }; -},{"./_is-object":175}],175:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"dup":122}],176:[function(require,module,exports){ +},{"./_is-object":181}],181:[function(require,module,exports){ +arguments[4][128][0].apply(exports,arguments) +},{"dup":128}],182:[function(require,module,exports){ // 7.2.8 IsRegExp(argument) var isObject = require('./_is-object'); var cof = require('./_cof'); @@ -18543,7 +17055,7 @@ module.exports = function (it) { return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; -},{"./_cof":142,"./_is-object":175,"./_wks":246}],177:[function(require,module,exports){ +},{"./_cof":148,"./_is-object":181,"./_wks":252}],183:[function(require,module,exports){ // call something on iterator step with safe closing on error var anObject = require('./_an-object'); module.exports = function (iterator, fn, value, entries) { @@ -18557,7 +17069,7 @@ module.exports = function (iterator, fn, value, entries) { } }; -},{"./_an-object":132}],178:[function(require,module,exports){ +},{"./_an-object":138}],184:[function(require,module,exports){ 'use strict'; var create = require('./_object-create'); var descriptor = require('./_property-desc'); @@ -18572,7 +17084,7 @@ module.exports = function (Constructor, NAME, next) { setToStringTag(Constructor, NAME + ' Iterator'); }; -},{"./_hide":166,"./_object-create":192,"./_property-desc":210,"./_set-to-string-tag":218,"./_wks":246}],179:[function(require,module,exports){ +},{"./_hide":172,"./_object-create":198,"./_property-desc":216,"./_set-to-string-tag":224,"./_wks":252}],185:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library'); var $export = require('./_export'); @@ -18643,7 +17155,7 @@ module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE return methods; }; -},{"./_export":156,"./_hide":166,"./_iter-create":178,"./_iterators":182,"./_library":183,"./_object-gpo":199,"./_redefine":212,"./_set-to-string-tag":218,"./_wks":246}],180:[function(require,module,exports){ +},{"./_export":162,"./_hide":172,"./_iter-create":184,"./_iterators":188,"./_library":189,"./_object-gpo":205,"./_redefine":218,"./_set-to-string-tag":224,"./_wks":252}],186:[function(require,module,exports){ var ITERATOR = require('./_wks')('iterator'); var SAFE_CLOSING = false; @@ -18667,18 +17179,18 @@ module.exports = function (exec, skipClosing) { return safe; }; -},{"./_wks":246}],181:[function(require,module,exports){ +},{"./_wks":252}],187:[function(require,module,exports){ module.exports = function (done, value) { return { value: value, done: !!done }; }; -},{}],182:[function(require,module,exports){ +},{}],188:[function(require,module,exports){ module.exports = {}; -},{}],183:[function(require,module,exports){ +},{}],189:[function(require,module,exports){ module.exports = false; -},{}],184:[function(require,module,exports){ +},{}],190:[function(require,module,exports){ // 20.2.2.14 Math.expm1(x) var $expm1 = Math.expm1; module.exports = (!$expm1 @@ -18690,7 +17202,7 @@ module.exports = (!$expm1 return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; } : $expm1; -},{}],185:[function(require,module,exports){ +},{}],191:[function(require,module,exports){ // 20.2.2.16 Math.fround(x) var sign = require('./_math-sign'); var pow = Math.pow; @@ -18715,20 +17227,20 @@ module.exports = Math.fround || function fround(x) { return $sign * result; }; -},{"./_math-sign":187}],186:[function(require,module,exports){ +},{"./_math-sign":193}],192:[function(require,module,exports){ // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x) { return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; -},{}],187:[function(require,module,exports){ +},{}],193:[function(require,module,exports){ // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x) { // eslint-disable-next-line no-self-compare return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; -},{}],188:[function(require,module,exports){ +},{}],194:[function(require,module,exports){ var META = require('./_uid')('meta'); var isObject = require('./_is-object'); var has = require('./_has'); @@ -18783,7 +17295,7 @@ var meta = module.exports = { onFreeze: onFreeze }; -},{"./_fails":158,"./_has":165,"./_is-object":175,"./_object-dp":193,"./_uid":241}],189:[function(require,module,exports){ +},{"./_fails":164,"./_has":171,"./_is-object":181,"./_object-dp":199,"./_uid":247}],195:[function(require,module,exports){ var global = require('./_global'); var macrotask = require('./_task').set; var Observer = global.MutationObserver || global.WebKitMutationObserver; @@ -18854,7 +17366,7 @@ module.exports = function () { }; }; -},{"./_cof":142,"./_global":164,"./_task":230}],190:[function(require,module,exports){ +},{"./_cof":148,"./_global":170,"./_task":236}],196:[function(require,module,exports){ 'use strict'; // 25.4.1.5 NewPromiseCapability(C) var aFunction = require('./_a-function'); @@ -18874,7 +17386,7 @@ module.exports.f = function (C) { return new PromiseCapability(C); }; -},{"./_a-function":127}],191:[function(require,module,exports){ +},{"./_a-function":133}],197:[function(require,module,exports){ 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var DESCRIPTORS = require('./_descriptors'); @@ -18914,7 +17426,7 @@ module.exports = !$assign || require('./_fails')(function () { } return T; } : $assign; -},{"./_descriptors":152,"./_fails":158,"./_iobject":171,"./_object-gops":198,"./_object-keys":201,"./_object-pie":202,"./_to-object":236}],192:[function(require,module,exports){ +},{"./_descriptors":158,"./_fails":164,"./_iobject":177,"./_object-gops":204,"./_object-keys":207,"./_object-pie":208,"./_to-object":242}],198:[function(require,module,exports){ // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = require('./_an-object'); var dPs = require('./_object-dps'); @@ -18957,9 +17469,9 @@ module.exports = Object.create || function create(O, Properties) { return Properties === undefined ? result : dPs(result, Properties); }; -},{"./_an-object":132,"./_dom-create":153,"./_enum-bug-keys":154,"./_html":167,"./_object-dps":194,"./_shared-key":219}],193:[function(require,module,exports){ -arguments[4][123][0].apply(exports,arguments) -},{"./_an-object":132,"./_descriptors":152,"./_ie8-dom-define":168,"./_to-primitive":237,"dup":123}],194:[function(require,module,exports){ +},{"./_an-object":138,"./_dom-create":159,"./_enum-bug-keys":160,"./_html":173,"./_object-dps":200,"./_shared-key":225}],199:[function(require,module,exports){ +arguments[4][129][0].apply(exports,arguments) +},{"./_an-object":138,"./_descriptors":158,"./_ie8-dom-define":174,"./_to-primitive":243,"dup":129}],200:[function(require,module,exports){ var dP = require('./_object-dp'); var anObject = require('./_an-object'); var getKeys = require('./_object-keys'); @@ -18974,7 +17486,7 @@ module.exports = require('./_descriptors') ? Object.defineProperties : function return O; }; -},{"./_an-object":132,"./_descriptors":152,"./_object-dp":193,"./_object-keys":201}],195:[function(require,module,exports){ +},{"./_an-object":138,"./_descriptors":158,"./_object-dp":199,"./_object-keys":207}],201:[function(require,module,exports){ var pIE = require('./_object-pie'); var createDesc = require('./_property-desc'); var toIObject = require('./_to-iobject'); @@ -18992,7 +17504,7 @@ exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; -},{"./_descriptors":152,"./_has":165,"./_ie8-dom-define":168,"./_object-pie":202,"./_property-desc":210,"./_to-iobject":234,"./_to-primitive":237}],196:[function(require,module,exports){ +},{"./_descriptors":158,"./_has":171,"./_ie8-dom-define":174,"./_object-pie":208,"./_property-desc":216,"./_to-iobject":240,"./_to-primitive":243}],202:[function(require,module,exports){ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = require('./_to-iobject'); var gOPN = require('./_object-gopn').f; @@ -19013,7 +17525,7 @@ module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; -},{"./_object-gopn":197,"./_to-iobject":234}],197:[function(require,module,exports){ +},{"./_object-gopn":203,"./_to-iobject":240}],203:[function(require,module,exports){ // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = require('./_object-keys-internal'); var hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype'); @@ -19022,10 +17534,10 @@ exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; -},{"./_enum-bug-keys":154,"./_object-keys-internal":200}],198:[function(require,module,exports){ +},{"./_enum-bug-keys":160,"./_object-keys-internal":206}],204:[function(require,module,exports){ exports.f = Object.getOwnPropertySymbols; -},{}],199:[function(require,module,exports){ +},{}],205:[function(require,module,exports){ // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = require('./_has'); var toObject = require('./_to-object'); @@ -19040,7 +17552,7 @@ module.exports = Object.getPrototypeOf || function (O) { } return O instanceof Object ? ObjectProto : null; }; -},{"./_has":165,"./_shared-key":219,"./_to-object":236}],200:[function(require,module,exports){ +},{"./_has":171,"./_shared-key":225,"./_to-object":242}],206:[function(require,module,exports){ var has = require('./_has'); var toIObject = require('./_to-iobject'); var arrayIndexOf = require('./_array-includes')(false); @@ -19059,7 +17571,7 @@ module.exports = function (object, names) { return result; }; -},{"./_array-includes":135,"./_has":165,"./_shared-key":219,"./_to-iobject":234}],201:[function(require,module,exports){ +},{"./_array-includes":141,"./_has":171,"./_shared-key":225,"./_to-iobject":240}],207:[function(require,module,exports){ // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = require('./_object-keys-internal'); var enumBugKeys = require('./_enum-bug-keys'); @@ -19068,10 +17580,10 @@ module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; -},{"./_enum-bug-keys":154,"./_object-keys-internal":200}],202:[function(require,module,exports){ +},{"./_enum-bug-keys":160,"./_object-keys-internal":206}],208:[function(require,module,exports){ exports.f = {}.propertyIsEnumerable; -},{}],203:[function(require,module,exports){ +},{}],209:[function(require,module,exports){ // most Object methods by ES6 should accept primitives var $export = require('./_export'); var core = require('./_core'); @@ -19083,7 +17595,7 @@ module.exports = function (KEY, exec) { $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); }; -},{"./_core":146,"./_export":156,"./_fails":158}],204:[function(require,module,exports){ +},{"./_core":152,"./_export":162,"./_fails":164}],210:[function(require,module,exports){ var DESCRIPTORS = require('./_descriptors'); var getKeys = require('./_object-keys'); var toIObject = require('./_to-iobject'); @@ -19106,7 +17618,7 @@ module.exports = function (isEntries) { }; }; -},{"./_descriptors":152,"./_object-keys":201,"./_object-pie":202,"./_to-iobject":234}],205:[function(require,module,exports){ +},{"./_descriptors":158,"./_object-keys":207,"./_object-pie":208,"./_to-iobject":240}],211:[function(require,module,exports){ // all object keys, includes non-enumerable and symbols var gOPN = require('./_object-gopn'); var gOPS = require('./_object-gops'); @@ -19118,7 +17630,7 @@ module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { return getSymbols ? keys.concat(getSymbols(it)) : keys; }; -},{"./_an-object":132,"./_global":164,"./_object-gopn":197,"./_object-gops":198}],206:[function(require,module,exports){ +},{"./_an-object":138,"./_global":170,"./_object-gopn":203,"./_object-gops":204}],212:[function(require,module,exports){ var $parseFloat = require('./_global').parseFloat; var $trim = require('./_string-trim').trim; @@ -19128,7 +17640,7 @@ module.exports = 1 / $parseFloat(require('./_string-ws') + '-0') !== -Infinity ? return result === 0 && string.charAt(0) == '-' ? -0 : result; } : $parseFloat; -},{"./_global":164,"./_string-trim":228,"./_string-ws":229}],207:[function(require,module,exports){ +},{"./_global":170,"./_string-trim":234,"./_string-ws":235}],213:[function(require,module,exports){ var $parseInt = require('./_global').parseInt; var $trim = require('./_string-trim').trim; var ws = require('./_string-ws'); @@ -19139,7 +17651,7 @@ module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? f return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); } : $parseInt; -},{"./_global":164,"./_string-trim":228,"./_string-ws":229}],208:[function(require,module,exports){ +},{"./_global":170,"./_string-trim":234,"./_string-ws":235}],214:[function(require,module,exports){ module.exports = function (exec) { try { return { e: false, v: exec() }; @@ -19148,7 +17660,7 @@ module.exports = function (exec) { } }; -},{}],209:[function(require,module,exports){ +},{}],215:[function(require,module,exports){ var anObject = require('./_an-object'); var isObject = require('./_is-object'); var newPromiseCapability = require('./_new-promise-capability'); @@ -19162,16 +17674,16 @@ module.exports = function (C, x) { return promiseCapability.promise; }; -},{"./_an-object":132,"./_is-object":175,"./_new-promise-capability":190}],210:[function(require,module,exports){ -arguments[4][124][0].apply(exports,arguments) -},{"dup":124}],211:[function(require,module,exports){ +},{"./_an-object":138,"./_is-object":181,"./_new-promise-capability":196}],216:[function(require,module,exports){ +arguments[4][130][0].apply(exports,arguments) +},{"dup":130}],217:[function(require,module,exports){ var redefine = require('./_redefine'); module.exports = function (target, src, safe) { for (var key in src) redefine(target, key, src[key], safe); return target; }; -},{"./_redefine":212}],212:[function(require,module,exports){ +},{"./_redefine":218}],218:[function(require,module,exports){ var global = require('./_global'); var hide = require('./_hide'); var has = require('./_has'); @@ -19204,7 +17716,7 @@ require('./_core').inspectSource = function (it) { return typeof this == 'function' && this[SRC] || $toString.call(this); }); -},{"./_core":146,"./_function-to-string":163,"./_global":164,"./_has":165,"./_hide":166,"./_uid":241}],213:[function(require,module,exports){ +},{"./_core":152,"./_function-to-string":169,"./_global":170,"./_has":171,"./_hide":172,"./_uid":247}],219:[function(require,module,exports){ 'use strict'; var classof = require('./_classof'); @@ -19227,7 +17739,7 @@ module.exports = function (R, S) { return builtinExec.call(R, S); }; -},{"./_classof":141}],214:[function(require,module,exports){ +},{"./_classof":147}],220:[function(require,module,exports){ 'use strict'; var regexpFlags = require('./_flags'); @@ -19287,14 +17799,14 @@ if (PATCH) { module.exports = patchedExec; -},{"./_flags":160}],215:[function(require,module,exports){ +},{"./_flags":166}],221:[function(require,module,exports){ // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y) { // eslint-disable-next-line no-self-compare return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; -},{}],216:[function(require,module,exports){ +},{}],222:[function(require,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = require('./_is-object'); @@ -19321,7 +17833,7 @@ module.exports = { check: check }; -},{"./_an-object":132,"./_ctx":148,"./_is-object":175,"./_object-gopd":195}],217:[function(require,module,exports){ +},{"./_an-object":138,"./_ctx":154,"./_is-object":181,"./_object-gopd":201}],223:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var dP = require('./_object-dp'); @@ -19336,7 +17848,7 @@ module.exports = function (KEY) { }); }; -},{"./_descriptors":152,"./_global":164,"./_object-dp":193,"./_wks":246}],218:[function(require,module,exports){ +},{"./_descriptors":158,"./_global":170,"./_object-dp":199,"./_wks":252}],224:[function(require,module,exports){ var def = require('./_object-dp').f; var has = require('./_has'); var TAG = require('./_wks')('toStringTag'); @@ -19345,14 +17857,14 @@ module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; -},{"./_has":165,"./_object-dp":193,"./_wks":246}],219:[function(require,module,exports){ +},{"./_has":171,"./_object-dp":199,"./_wks":252}],225:[function(require,module,exports){ var shared = require('./_shared')('keys'); var uid = require('./_uid'); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; -},{"./_shared":220,"./_uid":241}],220:[function(require,module,exports){ +},{"./_shared":226,"./_uid":247}],226:[function(require,module,exports){ var core = require('./_core'); var global = require('./_global'); var SHARED = '__core-js_shared__'; @@ -19366,7 +17878,7 @@ var store = global[SHARED] || (global[SHARED] = {}); copyright: '© 2020 Denis Pushkarev (zloirock.ru)' }); -},{"./_core":146,"./_global":164,"./_library":183}],221:[function(require,module,exports){ +},{"./_core":152,"./_global":170,"./_library":189}],227:[function(require,module,exports){ // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = require('./_an-object'); var aFunction = require('./_a-function'); @@ -19377,7 +17889,7 @@ module.exports = function (O, D) { return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; -},{"./_a-function":127,"./_an-object":132,"./_wks":246}],222:[function(require,module,exports){ +},{"./_a-function":133,"./_an-object":138,"./_wks":252}],228:[function(require,module,exports){ 'use strict'; var fails = require('./_fails'); @@ -19388,7 +17900,7 @@ module.exports = function (method, arg) { }); }; -},{"./_fails":158}],223:[function(require,module,exports){ +},{"./_fails":164}],229:[function(require,module,exports){ var toInteger = require('./_to-integer'); var defined = require('./_defined'); // true -> String#at @@ -19407,7 +17919,7 @@ module.exports = function (TO_STRING) { }; }; -},{"./_defined":151,"./_to-integer":233}],224:[function(require,module,exports){ +},{"./_defined":157,"./_to-integer":239}],230:[function(require,module,exports){ // helper for String#{startsWith, endsWith, includes} var isRegExp = require('./_is-regexp'); var defined = require('./_defined'); @@ -19417,7 +17929,7 @@ module.exports = function (that, searchString, NAME) { return String(defined(that)); }; -},{"./_defined":151,"./_is-regexp":176}],225:[function(require,module,exports){ +},{"./_defined":157,"./_is-regexp":182}],231:[function(require,module,exports){ var $export = require('./_export'); var fails = require('./_fails'); var defined = require('./_defined'); @@ -19438,7 +17950,7 @@ module.exports = function (NAME, exec) { }), 'String', O); }; -},{"./_defined":151,"./_export":156,"./_fails":158}],226:[function(require,module,exports){ +},{"./_defined":157,"./_export":162,"./_fails":164}],232:[function(require,module,exports){ // https://github.com/tc39/proposal-string-pad-start-end var toLength = require('./_to-length'); var repeat = require('./_string-repeat'); @@ -19456,7 +17968,7 @@ module.exports = function (that, maxLength, fillString, left) { return left ? stringFiller + S : S + stringFiller; }; -},{"./_defined":151,"./_string-repeat":227,"./_to-length":235}],227:[function(require,module,exports){ +},{"./_defined":157,"./_string-repeat":233,"./_to-length":241}],233:[function(require,module,exports){ 'use strict'; var toInteger = require('./_to-integer'); var defined = require('./_defined'); @@ -19470,7 +17982,7 @@ module.exports = function repeat(count) { return res; }; -},{"./_defined":151,"./_to-integer":233}],228:[function(require,module,exports){ +},{"./_defined":157,"./_to-integer":239}],234:[function(require,module,exports){ var $export = require('./_export'); var defined = require('./_defined'); var fails = require('./_fails'); @@ -19502,11 +18014,11 @@ var trim = exporter.trim = function (string, TYPE) { module.exports = exporter; -},{"./_defined":151,"./_export":156,"./_fails":158,"./_string-ws":229}],229:[function(require,module,exports){ +},{"./_defined":157,"./_export":162,"./_fails":164,"./_string-ws":235}],235:[function(require,module,exports){ module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; -},{}],230:[function(require,module,exports){ +},{}],236:[function(require,module,exports){ var ctx = require('./_ctx'); var invoke = require('./_invoke'); var html = require('./_html'); @@ -19592,7 +18104,7 @@ module.exports = { clear: clearTask }; -},{"./_cof":142,"./_ctx":148,"./_dom-create":153,"./_global":164,"./_html":167,"./_invoke":170}],231:[function(require,module,exports){ +},{"./_cof":148,"./_ctx":154,"./_dom-create":159,"./_global":170,"./_html":173,"./_invoke":176}],237:[function(require,module,exports){ var toInteger = require('./_to-integer'); var max = Math.max; var min = Math.min; @@ -19601,7 +18113,7 @@ module.exports = function (index, length) { return index < 0 ? max(index + length, 0) : min(index, length); }; -},{"./_to-integer":233}],232:[function(require,module,exports){ +},{"./_to-integer":239}],238:[function(require,module,exports){ // https://tc39.github.io/ecma262/#sec-toindex var toInteger = require('./_to-integer'); var toLength = require('./_to-length'); @@ -19613,7 +18125,7 @@ module.exports = function (it) { return length; }; -},{"./_to-integer":233,"./_to-length":235}],233:[function(require,module,exports){ +},{"./_to-integer":239,"./_to-length":241}],239:[function(require,module,exports){ // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; @@ -19621,7 +18133,7 @@ module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; -},{}],234:[function(require,module,exports){ +},{}],240:[function(require,module,exports){ // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = require('./_iobject'); var defined = require('./_defined'); @@ -19629,7 +18141,7 @@ module.exports = function (it) { return IObject(defined(it)); }; -},{"./_defined":151,"./_iobject":171}],235:[function(require,module,exports){ +},{"./_defined":157,"./_iobject":177}],241:[function(require,module,exports){ // 7.1.15 ToLength var toInteger = require('./_to-integer'); var min = Math.min; @@ -19637,16 +18149,16 @@ module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; -},{"./_to-integer":233}],236:[function(require,module,exports){ +},{"./_to-integer":239}],242:[function(require,module,exports){ // 7.1.13 ToObject(argument) var defined = require('./_defined'); module.exports = function (it) { return Object(defined(it)); }; -},{"./_defined":151}],237:[function(require,module,exports){ -arguments[4][125][0].apply(exports,arguments) -},{"./_is-object":175,"dup":125}],238:[function(require,module,exports){ +},{"./_defined":157}],243:[function(require,module,exports){ +arguments[4][131][0].apply(exports,arguments) +},{"./_is-object":181,"dup":131}],244:[function(require,module,exports){ 'use strict'; if (require('./_descriptors')) { var LIBRARY = require('./_library'); @@ -20128,7 +18640,7 @@ if (require('./_descriptors')) { }; } else module.exports = function () { /* empty */ }; -},{"./_an-instance":131,"./_array-copy-within":133,"./_array-fill":134,"./_array-includes":135,"./_array-methods":136,"./_classof":141,"./_ctx":148,"./_descriptors":152,"./_export":156,"./_fails":158,"./_global":164,"./_has":165,"./_hide":166,"./_is-array-iter":172,"./_is-object":175,"./_iter-detect":180,"./_iterators":182,"./_library":183,"./_object-create":192,"./_object-dp":193,"./_object-gopd":195,"./_object-gopn":197,"./_object-gpo":199,"./_property-desc":210,"./_redefine-all":211,"./_set-species":217,"./_species-constructor":221,"./_to-absolute-index":231,"./_to-index":232,"./_to-integer":233,"./_to-length":235,"./_to-object":236,"./_to-primitive":237,"./_typed":240,"./_typed-buffer":239,"./_uid":241,"./_wks":246,"./core.get-iterator-method":247,"./es6.array.iterator":258}],239:[function(require,module,exports){ +},{"./_an-instance":137,"./_array-copy-within":139,"./_array-fill":140,"./_array-includes":141,"./_array-methods":142,"./_classof":147,"./_ctx":154,"./_descriptors":158,"./_export":162,"./_fails":164,"./_global":170,"./_has":171,"./_hide":172,"./_is-array-iter":178,"./_is-object":181,"./_iter-detect":186,"./_iterators":188,"./_library":189,"./_object-create":198,"./_object-dp":199,"./_object-gopd":201,"./_object-gopn":203,"./_object-gpo":205,"./_property-desc":216,"./_redefine-all":217,"./_set-species":223,"./_species-constructor":227,"./_to-absolute-index":237,"./_to-index":238,"./_to-integer":239,"./_to-length":241,"./_to-object":242,"./_to-primitive":243,"./_typed":246,"./_typed-buffer":245,"./_uid":247,"./_wks":252,"./core.get-iterator-method":253,"./es6.array.iterator":264}],245:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var DESCRIPTORS = require('./_descriptors'); @@ -20406,7 +18918,7 @@ hide($DataView[PROTOTYPE], $typed.VIEW, true); exports[ARRAY_BUFFER] = $ArrayBuffer; exports[DATA_VIEW] = $DataView; -},{"./_an-instance":131,"./_array-fill":134,"./_descriptors":152,"./_fails":158,"./_global":164,"./_hide":166,"./_library":183,"./_object-dp":193,"./_object-gopn":197,"./_redefine-all":211,"./_set-to-string-tag":218,"./_to-index":232,"./_to-integer":233,"./_to-length":235,"./_typed":240}],240:[function(require,module,exports){ +},{"./_an-instance":137,"./_array-fill":140,"./_descriptors":158,"./_fails":164,"./_global":170,"./_hide":172,"./_library":189,"./_object-dp":199,"./_object-gopn":203,"./_redefine-all":217,"./_set-to-string-tag":224,"./_to-index":238,"./_to-integer":239,"./_to-length":241,"./_typed":246}],246:[function(require,module,exports){ var global = require('./_global'); var hide = require('./_hide'); var uid = require('./_uid'); @@ -20436,27 +18948,27 @@ module.exports = { VIEW: VIEW }; -},{"./_global":164,"./_hide":166,"./_uid":241}],241:[function(require,module,exports){ +},{"./_global":170,"./_hide":172,"./_uid":247}],247:[function(require,module,exports){ var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; -},{}],242:[function(require,module,exports){ +},{}],248:[function(require,module,exports){ var global = require('./_global'); var navigator = global.navigator; module.exports = navigator && navigator.userAgent || ''; -},{"./_global":164}],243:[function(require,module,exports){ +},{"./_global":170}],249:[function(require,module,exports){ var isObject = require('./_is-object'); module.exports = function (it, TYPE) { if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); return it; }; -},{"./_is-object":175}],244:[function(require,module,exports){ +},{"./_is-object":181}],250:[function(require,module,exports){ var global = require('./_global'); var core = require('./_core'); var LIBRARY = require('./_library'); @@ -20467,10 +18979,10 @@ module.exports = function (name) { if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; -},{"./_core":146,"./_global":164,"./_library":183,"./_object-dp":193,"./_wks-ext":245}],245:[function(require,module,exports){ +},{"./_core":152,"./_global":170,"./_library":189,"./_object-dp":199,"./_wks-ext":251}],251:[function(require,module,exports){ exports.f = require('./_wks'); -},{"./_wks":246}],246:[function(require,module,exports){ +},{"./_wks":252}],252:[function(require,module,exports){ var store = require('./_shared')('wks'); var uid = require('./_uid'); var Symbol = require('./_global').Symbol; @@ -20483,7 +18995,7 @@ var $exports = module.exports = function (name) { $exports.store = store; -},{"./_global":164,"./_shared":220,"./_uid":241}],247:[function(require,module,exports){ +},{"./_global":170,"./_shared":226,"./_uid":247}],253:[function(require,module,exports){ var classof = require('./_classof'); var ITERATOR = require('./_wks')('iterator'); var Iterators = require('./_iterators'); @@ -20493,7 +19005,7 @@ module.exports = require('./_core').getIteratorMethod = function (it) { || Iterators[classof(it)]; }; -},{"./_classof":141,"./_core":146,"./_iterators":182,"./_wks":246}],248:[function(require,module,exports){ +},{"./_classof":147,"./_core":152,"./_iterators":188,"./_wks":252}],254:[function(require,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = require('./_export'); @@ -20501,7 +19013,7 @@ $export($export.P, 'Array', { copyWithin: require('./_array-copy-within') }); require('./_add-to-unscopables')('copyWithin'); -},{"./_add-to-unscopables":129,"./_array-copy-within":133,"./_export":156}],249:[function(require,module,exports){ +},{"./_add-to-unscopables":135,"./_array-copy-within":139,"./_export":162}],255:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $every = require('./_array-methods')(4); @@ -20513,7 +19025,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].every, true), 'A } }); -},{"./_array-methods":136,"./_export":156,"./_strict-method":222}],250:[function(require,module,exports){ +},{"./_array-methods":142,"./_export":162,"./_strict-method":228}],256:[function(require,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = require('./_export'); @@ -20521,7 +19033,7 @@ $export($export.P, 'Array', { fill: require('./_array-fill') }); require('./_add-to-unscopables')('fill'); -},{"./_add-to-unscopables":129,"./_array-fill":134,"./_export":156}],251:[function(require,module,exports){ +},{"./_add-to-unscopables":135,"./_array-fill":140,"./_export":162}],257:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $filter = require('./_array-methods')(2); @@ -20533,7 +19045,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].filter, true), ' } }); -},{"./_array-methods":136,"./_export":156,"./_strict-method":222}],252:[function(require,module,exports){ +},{"./_array-methods":142,"./_export":162,"./_strict-method":228}],258:[function(require,module,exports){ 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = require('./_export'); @@ -20549,7 +19061,7 @@ $export($export.P + $export.F * forced, 'Array', { }); require('./_add-to-unscopables')(KEY); -},{"./_add-to-unscopables":129,"./_array-methods":136,"./_export":156}],253:[function(require,module,exports){ +},{"./_add-to-unscopables":135,"./_array-methods":142,"./_export":162}],259:[function(require,module,exports){ 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = require('./_export'); @@ -20565,7 +19077,7 @@ $export($export.P + $export.F * forced, 'Array', { }); require('./_add-to-unscopables')(KEY); -},{"./_add-to-unscopables":129,"./_array-methods":136,"./_export":156}],254:[function(require,module,exports){ +},{"./_add-to-unscopables":135,"./_array-methods":142,"./_export":162}],260:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $forEach = require('./_array-methods')(0); @@ -20578,7 +19090,7 @@ $export($export.P + $export.F * !STRICT, 'Array', { } }); -},{"./_array-methods":136,"./_export":156,"./_strict-method":222}],255:[function(require,module,exports){ +},{"./_array-methods":142,"./_export":162,"./_strict-method":228}],261:[function(require,module,exports){ 'use strict'; var ctx = require('./_ctx'); var $export = require('./_export'); @@ -20617,7 +19129,7 @@ $export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Arr } }); -},{"./_create-property":147,"./_ctx":148,"./_export":156,"./_is-array-iter":172,"./_iter-call":177,"./_iter-detect":180,"./_to-length":235,"./_to-object":236,"./core.get-iterator-method":247}],256:[function(require,module,exports){ +},{"./_create-property":153,"./_ctx":154,"./_export":162,"./_is-array-iter":178,"./_iter-call":183,"./_iter-detect":186,"./_to-length":241,"./_to-object":242,"./core.get-iterator-method":253}],262:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $indexOf = require('./_array-includes')(false); @@ -20634,13 +19146,13 @@ $export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($ } }); -},{"./_array-includes":135,"./_export":156,"./_strict-method":222}],257:[function(require,module,exports){ +},{"./_array-includes":141,"./_export":162,"./_strict-method":228}],263:[function(require,module,exports){ // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = require('./_export'); $export($export.S, 'Array', { isArray: require('./_is-array') }); -},{"./_export":156,"./_is-array":173}],258:[function(require,module,exports){ +},{"./_export":162,"./_is-array":179}],264:[function(require,module,exports){ 'use strict'; var addToUnscopables = require('./_add-to-unscopables'); var step = require('./_iter-step'); @@ -20676,7 +19188,7 @@ addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); -},{"./_add-to-unscopables":129,"./_iter-define":179,"./_iter-step":181,"./_iterators":182,"./_to-iobject":234}],259:[function(require,module,exports){ +},{"./_add-to-unscopables":135,"./_iter-define":185,"./_iter-step":187,"./_iterators":188,"./_to-iobject":240}],265:[function(require,module,exports){ 'use strict'; // 22.1.3.13 Array.prototype.join(separator) var $export = require('./_export'); @@ -20690,7 +19202,7 @@ $export($export.P + $export.F * (require('./_iobject') != Object || !require('./ } }); -},{"./_export":156,"./_iobject":171,"./_strict-method":222,"./_to-iobject":234}],260:[function(require,module,exports){ +},{"./_export":162,"./_iobject":177,"./_strict-method":228,"./_to-iobject":240}],266:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var toIObject = require('./_to-iobject'); @@ -20714,7 +19226,7 @@ $export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($ } }); -},{"./_export":156,"./_strict-method":222,"./_to-integer":233,"./_to-iobject":234,"./_to-length":235}],261:[function(require,module,exports){ +},{"./_export":162,"./_strict-method":228,"./_to-integer":239,"./_to-iobject":240,"./_to-length":241}],267:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $map = require('./_array-methods')(1); @@ -20726,7 +19238,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].map, true), 'Arr } }); -},{"./_array-methods":136,"./_export":156,"./_strict-method":222}],262:[function(require,module,exports){ +},{"./_array-methods":142,"./_export":162,"./_strict-method":228}],268:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var createProperty = require('./_create-property'); @@ -20747,7 +19259,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_create-property":147,"./_export":156,"./_fails":158}],263:[function(require,module,exports){ +},{"./_create-property":153,"./_export":162,"./_fails":164}],269:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $reduce = require('./_array-reduce'); @@ -20759,7 +19271,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].reduceRight, tru } }); -},{"./_array-reduce":137,"./_export":156,"./_strict-method":222}],264:[function(require,module,exports){ +},{"./_array-reduce":143,"./_export":162,"./_strict-method":228}],270:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $reduce = require('./_array-reduce'); @@ -20771,7 +19283,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].reduce, true), ' } }); -},{"./_array-reduce":137,"./_export":156,"./_strict-method":222}],265:[function(require,module,exports){ +},{"./_array-reduce":143,"./_export":162,"./_strict-method":228}],271:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var html = require('./_html'); @@ -20801,7 +19313,7 @@ $export($export.P + $export.F * require('./_fails')(function () { } }); -},{"./_cof":142,"./_export":156,"./_fails":158,"./_html":167,"./_to-absolute-index":231,"./_to-length":235}],266:[function(require,module,exports){ +},{"./_cof":148,"./_export":162,"./_fails":164,"./_html":173,"./_to-absolute-index":237,"./_to-length":241}],272:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $some = require('./_array-methods')(3); @@ -20813,7 +19325,7 @@ $export($export.P + $export.F * !require('./_strict-method')([].some, true), 'Ar } }); -},{"./_array-methods":136,"./_export":156,"./_strict-method":222}],267:[function(require,module,exports){ +},{"./_array-methods":142,"./_export":162,"./_strict-method":228}],273:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var aFunction = require('./_a-function'); @@ -20838,16 +19350,16 @@ $export($export.P + $export.F * (fails(function () { } }); -},{"./_a-function":127,"./_export":156,"./_fails":158,"./_strict-method":222,"./_to-object":236}],268:[function(require,module,exports){ +},{"./_a-function":133,"./_export":162,"./_fails":164,"./_strict-method":228,"./_to-object":242}],274:[function(require,module,exports){ require('./_set-species')('Array'); -},{"./_set-species":217}],269:[function(require,module,exports){ +},{"./_set-species":223}],275:[function(require,module,exports){ // 20.3.3.1 / 15.9.4.4 Date.now() var $export = require('./_export'); $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); -},{"./_export":156}],270:[function(require,module,exports){ +},{"./_export":162}],276:[function(require,module,exports){ // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var $export = require('./_export'); var toISOString = require('./_date-to-iso-string'); @@ -20857,7 +19369,7 @@ $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'D toISOString: toISOString }); -},{"./_date-to-iso-string":149,"./_export":156}],271:[function(require,module,exports){ +},{"./_date-to-iso-string":155,"./_export":162}],277:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var toObject = require('./_to-object'); @@ -20875,13 +19387,13 @@ $export($export.P + $export.F * require('./_fails')(function () { } }); -},{"./_export":156,"./_fails":158,"./_to-object":236,"./_to-primitive":237}],272:[function(require,module,exports){ +},{"./_export":162,"./_fails":164,"./_to-object":242,"./_to-primitive":243}],278:[function(require,module,exports){ var TO_PRIMITIVE = require('./_wks')('toPrimitive'); var proto = Date.prototype; if (!(TO_PRIMITIVE in proto)) require('./_hide')(proto, TO_PRIMITIVE, require('./_date-to-primitive')); -},{"./_date-to-primitive":150,"./_hide":166,"./_wks":246}],273:[function(require,module,exports){ +},{"./_date-to-primitive":156,"./_hide":172,"./_wks":252}],279:[function(require,module,exports){ var DateProto = Date.prototype; var INVALID_DATE = 'Invalid Date'; var TO_STRING = 'toString'; @@ -20895,13 +19407,13 @@ if (new Date(NaN) + '' != INVALID_DATE) { }); } -},{"./_redefine":212}],274:[function(require,module,exports){ +},{"./_redefine":218}],280:[function(require,module,exports){ // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) var $export = require('./_export'); $export($export.P, 'Function', { bind: require('./_bind') }); -},{"./_bind":140,"./_export":156}],275:[function(require,module,exports){ +},{"./_bind":146,"./_export":162}],281:[function(require,module,exports){ 'use strict'; var isObject = require('./_is-object'); var getPrototypeOf = require('./_object-gpo'); @@ -20916,7 +19428,7 @@ if (!(HAS_INSTANCE in FunctionProto)) require('./_object-dp').f(FunctionProto, H return false; } }); -},{"./_is-object":175,"./_object-dp":193,"./_object-gpo":199,"./_wks":246}],276:[function(require,module,exports){ +},{"./_is-object":181,"./_object-dp":199,"./_object-gpo":205,"./_wks":252}],282:[function(require,module,exports){ var dP = require('./_object-dp').f; var FProto = Function.prototype; var nameRE = /^\s*function ([^ (]*)/; @@ -20934,7 +19446,7 @@ NAME in FProto || require('./_descriptors') && dP(FProto, NAME, { } }); -},{"./_descriptors":152,"./_object-dp":193}],277:[function(require,module,exports){ +},{"./_descriptors":158,"./_object-dp":199}],283:[function(require,module,exports){ 'use strict'; var strong = require('./_collection-strong'); var validate = require('./_validate-collection'); @@ -20955,7 +19467,7 @@ module.exports = require('./_collection')(MAP, function (get) { } }, strong, true); -},{"./_collection":145,"./_collection-strong":143,"./_validate-collection":243}],278:[function(require,module,exports){ +},{"./_collection":151,"./_collection-strong":149,"./_validate-collection":249}],284:[function(require,module,exports){ // 20.2.2.3 Math.acosh(x) var $export = require('./_export'); var log1p = require('./_math-log1p'); @@ -20975,7 +19487,7 @@ $export($export.S + $export.F * !($acosh } }); -},{"./_export":156,"./_math-log1p":186}],279:[function(require,module,exports){ +},{"./_export":162,"./_math-log1p":192}],285:[function(require,module,exports){ // 20.2.2.5 Math.asinh(x) var $export = require('./_export'); var $asinh = Math.asinh; @@ -20987,7 +19499,7 @@ function asinh(x) { // Tor Browser bug: Math.asinh(0) -> -0 $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); -},{"./_export":156}],280:[function(require,module,exports){ +},{"./_export":162}],286:[function(require,module,exports){ // 20.2.2.7 Math.atanh(x) var $export = require('./_export'); var $atanh = Math.atanh; @@ -20999,7 +19511,7 @@ $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { } }); -},{"./_export":156}],281:[function(require,module,exports){ +},{"./_export":162}],287:[function(require,module,exports){ // 20.2.2.9 Math.cbrt(x) var $export = require('./_export'); var sign = require('./_math-sign'); @@ -21010,7 +19522,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":156,"./_math-sign":187}],282:[function(require,module,exports){ +},{"./_export":162,"./_math-sign":193}],288:[function(require,module,exports){ // 20.2.2.11 Math.clz32(x) var $export = require('./_export'); @@ -21020,7 +19532,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":156}],283:[function(require,module,exports){ +},{"./_export":162}],289:[function(require,module,exports){ // 20.2.2.12 Math.cosh(x) var $export = require('./_export'); var exp = Math.exp; @@ -21031,20 +19543,20 @@ $export($export.S, 'Math', { } }); -},{"./_export":156}],284:[function(require,module,exports){ +},{"./_export":162}],290:[function(require,module,exports){ // 20.2.2.14 Math.expm1(x) var $export = require('./_export'); var $expm1 = require('./_math-expm1'); $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); -},{"./_export":156,"./_math-expm1":184}],285:[function(require,module,exports){ +},{"./_export":162,"./_math-expm1":190}],291:[function(require,module,exports){ // 20.2.2.16 Math.fround(x) var $export = require('./_export'); $export($export.S, 'Math', { fround: require('./_math-fround') }); -},{"./_export":156,"./_math-fround":185}],286:[function(require,module,exports){ +},{"./_export":162,"./_math-fround":191}],292:[function(require,module,exports){ // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = require('./_export'); var abs = Math.abs; @@ -21071,7 +19583,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":156}],287:[function(require,module,exports){ +},{"./_export":162}],293:[function(require,module,exports){ // 20.2.2.18 Math.imul(x, y) var $export = require('./_export'); var $imul = Math.imul; @@ -21090,7 +19602,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_export":156,"./_fails":158}],288:[function(require,module,exports){ +},{"./_export":162,"./_fails":164}],294:[function(require,module,exports){ // 20.2.2.21 Math.log10(x) var $export = require('./_export'); @@ -21100,13 +19612,13 @@ $export($export.S, 'Math', { } }); -},{"./_export":156}],289:[function(require,module,exports){ +},{"./_export":162}],295:[function(require,module,exports){ // 20.2.2.20 Math.log1p(x) var $export = require('./_export'); $export($export.S, 'Math', { log1p: require('./_math-log1p') }); -},{"./_export":156,"./_math-log1p":186}],290:[function(require,module,exports){ +},{"./_export":162,"./_math-log1p":192}],296:[function(require,module,exports){ // 20.2.2.22 Math.log2(x) var $export = require('./_export'); @@ -21116,13 +19628,13 @@ $export($export.S, 'Math', { } }); -},{"./_export":156}],291:[function(require,module,exports){ +},{"./_export":162}],297:[function(require,module,exports){ // 20.2.2.28 Math.sign(x) var $export = require('./_export'); $export($export.S, 'Math', { sign: require('./_math-sign') }); -},{"./_export":156,"./_math-sign":187}],292:[function(require,module,exports){ +},{"./_export":162,"./_math-sign":193}],298:[function(require,module,exports){ // 20.2.2.30 Math.sinh(x) var $export = require('./_export'); var expm1 = require('./_math-expm1'); @@ -21139,7 +19651,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_export":156,"./_fails":158,"./_math-expm1":184}],293:[function(require,module,exports){ +},{"./_export":162,"./_fails":164,"./_math-expm1":190}],299:[function(require,module,exports){ // 20.2.2.33 Math.tanh(x) var $export = require('./_export'); var expm1 = require('./_math-expm1'); @@ -21153,7 +19665,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":156,"./_math-expm1":184}],294:[function(require,module,exports){ +},{"./_export":162,"./_math-expm1":190}],300:[function(require,module,exports){ // 20.2.2.34 Math.trunc(x) var $export = require('./_export'); @@ -21163,7 +19675,7 @@ $export($export.S, 'Math', { } }); -},{"./_export":156}],295:[function(require,module,exports){ +},{"./_export":162}],301:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var has = require('./_has'); @@ -21234,13 +19746,13 @@ if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { require('./_redefine')(global, NUMBER, $Number); } -},{"./_cof":142,"./_descriptors":152,"./_fails":158,"./_global":164,"./_has":165,"./_inherit-if-required":169,"./_object-create":192,"./_object-dp":193,"./_object-gopd":195,"./_object-gopn":197,"./_redefine":212,"./_string-trim":228,"./_to-primitive":237}],296:[function(require,module,exports){ +},{"./_cof":148,"./_descriptors":158,"./_fails":164,"./_global":170,"./_has":171,"./_inherit-if-required":175,"./_object-create":198,"./_object-dp":199,"./_object-gopd":201,"./_object-gopn":203,"./_redefine":218,"./_string-trim":234,"./_to-primitive":243}],302:[function(require,module,exports){ // 20.1.2.1 Number.EPSILON var $export = require('./_export'); $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); -},{"./_export":156}],297:[function(require,module,exports){ +},{"./_export":162}],303:[function(require,module,exports){ // 20.1.2.2 Number.isFinite(number) var $export = require('./_export'); var _isFinite = require('./_global').isFinite; @@ -21251,13 +19763,13 @@ $export($export.S, 'Number', { } }); -},{"./_export":156,"./_global":164}],298:[function(require,module,exports){ +},{"./_export":162,"./_global":170}],304:[function(require,module,exports){ // 20.1.2.3 Number.isInteger(number) var $export = require('./_export'); $export($export.S, 'Number', { isInteger: require('./_is-integer') }); -},{"./_export":156,"./_is-integer":174}],299:[function(require,module,exports){ +},{"./_export":162,"./_is-integer":180}],305:[function(require,module,exports){ // 20.1.2.4 Number.isNaN(number) var $export = require('./_export'); @@ -21268,7 +19780,7 @@ $export($export.S, 'Number', { } }); -},{"./_export":156}],300:[function(require,module,exports){ +},{"./_export":162}],306:[function(require,module,exports){ // 20.1.2.5 Number.isSafeInteger(number) var $export = require('./_export'); var isInteger = require('./_is-integer'); @@ -21280,31 +19792,31 @@ $export($export.S, 'Number', { } }); -},{"./_export":156,"./_is-integer":174}],301:[function(require,module,exports){ +},{"./_export":162,"./_is-integer":180}],307:[function(require,module,exports){ // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = require('./_export'); $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); -},{"./_export":156}],302:[function(require,module,exports){ +},{"./_export":162}],308:[function(require,module,exports){ // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = require('./_export'); $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); -},{"./_export":156}],303:[function(require,module,exports){ +},{"./_export":162}],309:[function(require,module,exports){ var $export = require('./_export'); var $parseFloat = require('./_parse-float'); // 20.1.2.12 Number.parseFloat(string) $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); -},{"./_export":156,"./_parse-float":206}],304:[function(require,module,exports){ +},{"./_export":162,"./_parse-float":212}],310:[function(require,module,exports){ var $export = require('./_export'); var $parseInt = require('./_parse-int'); // 20.1.2.13 Number.parseInt(string, radix) $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); -},{"./_export":156,"./_parse-int":207}],305:[function(require,module,exports){ +},{"./_export":162,"./_parse-int":213}],311:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var toInteger = require('./_to-integer'); @@ -21420,7 +19932,7 @@ $export($export.P + $export.F * (!!$toFixed && ( } }); -},{"./_a-number-value":128,"./_export":156,"./_fails":158,"./_string-repeat":227,"./_to-integer":233}],306:[function(require,module,exports){ +},{"./_a-number-value":134,"./_export":162,"./_fails":164,"./_string-repeat":233,"./_to-integer":239}],312:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $fails = require('./_fails'); @@ -21440,28 +19952,28 @@ $export($export.P + $export.F * ($fails(function () { } }); -},{"./_a-number-value":128,"./_export":156,"./_fails":158}],307:[function(require,module,exports){ +},{"./_a-number-value":134,"./_export":162,"./_fails":164}],313:[function(require,module,exports){ // 19.1.3.1 Object.assign(target, source) var $export = require('./_export'); $export($export.S + $export.F, 'Object', { assign: require('./_object-assign') }); -},{"./_export":156,"./_object-assign":191}],308:[function(require,module,exports){ +},{"./_export":162,"./_object-assign":197}],314:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: require('./_object-create') }); -},{"./_export":156,"./_object-create":192}],309:[function(require,module,exports){ +},{"./_export":162,"./_object-create":198}],315:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) $export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperties: require('./_object-dps') }); -},{"./_descriptors":152,"./_export":156,"./_object-dps":194}],310:[function(require,module,exports){ +},{"./_descriptors":158,"./_export":162,"./_object-dps":200}],316:[function(require,module,exports){ var $export = require('./_export'); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperty: require('./_object-dp').f }); -},{"./_descriptors":152,"./_export":156,"./_object-dp":193}],311:[function(require,module,exports){ +},{"./_descriptors":158,"./_export":162,"./_object-dp":199}],317:[function(require,module,exports){ // 19.1.2.5 Object.freeze(O) var isObject = require('./_is-object'); var meta = require('./_meta').onFreeze; @@ -21472,7 +19984,7 @@ require('./_object-sap')('freeze', function ($freeze) { }; }); -},{"./_is-object":175,"./_meta":188,"./_object-sap":203}],312:[function(require,module,exports){ +},{"./_is-object":181,"./_meta":194,"./_object-sap":209}],318:[function(require,module,exports){ // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = require('./_to-iobject'); var $getOwnPropertyDescriptor = require('./_object-gopd').f; @@ -21483,13 +19995,13 @@ require('./_object-sap')('getOwnPropertyDescriptor', function () { }; }); -},{"./_object-gopd":195,"./_object-sap":203,"./_to-iobject":234}],313:[function(require,module,exports){ +},{"./_object-gopd":201,"./_object-sap":209,"./_to-iobject":240}],319:[function(require,module,exports){ // 19.1.2.7 Object.getOwnPropertyNames(O) require('./_object-sap')('getOwnPropertyNames', function () { return require('./_object-gopn-ext').f; }); -},{"./_object-gopn-ext":196,"./_object-sap":203}],314:[function(require,module,exports){ +},{"./_object-gopn-ext":202,"./_object-sap":209}],320:[function(require,module,exports){ // 19.1.2.9 Object.getPrototypeOf(O) var toObject = require('./_to-object'); var $getPrototypeOf = require('./_object-gpo'); @@ -21500,7 +20012,7 @@ require('./_object-sap')('getPrototypeOf', function () { }; }); -},{"./_object-gpo":199,"./_object-sap":203,"./_to-object":236}],315:[function(require,module,exports){ +},{"./_object-gpo":205,"./_object-sap":209,"./_to-object":242}],321:[function(require,module,exports){ // 19.1.2.11 Object.isExtensible(O) var isObject = require('./_is-object'); @@ -21510,7 +20022,7 @@ require('./_object-sap')('isExtensible', function ($isExtensible) { }; }); -},{"./_is-object":175,"./_object-sap":203}],316:[function(require,module,exports){ +},{"./_is-object":181,"./_object-sap":209}],322:[function(require,module,exports){ // 19.1.2.12 Object.isFrozen(O) var isObject = require('./_is-object'); @@ -21520,7 +20032,7 @@ require('./_object-sap')('isFrozen', function ($isFrozen) { }; }); -},{"./_is-object":175,"./_object-sap":203}],317:[function(require,module,exports){ +},{"./_is-object":181,"./_object-sap":209}],323:[function(require,module,exports){ // 19.1.2.13 Object.isSealed(O) var isObject = require('./_is-object'); @@ -21530,12 +20042,12 @@ require('./_object-sap')('isSealed', function ($isSealed) { }; }); -},{"./_is-object":175,"./_object-sap":203}],318:[function(require,module,exports){ +},{"./_is-object":181,"./_object-sap":209}],324:[function(require,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $export = require('./_export'); $export($export.S, 'Object', { is: require('./_same-value') }); -},{"./_export":156,"./_same-value":215}],319:[function(require,module,exports){ +},{"./_export":162,"./_same-value":221}],325:[function(require,module,exports){ // 19.1.2.14 Object.keys(O) var toObject = require('./_to-object'); var $keys = require('./_object-keys'); @@ -21546,7 +20058,7 @@ require('./_object-sap')('keys', function () { }; }); -},{"./_object-keys":201,"./_object-sap":203,"./_to-object":236}],320:[function(require,module,exports){ +},{"./_object-keys":207,"./_object-sap":209,"./_to-object":242}],326:[function(require,module,exports){ // 19.1.2.15 Object.preventExtensions(O) var isObject = require('./_is-object'); var meta = require('./_meta').onFreeze; @@ -21557,7 +20069,7 @@ require('./_object-sap')('preventExtensions', function ($preventExtensions) { }; }); -},{"./_is-object":175,"./_meta":188,"./_object-sap":203}],321:[function(require,module,exports){ +},{"./_is-object":181,"./_meta":194,"./_object-sap":209}],327:[function(require,module,exports){ // 19.1.2.17 Object.seal(O) var isObject = require('./_is-object'); var meta = require('./_meta').onFreeze; @@ -21568,12 +20080,12 @@ require('./_object-sap')('seal', function ($seal) { }; }); -},{"./_is-object":175,"./_meta":188,"./_object-sap":203}],322:[function(require,module,exports){ +},{"./_is-object":181,"./_meta":194,"./_object-sap":209}],328:[function(require,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = require('./_export'); $export($export.S, 'Object', { setPrototypeOf: require('./_set-proto').set }); -},{"./_export":156,"./_set-proto":216}],323:[function(require,module,exports){ +},{"./_export":162,"./_set-proto":222}],329:[function(require,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var classof = require('./_classof'); @@ -21585,19 +20097,19 @@ if (test + '' != '[object z]') { }, true); } -},{"./_classof":141,"./_redefine":212,"./_wks":246}],324:[function(require,module,exports){ +},{"./_classof":147,"./_redefine":218,"./_wks":252}],330:[function(require,module,exports){ var $export = require('./_export'); var $parseFloat = require('./_parse-float'); // 18.2.4 parseFloat(string) $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); -},{"./_export":156,"./_parse-float":206}],325:[function(require,module,exports){ +},{"./_export":162,"./_parse-float":212}],331:[function(require,module,exports){ var $export = require('./_export'); var $parseInt = require('./_parse-int'); // 18.2.5 parseInt(string, radix) $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); -},{"./_export":156,"./_parse-int":207}],326:[function(require,module,exports){ +},{"./_export":162,"./_parse-int":213}],332:[function(require,module,exports){ 'use strict'; var LIBRARY = require('./_library'); var global = require('./_global'); @@ -21885,7 +20397,7 @@ $export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(functi } }); -},{"./_a-function":127,"./_an-instance":131,"./_classof":141,"./_core":146,"./_ctx":148,"./_export":156,"./_for-of":162,"./_global":164,"./_is-object":175,"./_iter-detect":180,"./_library":183,"./_microtask":189,"./_new-promise-capability":190,"./_perform":208,"./_promise-resolve":209,"./_redefine-all":211,"./_set-species":217,"./_set-to-string-tag":218,"./_species-constructor":221,"./_task":230,"./_user-agent":242,"./_wks":246}],327:[function(require,module,exports){ +},{"./_a-function":133,"./_an-instance":137,"./_classof":147,"./_core":152,"./_ctx":154,"./_export":162,"./_for-of":168,"./_global":170,"./_is-object":181,"./_iter-detect":186,"./_library":189,"./_microtask":195,"./_new-promise-capability":196,"./_perform":214,"./_promise-resolve":215,"./_redefine-all":217,"./_set-species":223,"./_set-to-string-tag":224,"./_species-constructor":227,"./_task":236,"./_user-agent":248,"./_wks":252}],333:[function(require,module,exports){ // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = require('./_export'); var aFunction = require('./_a-function'); @@ -21903,7 +20415,7 @@ $export($export.S + $export.F * !require('./_fails')(function () { } }); -},{"./_a-function":127,"./_an-object":132,"./_export":156,"./_fails":158,"./_global":164}],328:[function(require,module,exports){ +},{"./_a-function":133,"./_an-object":138,"./_export":162,"./_fails":164,"./_global":170}],334:[function(require,module,exports){ // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $export = require('./_export'); var create = require('./_object-create'); @@ -21952,7 +20464,7 @@ $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { } }); -},{"./_a-function":127,"./_an-object":132,"./_bind":140,"./_export":156,"./_fails":158,"./_global":164,"./_is-object":175,"./_object-create":192}],329:[function(require,module,exports){ +},{"./_a-function":133,"./_an-object":138,"./_bind":146,"./_export":162,"./_fails":164,"./_global":170,"./_is-object":181,"./_object-create":198}],335:[function(require,module,exports){ // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var dP = require('./_object-dp'); var $export = require('./_export'); @@ -21977,7 +20489,7 @@ $export($export.S + $export.F * require('./_fails')(function () { } }); -},{"./_an-object":132,"./_export":156,"./_fails":158,"./_object-dp":193,"./_to-primitive":237}],330:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_fails":164,"./_object-dp":199,"./_to-primitive":243}],336:[function(require,module,exports){ // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = require('./_export'); var gOPD = require('./_object-gopd').f; @@ -21990,7 +20502,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":132,"./_export":156,"./_object-gopd":195}],331:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_object-gopd":201}],337:[function(require,module,exports){ 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = require('./_export'); @@ -22018,7 +20530,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":132,"./_export":156,"./_iter-create":178}],332:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_iter-create":184}],338:[function(require,module,exports){ // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var gOPD = require('./_object-gopd'); var $export = require('./_export'); @@ -22030,7 +20542,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":132,"./_export":156,"./_object-gopd":195}],333:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_object-gopd":201}],339:[function(require,module,exports){ // 26.1.8 Reflect.getPrototypeOf(target) var $export = require('./_export'); var getProto = require('./_object-gpo'); @@ -22042,7 +20554,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":132,"./_export":156,"./_object-gpo":199}],334:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_object-gpo":205}],340:[function(require,module,exports){ // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var gOPD = require('./_object-gopd'); var getPrototypeOf = require('./_object-gpo'); @@ -22065,7 +20577,7 @@ function get(target, propertyKey /* , receiver */) { $export($export.S, 'Reflect', { get: get }); -},{"./_an-object":132,"./_export":156,"./_has":165,"./_is-object":175,"./_object-gopd":195,"./_object-gpo":199}],335:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_has":171,"./_is-object":181,"./_object-gopd":201,"./_object-gpo":205}],341:[function(require,module,exports){ // 26.1.9 Reflect.has(target, propertyKey) var $export = require('./_export'); @@ -22075,7 +20587,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_export":156}],336:[function(require,module,exports){ +},{"./_export":162}],342:[function(require,module,exports){ // 26.1.10 Reflect.isExtensible(target) var $export = require('./_export'); var anObject = require('./_an-object'); @@ -22088,13 +20600,13 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":132,"./_export":156}],337:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162}],343:[function(require,module,exports){ // 26.1.11 Reflect.ownKeys(target) var $export = require('./_export'); $export($export.S, 'Reflect', { ownKeys: require('./_own-keys') }); -},{"./_export":156,"./_own-keys":205}],338:[function(require,module,exports){ +},{"./_export":162,"./_own-keys":211}],344:[function(require,module,exports){ // 26.1.12 Reflect.preventExtensions(target) var $export = require('./_export'); var anObject = require('./_an-object'); @@ -22112,7 +20624,7 @@ $export($export.S, 'Reflect', { } }); -},{"./_an-object":132,"./_export":156}],339:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162}],345:[function(require,module,exports){ // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = require('./_export'); var setProto = require('./_set-proto'); @@ -22129,7 +20641,7 @@ if (setProto) $export($export.S, 'Reflect', { } }); -},{"./_export":156,"./_set-proto":216}],340:[function(require,module,exports){ +},{"./_export":162,"./_set-proto":222}],346:[function(require,module,exports){ // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var dP = require('./_object-dp'); var gOPD = require('./_object-gopd'); @@ -22164,7 +20676,7 @@ function set(target, propertyKey, V /* , receiver */) { $export($export.S, 'Reflect', { set: set }); -},{"./_an-object":132,"./_export":156,"./_has":165,"./_is-object":175,"./_object-dp":193,"./_object-gopd":195,"./_object-gpo":199,"./_property-desc":210}],341:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_has":171,"./_is-object":181,"./_object-dp":199,"./_object-gopd":201,"./_object-gpo":205,"./_property-desc":216}],347:[function(require,module,exports){ var global = require('./_global'); var inheritIfRequired = require('./_inherit-if-required'); var dP = require('./_object-dp').f; @@ -22209,7 +20721,7 @@ if (require('./_descriptors') && (!CORRECT_NEW || require('./_fails')(function ( require('./_set-species')('RegExp'); -},{"./_descriptors":152,"./_fails":158,"./_flags":160,"./_global":164,"./_inherit-if-required":169,"./_is-regexp":176,"./_object-dp":193,"./_object-gopn":197,"./_redefine":212,"./_set-species":217,"./_wks":246}],342:[function(require,module,exports){ +},{"./_descriptors":158,"./_fails":164,"./_flags":166,"./_global":170,"./_inherit-if-required":175,"./_is-regexp":182,"./_object-dp":199,"./_object-gopn":203,"./_redefine":218,"./_set-species":223,"./_wks":252}],348:[function(require,module,exports){ 'use strict'; var regexpExec = require('./_regexp-exec'); require('./_export')({ @@ -22220,14 +20732,14 @@ require('./_export')({ exec: regexpExec }); -},{"./_export":156,"./_regexp-exec":214}],343:[function(require,module,exports){ +},{"./_export":162,"./_regexp-exec":220}],349:[function(require,module,exports){ // 21.2.5.3 get RegExp.prototype.flags() if (require('./_descriptors') && /./g.flags != 'g') require('./_object-dp').f(RegExp.prototype, 'flags', { configurable: true, get: require('./_flags') }); -},{"./_descriptors":152,"./_flags":160,"./_object-dp":193}],344:[function(require,module,exports){ +},{"./_descriptors":158,"./_flags":166,"./_object-dp":199}],350:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); @@ -22269,7 +20781,7 @@ require('./_fix-re-wks')('match', 1, function (defined, MATCH, $match, maybeCall ]; }); -},{"./_advance-string-index":130,"./_an-object":132,"./_fix-re-wks":159,"./_regexp-exec-abstract":213,"./_to-length":235}],345:[function(require,module,exports){ +},{"./_advance-string-index":136,"./_an-object":138,"./_fix-re-wks":165,"./_regexp-exec-abstract":219,"./_to-length":241}],351:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); @@ -22389,7 +20901,7 @@ require('./_fix-re-wks')('replace', 2, function (defined, REPLACE, $replace, may } }); -},{"./_advance-string-index":130,"./_an-object":132,"./_fix-re-wks":159,"./_regexp-exec-abstract":213,"./_to-integer":233,"./_to-length":235,"./_to-object":236}],346:[function(require,module,exports){ +},{"./_advance-string-index":136,"./_an-object":138,"./_fix-re-wks":165,"./_regexp-exec-abstract":219,"./_to-integer":239,"./_to-length":241,"./_to-object":242}],352:[function(require,module,exports){ 'use strict'; var anObject = require('./_an-object'); @@ -22422,7 +20934,7 @@ require('./_fix-re-wks')('search', 1, function (defined, SEARCH, $search, maybeC ]; }); -},{"./_an-object":132,"./_fix-re-wks":159,"./_regexp-exec-abstract":213,"./_same-value":215}],347:[function(require,module,exports){ +},{"./_an-object":138,"./_fix-re-wks":165,"./_regexp-exec-abstract":219,"./_same-value":221}],353:[function(require,module,exports){ 'use strict'; var isRegExp = require('./_is-regexp'); @@ -22558,7 +21070,7 @@ require('./_fix-re-wks')('split', 2, function (defined, SPLIT, $split, maybeCall ]; }); -},{"./_advance-string-index":130,"./_an-object":132,"./_fails":158,"./_fix-re-wks":159,"./_is-regexp":176,"./_regexp-exec":214,"./_regexp-exec-abstract":213,"./_species-constructor":221,"./_to-length":235}],348:[function(require,module,exports){ +},{"./_advance-string-index":136,"./_an-object":138,"./_fails":164,"./_fix-re-wks":165,"./_is-regexp":182,"./_regexp-exec":220,"./_regexp-exec-abstract":219,"./_species-constructor":227,"./_to-length":241}],354:[function(require,module,exports){ 'use strict'; require('./es6.regexp.flags'); var anObject = require('./_an-object'); @@ -22585,7 +21097,7 @@ if (require('./_fails')(function () { return $toString.call({ source: 'a', flags }); } -},{"./_an-object":132,"./_descriptors":152,"./_fails":158,"./_flags":160,"./_redefine":212,"./es6.regexp.flags":343}],349:[function(require,module,exports){ +},{"./_an-object":138,"./_descriptors":158,"./_fails":164,"./_flags":166,"./_redefine":218,"./es6.regexp.flags":349}],355:[function(require,module,exports){ 'use strict'; var strong = require('./_collection-strong'); var validate = require('./_validate-collection'); @@ -22601,7 +21113,7 @@ module.exports = require('./_collection')(SET, function (get) { } }, strong); -},{"./_collection":145,"./_collection-strong":143,"./_validate-collection":243}],350:[function(require,module,exports){ +},{"./_collection":151,"./_collection-strong":149,"./_validate-collection":249}],356:[function(require,module,exports){ 'use strict'; // B.2.3.2 String.prototype.anchor(name) require('./_string-html')('anchor', function (createHTML) { @@ -22610,7 +21122,7 @@ require('./_string-html')('anchor', function (createHTML) { }; }); -},{"./_string-html":225}],351:[function(require,module,exports){ +},{"./_string-html":231}],357:[function(require,module,exports){ 'use strict'; // B.2.3.3 String.prototype.big() require('./_string-html')('big', function (createHTML) { @@ -22619,7 +21131,7 @@ require('./_string-html')('big', function (createHTML) { }; }); -},{"./_string-html":225}],352:[function(require,module,exports){ +},{"./_string-html":231}],358:[function(require,module,exports){ 'use strict'; // B.2.3.4 String.prototype.blink() require('./_string-html')('blink', function (createHTML) { @@ -22628,7 +21140,7 @@ require('./_string-html')('blink', function (createHTML) { }; }); -},{"./_string-html":225}],353:[function(require,module,exports){ +},{"./_string-html":231}],359:[function(require,module,exports){ 'use strict'; // B.2.3.5 String.prototype.bold() require('./_string-html')('bold', function (createHTML) { @@ -22637,7 +21149,7 @@ require('./_string-html')('bold', function (createHTML) { }; }); -},{"./_string-html":225}],354:[function(require,module,exports){ +},{"./_string-html":231}],360:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $at = require('./_string-at')(false); @@ -22648,7 +21160,7 @@ $export($export.P, 'String', { } }); -},{"./_export":156,"./_string-at":223}],355:[function(require,module,exports){ +},{"./_export":162,"./_string-at":229}],361:[function(require,module,exports){ // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = require('./_export'); @@ -22670,7 +21182,7 @@ $export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'Strin } }); -},{"./_export":156,"./_fails-is-regexp":157,"./_string-context":224,"./_to-length":235}],356:[function(require,module,exports){ +},{"./_export":162,"./_fails-is-regexp":163,"./_string-context":230,"./_to-length":241}],362:[function(require,module,exports){ 'use strict'; // B.2.3.6 String.prototype.fixed() require('./_string-html')('fixed', function (createHTML) { @@ -22679,7 +21191,7 @@ require('./_string-html')('fixed', function (createHTML) { }; }); -},{"./_string-html":225}],357:[function(require,module,exports){ +},{"./_string-html":231}],363:[function(require,module,exports){ 'use strict'; // B.2.3.7 String.prototype.fontcolor(color) require('./_string-html')('fontcolor', function (createHTML) { @@ -22688,7 +21200,7 @@ require('./_string-html')('fontcolor', function (createHTML) { }; }); -},{"./_string-html":225}],358:[function(require,module,exports){ +},{"./_string-html":231}],364:[function(require,module,exports){ 'use strict'; // B.2.3.8 String.prototype.fontsize(size) require('./_string-html')('fontsize', function (createHTML) { @@ -22697,7 +21209,7 @@ require('./_string-html')('fontsize', function (createHTML) { }; }); -},{"./_string-html":225}],359:[function(require,module,exports){ +},{"./_string-html":231}],365:[function(require,module,exports){ var $export = require('./_export'); var toAbsoluteIndex = require('./_to-absolute-index'); var fromCharCode = String.fromCharCode; @@ -22722,7 +21234,7 @@ $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1) } }); -},{"./_export":156,"./_to-absolute-index":231}],360:[function(require,module,exports){ +},{"./_export":162,"./_to-absolute-index":237}],366:[function(require,module,exports){ // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = require('./_export'); @@ -22736,7 +21248,7 @@ $export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String } }); -},{"./_export":156,"./_fails-is-regexp":157,"./_string-context":224}],361:[function(require,module,exports){ +},{"./_export":162,"./_fails-is-regexp":163,"./_string-context":230}],367:[function(require,module,exports){ 'use strict'; // B.2.3.9 String.prototype.italics() require('./_string-html')('italics', function (createHTML) { @@ -22745,7 +21257,7 @@ require('./_string-html')('italics', function (createHTML) { }; }); -},{"./_string-html":225}],362:[function(require,module,exports){ +},{"./_string-html":231}],368:[function(require,module,exports){ 'use strict'; var $at = require('./_string-at')(true); @@ -22764,7 +21276,7 @@ require('./_iter-define')(String, 'String', function (iterated) { return { value: point, done: false }; }); -},{"./_iter-define":179,"./_string-at":223}],363:[function(require,module,exports){ +},{"./_iter-define":185,"./_string-at":229}],369:[function(require,module,exports){ 'use strict'; // B.2.3.10 String.prototype.link(url) require('./_string-html')('link', function (createHTML) { @@ -22773,7 +21285,7 @@ require('./_string-html')('link', function (createHTML) { }; }); -},{"./_string-html":225}],364:[function(require,module,exports){ +},{"./_string-html":231}],370:[function(require,module,exports){ var $export = require('./_export'); var toIObject = require('./_to-iobject'); var toLength = require('./_to-length'); @@ -22793,7 +21305,7 @@ $export($export.S, 'String', { } }); -},{"./_export":156,"./_to-iobject":234,"./_to-length":235}],365:[function(require,module,exports){ +},{"./_export":162,"./_to-iobject":240,"./_to-length":241}],371:[function(require,module,exports){ var $export = require('./_export'); $export($export.P, 'String', { @@ -22801,7 +21313,7 @@ $export($export.P, 'String', { repeat: require('./_string-repeat') }); -},{"./_export":156,"./_string-repeat":227}],366:[function(require,module,exports){ +},{"./_export":162,"./_string-repeat":233}],372:[function(require,module,exports){ 'use strict'; // B.2.3.11 String.prototype.small() require('./_string-html')('small', function (createHTML) { @@ -22810,7 +21322,7 @@ require('./_string-html')('small', function (createHTML) { }; }); -},{"./_string-html":225}],367:[function(require,module,exports){ +},{"./_string-html":231}],373:[function(require,module,exports){ // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = require('./_export'); @@ -22830,7 +21342,7 @@ $export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'Str } }); -},{"./_export":156,"./_fails-is-regexp":157,"./_string-context":224,"./_to-length":235}],368:[function(require,module,exports){ +},{"./_export":162,"./_fails-is-regexp":163,"./_string-context":230,"./_to-length":241}],374:[function(require,module,exports){ 'use strict'; // B.2.3.12 String.prototype.strike() require('./_string-html')('strike', function (createHTML) { @@ -22839,7 +21351,7 @@ require('./_string-html')('strike', function (createHTML) { }; }); -},{"./_string-html":225}],369:[function(require,module,exports){ +},{"./_string-html":231}],375:[function(require,module,exports){ 'use strict'; // B.2.3.13 String.prototype.sub() require('./_string-html')('sub', function (createHTML) { @@ -22848,7 +21360,7 @@ require('./_string-html')('sub', function (createHTML) { }; }); -},{"./_string-html":225}],370:[function(require,module,exports){ +},{"./_string-html":231}],376:[function(require,module,exports){ 'use strict'; // B.2.3.14 String.prototype.sup() require('./_string-html')('sup', function (createHTML) { @@ -22857,7 +21369,7 @@ require('./_string-html')('sup', function (createHTML) { }; }); -},{"./_string-html":225}],371:[function(require,module,exports){ +},{"./_string-html":231}],377:[function(require,module,exports){ 'use strict'; // 21.1.3.25 String.prototype.trim() require('./_string-trim')('trim', function ($trim) { @@ -22866,7 +21378,7 @@ require('./_string-trim')('trim', function ($trim) { }; }); -},{"./_string-trim":228}],372:[function(require,module,exports){ +},{"./_string-trim":234}],378:[function(require,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var global = require('./_global'); @@ -23114,7 +21626,7 @@ setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); -},{"./_an-object":132,"./_descriptors":152,"./_enum-keys":155,"./_export":156,"./_fails":158,"./_global":164,"./_has":165,"./_hide":166,"./_is-array":173,"./_is-object":175,"./_library":183,"./_meta":188,"./_object-create":192,"./_object-dp":193,"./_object-gopd":195,"./_object-gopn":197,"./_object-gopn-ext":196,"./_object-gops":198,"./_object-keys":201,"./_object-pie":202,"./_property-desc":210,"./_redefine":212,"./_set-to-string-tag":218,"./_shared":220,"./_to-iobject":234,"./_to-object":236,"./_to-primitive":237,"./_uid":241,"./_wks":246,"./_wks-define":244,"./_wks-ext":245}],373:[function(require,module,exports){ +},{"./_an-object":138,"./_descriptors":158,"./_enum-keys":161,"./_export":162,"./_fails":164,"./_global":170,"./_has":171,"./_hide":172,"./_is-array":179,"./_is-object":181,"./_library":189,"./_meta":194,"./_object-create":198,"./_object-dp":199,"./_object-gopd":201,"./_object-gopn":203,"./_object-gopn-ext":202,"./_object-gops":204,"./_object-keys":207,"./_object-pie":208,"./_property-desc":216,"./_redefine":218,"./_set-to-string-tag":224,"./_shared":226,"./_to-iobject":240,"./_to-object":242,"./_to-primitive":243,"./_uid":247,"./_wks":252,"./_wks-define":250,"./_wks-ext":251}],379:[function(require,module,exports){ 'use strict'; var $export = require('./_export'); var $typed = require('./_typed'); @@ -23162,76 +21674,76 @@ $export($export.P + $export.U + $export.F * require('./_fails')(function () { require('./_set-species')(ARRAY_BUFFER); -},{"./_an-object":132,"./_export":156,"./_fails":158,"./_global":164,"./_is-object":175,"./_set-species":217,"./_species-constructor":221,"./_to-absolute-index":231,"./_to-length":235,"./_typed":240,"./_typed-buffer":239}],374:[function(require,module,exports){ +},{"./_an-object":138,"./_export":162,"./_fails":164,"./_global":170,"./_is-object":181,"./_set-species":223,"./_species-constructor":227,"./_to-absolute-index":237,"./_to-length":241,"./_typed":246,"./_typed-buffer":245}],380:[function(require,module,exports){ var $export = require('./_export'); $export($export.G + $export.W + $export.F * !require('./_typed').ABV, { DataView: require('./_typed-buffer').DataView }); -},{"./_export":156,"./_typed":240,"./_typed-buffer":239}],375:[function(require,module,exports){ +},{"./_export":162,"./_typed":246,"./_typed-buffer":245}],381:[function(require,module,exports){ require('./_typed-array')('Float32', 4, function (init) { return function Float32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],376:[function(require,module,exports){ +},{"./_typed-array":244}],382:[function(require,module,exports){ require('./_typed-array')('Float64', 8, function (init) { return function Float64Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],377:[function(require,module,exports){ +},{"./_typed-array":244}],383:[function(require,module,exports){ require('./_typed-array')('Int16', 2, function (init) { return function Int16Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],378:[function(require,module,exports){ +},{"./_typed-array":244}],384:[function(require,module,exports){ require('./_typed-array')('Int32', 4, function (init) { return function Int32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],379:[function(require,module,exports){ +},{"./_typed-array":244}],385:[function(require,module,exports){ require('./_typed-array')('Int8', 1, function (init) { return function Int8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],380:[function(require,module,exports){ +},{"./_typed-array":244}],386:[function(require,module,exports){ require('./_typed-array')('Uint16', 2, function (init) { return function Uint16Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],381:[function(require,module,exports){ +},{"./_typed-array":244}],387:[function(require,module,exports){ require('./_typed-array')('Uint32', 4, function (init) { return function Uint32Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],382:[function(require,module,exports){ +},{"./_typed-array":244}],388:[function(require,module,exports){ require('./_typed-array')('Uint8', 1, function (init) { return function Uint8Array(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }); -},{"./_typed-array":238}],383:[function(require,module,exports){ +},{"./_typed-array":244}],389:[function(require,module,exports){ require('./_typed-array')('Uint8', 1, function (init) { return function Uint8ClampedArray(data, byteOffset, length) { return init(this, data, byteOffset, length); }; }, true); -},{"./_typed-array":238}],384:[function(require,module,exports){ +},{"./_typed-array":244}],390:[function(require,module,exports){ 'use strict'; var global = require('./_global'); var each = require('./_array-methods')(0); @@ -23293,7 +21805,7 @@ if (NATIVE_WEAK_MAP && IS_IE11) { }); } -},{"./_array-methods":136,"./_collection":145,"./_collection-weak":144,"./_global":164,"./_is-object":175,"./_meta":188,"./_object-assign":191,"./_redefine":212,"./_validate-collection":243}],385:[function(require,module,exports){ +},{"./_array-methods":142,"./_collection":151,"./_collection-weak":150,"./_global":170,"./_is-object":181,"./_meta":194,"./_object-assign":197,"./_redefine":218,"./_validate-collection":249}],391:[function(require,module,exports){ 'use strict'; var weak = require('./_collection-weak'); var validate = require('./_validate-collection'); @@ -23309,7 +21821,7 @@ require('./_collection')(WEAK_SET, function (get) { } }, weak, false, true); -},{"./_collection":145,"./_collection-weak":144,"./_validate-collection":243}],386:[function(require,module,exports){ +},{"./_collection":151,"./_collection-weak":150,"./_validate-collection":249}],392:[function(require,module,exports){ 'use strict'; // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap var $export = require('./_export'); @@ -23333,7 +21845,7 @@ $export($export.P, 'Array', { require('./_add-to-unscopables')('flatMap'); -},{"./_a-function":127,"./_add-to-unscopables":129,"./_array-species-create":139,"./_export":156,"./_flatten-into-array":161,"./_to-length":235,"./_to-object":236}],387:[function(require,module,exports){ +},{"./_a-function":133,"./_add-to-unscopables":135,"./_array-species-create":145,"./_export":162,"./_flatten-into-array":167,"./_to-length":241,"./_to-object":242}],393:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/Array.prototype.includes var $export = require('./_export'); @@ -23347,7 +21859,7 @@ $export($export.P, 'Array', { require('./_add-to-unscopables')('includes'); -},{"./_add-to-unscopables":129,"./_array-includes":135,"./_export":156}],388:[function(require,module,exports){ +},{"./_add-to-unscopables":135,"./_array-includes":141,"./_export":162}],394:[function(require,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = require('./_export'); var $entries = require('./_object-to-array')(true); @@ -23358,7 +21870,7 @@ $export($export.S, 'Object', { } }); -},{"./_export":156,"./_object-to-array":204}],389:[function(require,module,exports){ +},{"./_export":162,"./_object-to-array":210}],395:[function(require,module,exports){ // https://github.com/tc39/proposal-object-getownpropertydescriptors var $export = require('./_export'); var ownKeys = require('./_own-keys'); @@ -23382,7 +21894,7 @@ $export($export.S, 'Object', { } }); -},{"./_create-property":147,"./_export":156,"./_object-gopd":195,"./_own-keys":205,"./_to-iobject":234}],390:[function(require,module,exports){ +},{"./_create-property":153,"./_export":162,"./_object-gopd":201,"./_own-keys":211,"./_to-iobject":240}],396:[function(require,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = require('./_export'); var $values = require('./_object-to-array')(false); @@ -23393,7 +21905,7 @@ $export($export.S, 'Object', { } }); -},{"./_export":156,"./_object-to-array":204}],391:[function(require,module,exports){ +},{"./_export":162,"./_object-to-array":210}],397:[function(require,module,exports){ // https://github.com/tc39/proposal-promise-finally 'use strict'; var $export = require('./_export'); @@ -23415,7 +21927,7 @@ $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { ); } }); -},{"./_core":146,"./_export":156,"./_global":164,"./_promise-resolve":209,"./_species-constructor":221}],392:[function(require,module,exports){ +},{"./_core":152,"./_export":162,"./_global":170,"./_promise-resolve":215,"./_species-constructor":227}],398:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export'); @@ -23431,7 +21943,7 @@ $export($export.P + $export.F * WEBKIT_BUG, 'String', { } }); -},{"./_export":156,"./_string-pad":226,"./_user-agent":242}],393:[function(require,module,exports){ +},{"./_export":162,"./_string-pad":232,"./_user-agent":248}],399:[function(require,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = require('./_export'); @@ -23447,7 +21959,7 @@ $export($export.P + $export.F * WEBKIT_BUG, 'String', { } }); -},{"./_export":156,"./_string-pad":226,"./_user-agent":242}],394:[function(require,module,exports){ +},{"./_export":162,"./_string-pad":232,"./_user-agent":248}],400:[function(require,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim require('./_string-trim')('trimLeft', function ($trim) { @@ -23456,7 +21968,7 @@ require('./_string-trim')('trimLeft', function ($trim) { }; }, 'trimStart'); -},{"./_string-trim":228}],395:[function(require,module,exports){ +},{"./_string-trim":234}],401:[function(require,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim require('./_string-trim')('trimRight', function ($trim) { @@ -23465,10 +21977,10 @@ require('./_string-trim')('trimRight', function ($trim) { }; }, 'trimEnd'); -},{"./_string-trim":228}],396:[function(require,module,exports){ +},{"./_string-trim":234}],402:[function(require,module,exports){ require('./_wks-define')('asyncIterator'); -},{"./_wks-define":244}],397:[function(require,module,exports){ +},{"./_wks-define":250}],403:[function(require,module,exports){ var $iterators = require('./es6.array.iterator'); var getKeys = require('./_object-keys'); var redefine = require('./_redefine'); @@ -23528,7 +22040,7 @@ for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++ } } -},{"./_global":164,"./_hide":166,"./_iterators":182,"./_object-keys":201,"./_redefine":212,"./_wks":246,"./es6.array.iterator":258}],398:[function(require,module,exports){ +},{"./_global":170,"./_hide":172,"./_iterators":188,"./_object-keys":207,"./_redefine":218,"./_wks":252,"./es6.array.iterator":264}],404:[function(require,module,exports){ var $export = require('./_export'); var $task = require('./_task'); $export($export.G + $export.B, { @@ -23536,7 +22048,7 @@ $export($export.G + $export.B, { clearImmediate: $task.clear }); -},{"./_export":156,"./_task":230}],399:[function(require,module,exports){ +},{"./_export":162,"./_task":236}],405:[function(require,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var global = require('./_global'); var $export = require('./_export'); @@ -23558,13 +22070,13 @@ $export($export.G + $export.B + $export.F * MSIE, { setInterval: wrap(global.setInterval) }); -},{"./_export":156,"./_global":164,"./_user-agent":242}],400:[function(require,module,exports){ +},{"./_export":162,"./_global":170,"./_user-agent":248}],406:[function(require,module,exports){ require('../modules/web.timers'); require('../modules/web.immediate'); require('../modules/web.dom.iterable'); module.exports = require('../modules/_core'); -},{"../modules/_core":146,"../modules/web.dom.iterable":397,"../modules/web.immediate":398,"../modules/web.timers":399}],401:[function(require,module,exports){ +},{"../modules/_core":152,"../modules/web.dom.iterable":403,"../modules/web.immediate":404,"../modules/web.timers":405}],407:[function(require,module,exports){ "use strict"; var _index = require("./index.js"); @@ -23580,7 +22092,7 @@ var _index = require("./index.js"); module.exports = { IdleQueue: _index.IdleQueue }; -},{"./index.js":402}],402:[function(require,module,exports){ +},{"./index.js":408}],408:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -23871,7 +22383,7 @@ function _tryIdleCall(idleQueue) { }, 0); }, 0); } -},{}],403:[function(require,module,exports){ +},{}],409:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unknownAction = exports.runFullQueryAgain = exports.removeExistingAndInsertAtSortPosition = exports.insertAtSortPosition = exports.alwaysWrong = exports.replaceExisting = exports.removeExisting = exports.removeLastInsertLast = exports.removeFirstInsertFirst = exports.removeLastInsertFirst = exports.removeFirstInsertLast = exports.removeLastItem = exports.removeFirstItem = exports.insertLast = exports.insertFirst = exports.doNothing = void 0; @@ -24019,7 +22531,7 @@ var unknownAction = function (_input) { }; exports.unknownAction = unknownAction; -},{"array-push-at-sort-position":60}],404:[function(require,module,exports){ +},{"array-push-at-sort-position":67}],410:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.actionFunctions = exports.orderedActionList = void 0; @@ -24066,7 +22578,7 @@ exports.actionFunctions = { unknownAction: action_functions_1.unknownAction }; -},{"./action-functions":403}],405:[function(require,module,exports){ +},{"./action-functions":409}],411:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveInput = exports.getSimpleBdd = exports.minimalBddString = void 0; @@ -24086,7 +22598,7 @@ var resolveInput = function (input) { }; exports.resolveInput = resolveInput; -},{"../states":407,"binary-decision-diagram":68}],406:[function(require,module,exports){ +},{"../states":413,"binary-decision-diagram":75}],412:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -24149,7 +22661,7 @@ function runAction(action, queryParams, changeEvent, previousResults, keyDocumen } exports.runAction = runAction; -},{"./actions":404,"./bdd/bdd.generated":405,"./states":407,"./util":409}],407:[function(require,module,exports){ +},{"./actions":410,"./bdd/bdd.generated":411,"./states":413,"./util":415}],413:[function(require,module,exports){ "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -24259,7 +22771,7 @@ function logStateSet(stateSet) { } exports.logStateSet = logStateSet; -},{"./state-resolver":408}],408:[function(require,module,exports){ +},{"./state-resolver":414}],414:[function(require,module,exports){ "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; @@ -24457,7 +22969,7 @@ var wasResultsEmpty = function (input) { }; exports.wasResultsEmpty = wasResultsEmpty; -},{"../util":409,"object-path":421}],409:[function(require,module,exports){ +},{"../util":415,"object-path":419}],415:[function(require,module,exports){ "use strict"; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; @@ -24620,16872 +23132,2776 @@ function roundToTwoDecimals(num) { } exports.roundToTwoDecimals = roundToTwoDecimals; -},{}],410:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - +},{}],416:[function(require,module,exports){ 'use strict'; -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } +// do not edit .js files directly - edit src/index.jst -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} +module.exports = function equal(a, b) { + if (a === b) return true; -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; -EventEmitter.init = function() { + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } + for (i = length; i-- !== 0;) { + var key = keys[i]; - this._maxListeners = this._maxListeners || undefined; -}; + if (!equal(a[key], b[key])) return false; + } -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + return true; } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); + // true if both NaN, false otherwise + return a!==a && b!==b; }; -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; +},{}],417:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } + i += d - var handler = events[type]; + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - if (handler === undefined) - return false; + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - if (typeof handler === 'function') { - ReflectApply(handler, this, args); + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); + m = m + Math.pow(2, mLen) + e = e - eBias } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - checkListener(listener); + value = Math.abs(value) - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); + if (e + eBias >= 1) { + value += rt / c } else { - existing.push(listener); + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 } - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 } } - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; + buffer[offset + i - d] |= s * 128 } -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); +},{}],418:[function(require,module,exports){ +(function (global,Buffer){(function (){ +// +// THIS FILE IS AUTOMATICALLY GENERATED! DO NOT EDIT BY HAND! +// +; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' + ? module.exports = factory() + : typeof define === 'function' && define.amd + ? define(factory) : + // cf. https://github.com/dankogai/js-base64/issues/119 + (function () { + // existing version for noConflict() + var _Base64 = global.Base64; + var gBase64 = factory(); + gBase64.noConflict = function () { + global.Base64 = _Base64; + return gBase64; + }; + if (global.Meteor) { // Meteor.js + Base64 = gBase64; + } + global.Base64 = gBase64; + })(); +}((typeof self !== 'undefined' ? self + : typeof window !== 'undefined' ? window + : typeof global !== 'undefined' ? global + : this), function () { + 'use strict'; + /** + * base64.ts + * + * Licensed under the BSD 3-Clause License. + * http://opensource.org/licenses/BSD-3-Clause + * + * References: + * http://en.wikipedia.org/wiki/Base64 + * + * @author Dan Kogai (https://github.com/dankogai) + */ + var version = '3.7.3'; + /** + * @deprecated use lowercase `version`. + */ + var VERSION = version; + var _hasatob = typeof atob === 'function'; + var _hasbtoa = typeof btoa === 'function'; + var _hasBuffer = typeof Buffer === 'function'; + var _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined; + var _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined; + var b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + var b64chs = Array.prototype.slice.call(b64ch); + var b64tab = (function (a) { + var tab = {}; + a.forEach(function (c, i) { return tab[c] = i; }); + return tab; + })(b64chs); + var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; + var _fromCC = String.fromCharCode.bind(String); + var _U8Afrom = typeof Uint8Array.from === 'function' + ? Uint8Array.from.bind(Uint8Array) + : function (it, fn) { + if (fn === void 0) { fn = function (x) { return x; }; } + return new Uint8Array(Array.prototype.slice.call(it, 0).map(fn)); + }; + var _mkUriSafe = function (src) { return src + .replace(/=/g, '').replace(/[+\/]/g, function (m0) { return m0 == '+' ? '-' : '_'; }); }; + var _tidyB64 = function (s) { return s.replace(/[^A-Za-z0-9\+\/]/g, ''); }; + /** + * polyfill version of `btoa` + */ + var btoaPolyfill = function (bin) { + // console.log('polyfilled'); + var u32, c0, c1, c2, asc = ''; + var pad = bin.length % 3; + for (var i = 0; i < bin.length;) { + if ((c0 = bin.charCodeAt(i++)) > 255 || + (c1 = bin.charCodeAt(i++)) > 255 || + (c2 = bin.charCodeAt(i++)) > 255) + throw new TypeError('invalid character found'); + u32 = (c0 << 16) | (c1 << 8) | c2; + asc += b64chs[u32 >> 18 & 63] + + b64chs[u32 >> 12 & 63] + + b64chs[u32 >> 6 & 63] + + b64chs[u32 & 63]; } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } + return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc; + }; + /** + * does what `window.btoa` of web browsers do. + * @param {String} bin binary string + * @returns {string} Base64-encoded string + */ + var _btoa = _hasbtoa ? function (bin) { return btoa(bin); } + : _hasBuffer ? function (bin) { return Buffer.from(bin, 'binary').toString('base64'); } + : btoaPolyfill; + var _fromUint8Array = _hasBuffer + ? function (u8a) { return Buffer.from(u8a).toString('base64'); } + : function (u8a) { + // cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326 + var maxargs = 0x1000; + var strs = []; + for (var i = 0, l = u8a.length; i < l; i += maxargs) { + strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs))); + } + return _btoa(strs.join('')); + }; + /** + * converts a Uint8Array to a Base64 string. + * @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5 + * @returns {string} Base64 string + */ + var fromUint8Array = function (u8a, urlsafe) { + if (urlsafe === void 0) { urlsafe = false; } + return urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a); + }; + // This trick is found broken https://github.com/dankogai/js-base64/issues/130 + // const utob = (src: string) => unescape(encodeURIComponent(src)); + // reverting good old fationed regexp + var cb_utob = function (c) { + if (c.length < 2) { + var cc = c.charCodeAt(0); + return cc < 0x80 ? c + : cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6)) + + _fromCC(0x80 | (cc & 0x3f))) + : (_fromCC(0xe0 | ((cc >>> 12) & 0x0f)) + + _fromCC(0x80 | ((cc >>> 6) & 0x3f)) + + _fromCC(0x80 | (cc & 0x3f))); } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); else { - spliceOne(list, position); + var cc = 0x10000 + + (c.charCodeAt(0) - 0xD800) * 0x400 + + (c.charCodeAt(1) - 0xDC00); + return (_fromCC(0xf0 | ((cc >>> 18) & 0x07)) + + _fromCC(0x80 | ((cc >>> 12) & 0x3f)) + + _fromCC(0x80 | ((cc >>> 6) & 0x3f)) + + _fromCC(0x80 | (cc & 0x3f))); } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; + var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; + /** + * @deprecated should have been internal use only. + * @param {string} src UTF-8 string + * @returns {string} UTF-16 string + */ + var utob = function (u) { return u.replace(re_utob, cb_utob); }; + // + var _encode = _hasBuffer + ? function (s) { return Buffer.from(s, 'utf8').toString('base64'); } + : _TE + ? function (s) { return _fromUint8Array(_TE.encode(s)); } + : function (s) { return _btoa(utob(s)); }; + /** + * converts a UTF-8-encoded string to a Base64 string. + * @param {boolean} [urlsafe] if `true` make the result URL-safe + * @returns {string} Base64 string + */ + var encode = function (src, urlsafe) { + if (urlsafe === void 0) { urlsafe = false; } + return urlsafe + ? _mkUriSafe(_encode(src)) + : _encode(src); + }; + /** + * converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5. + * @returns {string} Base64 string + */ + var encodeURI = function (src) { return encode(src, true); }; + // This trick is found broken https://github.com/dankogai/js-base64/issues/130 + // const btou = (src: string) => decodeURIComponent(escape(src)); + // reverting good old fationed regexp + var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g; + var cb_btou = function (cccc) { + switch (cccc.length) { + case 4: + var cp = ((0x07 & cccc.charCodeAt(0)) << 18) + | ((0x3f & cccc.charCodeAt(1)) << 12) + | ((0x3f & cccc.charCodeAt(2)) << 6) + | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000; + return (_fromCC((offset >>> 10) + 0xD800) + + _fromCC((offset & 0x3FF) + 0xDC00)); + case 3: + return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12) + | ((0x3f & cccc.charCodeAt(1)) << 6) + | (0x3f & cccc.charCodeAt(2))); + default: + return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6) + | (0x3f & cccc.charCodeAt(1))); } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); + }; + /** + * @deprecated should have been internal use only. + * @param {string} src UTF-16 string + * @returns {string} UTF-8 string + */ + var btou = function (b) { return b.replace(re_btou, cb_btou); }; + /** + * polyfill version of `atob` + */ + var atobPolyfill = function (asc) { + // console.log('polyfilled'); + asc = asc.replace(/\s+/g, ''); + if (!b64re.test(asc)) + throw new TypeError('malformed base64.'); + asc += '=='.slice(2 - (asc.length & 3)); + var u24, bin = '', r1, r2; + for (var i = 0; i < asc.length;) { + u24 = b64tab[asc.charAt(i++)] << 18 + | b64tab[asc.charAt(i++)] << 12 + | (r1 = b64tab[asc.charAt(i++)]) << 6 + | (r2 = b64tab[asc.charAt(i++)]); + bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) + : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) + : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255); } - } - - return this; + return bin; }; + /** + * does what `window.atob` of web browsers do. + * @param {String} asc Base64-encoded string + * @returns {string} binary string + */ + var _atob = _hasatob ? function (asc) { return atob(_tidyB64(asc)); } + : _hasBuffer ? function (asc) { return Buffer.from(asc, 'base64').toString('binary'); } + : atobPolyfill; + // + var _toUint8Array = _hasBuffer + ? function (a) { return _U8Afrom(Buffer.from(a, 'base64')); } + : function (a) { return _U8Afrom(_atob(a), function (c) { return c.charCodeAt(0); }); }; + /** + * converts a Base64 string to a Uint8Array. + */ + var toUint8Array = function (a) { return _toUint8Array(_unURI(a)); }; + // + var _decode = _hasBuffer + ? function (a) { return Buffer.from(a, 'base64').toString('utf8'); } + : _TD + ? function (a) { return _TD.decode(_toUint8Array(a)); } + : function (a) { return btou(_atob(a)); }; + var _unURI = function (a) { return _tidyB64(a.replace(/[-_]/g, function (m0) { return m0 == '-' ? '+' : '/'; })); }; + /** + * converts a Base64 string to a UTF-8 string. + * @param {String} src Base64 string. Both normal and URL-safe are supported + * @returns {string} UTF-8 string + */ + var decode = function (src) { return _decode(_unURI(src)); }; + /** + * check if a value is a valid Base64 string + * @param {String} src a value to check + */ + var isValid = function (src) { + if (typeof src !== 'string') + return false; + var s = src.replace(/\s+/g, '').replace(/={0,2}$/, ''); + return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s); + }; + // + var _noEnum = function (v) { + return { + value: v, enumerable: false, writable: true, configurable: true + }; + }; + /** + * extend String.prototype with relevant methods + */ + var extendString = function () { + var _add = function (name, body) { return Object.defineProperty(String.prototype, name, _noEnum(body)); }; + _add('fromBase64', function () { return decode(this); }); + _add('toBase64', function (urlsafe) { return encode(this, urlsafe); }); + _add('toBase64URI', function () { return encode(this, true); }); + _add('toBase64URL', function () { return encode(this, true); }); + _add('toUint8Array', function () { return toUint8Array(this); }); + }; + /** + * extend Uint8Array.prototype with relevant methods + */ + var extendUint8Array = function () { + var _add = function (name, body) { return Object.defineProperty(Uint8Array.prototype, name, _noEnum(body)); }; + _add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); }); + _add('toBase64URI', function () { return fromUint8Array(this, true); }); + _add('toBase64URL', function () { return fromUint8Array(this, true); }); + }; + /** + * extend Builtin prototypes with relevant methods + */ + var extendBuiltins = function () { + extendString(); + extendUint8Array(); + }; + var gBase64 = { + version: version, + VERSION: VERSION, + atob: _atob, + atobPolyfill: atobPolyfill, + btoa: _btoa, + btoaPolyfill: btoaPolyfill, + fromBase64: decode, + toBase64: encode, + encode: encode, + encodeURI: encodeURI, + encodeURL: encodeURI, + utob: utob, + btou: btou, + decode: decode, + isValid: isValid, + fromUint8Array: fromUint8Array, + toUint8Array: toUint8Array, + extendString: extendString, + extendUint8Array: extendUint8Array, + extendBuiltins: extendBuiltins + }; + // + // export Base64 to the namespace + // + // ES5 is yet to have Object.assign() that may make transpilers unhappy. + // gBase64.Base64 = Object.assign({}, gBase64); + gBase64.Base64 = {}; + Object.keys(gBase64).forEach(function (k) { return gBase64.Base64[k] = gBase64[k]; }); + return gBase64; +})); + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"buffer":102}],419:[function(require,module,exports){ +(function (root, factory) { + 'use strict' -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); + /*istanbul ignore next:cant test*/ + if (typeof module === 'object' && typeof module.exports === 'object') { + module.exports = factory() + } else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], factory) } else { - return listenerCount.call(emitter, type); + // Browser globals + root.objectPath = factory() } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; +})(this, function () { + 'use strict' - if (events !== undefined) { - var evlistener = events[type]; + var toStr = Object.prototype.toString - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; + function hasOwnProperty (obj, prop) { + if (obj == null) { + return false } + //to handle objects with null prototypes (too edge case?) + return Object.prototype.hasOwnProperty.call(obj, prop) } - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); + function isEmpty (value) { + if (!value) { + return true } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); + if (isArray(value) && value.length === 0) { + return true + } else if (typeof value !== 'string') { + for (var i in value) { + if (hasOwnProperty(value, i)) { + return false + } } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + return true } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + return false } -} -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + function toString (type) { + return toStr.call(type) } -} - -},{}],411:[function(require,module,exports){ -'use strict'; - -// do not edit .js files directly - edit src/index.jst - + function isObject (obj) { + return typeof obj === 'object' && toString(obj) === '[object Object]' + } -module.exports = function equal(a, b) { - if (a === b) return true; + var isArray = Array.isArray || function (obj) { + /*istanbul ignore next:cant test*/ + return toStr.call(obj) === '[object Array]' + } - if (a && b && typeof a == 'object' && typeof b == 'object') { - if (a.constructor !== b.constructor) return false; + function isBoolean (obj) { + return typeof obj === 'boolean' || toString(obj) === '[object Boolean]' + } - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; + function getKey (key) { + var intKey = parseInt(key) + if (intKey.toString() === key) { + return intKey } + return key + } + function factory (options) { + options = options || {} + var objectPath = function (obj) { + return Object.keys(objectPath).reduce(function (proxy, prop) { + if (prop === 'create') { + return proxy + } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; + /*istanbul ignore else*/ + if (typeof objectPath[prop] === 'function') { + proxy[prop] = objectPath[prop].bind(objectPath, obj) + } - for (i = length; i-- !== 0;) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + return proxy + }, {}) + } - for (i = length; i-- !== 0;) { - var key = keys[i]; + var hasShallowProperty + if (options.includeInheritedProps) { + hasShallowProperty = function () { + return true + } + } else { + hasShallowProperty = function (obj, prop) { + return (typeof prop === 'number' && Array.isArray(obj)) || hasOwnProperty(obj, prop) + } + } - if (!equal(a[key], b[key])) return false; + function getShallowProperty (obj, prop) { + if (hasShallowProperty(obj, prop)) { + return obj[prop] + } } - return true; - } + var getShallowPropertySafely + if (options.includeInheritedProps) { + getShallowPropertySafely = function (obj, currentPath) { + if (typeof currentPath !== 'string' && typeof currentPath !== 'number') { + currentPath = String(currentPath) + } + var currentValue = getShallowProperty(obj, currentPath) + if (currentPath === '__proto__' || currentPath === 'prototype' || + (currentPath === 'constructor' && typeof currentValue === 'function')) { + throw new Error('For security reasons, object\'s magic properties cannot be set') + } + return currentValue + } + } else { + getShallowPropertySafely = function (obj, currentPath) { + return getShallowProperty(obj, currentPath) + } + } - // true if both NaN, false otherwise - return a!==a && b!==b; -}; - -},{}],412:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] + function set (obj, path, value, doNotReplace) { + if (typeof path === 'number') { + path = [path] + } + if (!path || path.length === 0) { + return obj + } + if (typeof path === 'string') { + return set(obj, path.split('.').map(getKey), value, doNotReplace) + } + var currentPath = path[0] + var currentValue = getShallowPropertySafely(obj, currentPath) + if (path.length === 1) { + if (currentValue === void 0 || !doNotReplace) { + obj[currentPath] = value + } + return currentValue + } - i += d + if (currentValue === void 0) { + //check if we assume an array + if (typeof path[1] === 'number') { + obj[currentPath] = [] + } else { + obj[currentPath] = {} + } + } - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + return set(obj[currentPath], path.slice(1), value, doNotReplace) + } - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + objectPath.has = function (obj, path) { + if (typeof path === 'number') { + path = [path] + } else if (typeof path === 'string') { + path = path.split('.') + } - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} + if (!path || path.length === 0) { + return !!obj + } -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + for (var i = 0; i < path.length; i++) { + var j = getKey(path[i]) - value = Math.abs(value) + if ((typeof j === 'number' && isArray(obj) && j < obj.length) || + (options.includeInheritedProps ? (j in Object(obj)) : hasOwnProperty(obj, j))) { + obj = obj[j] + } else { + return false + } + } - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) + return true } - if (value * c >= 2) { - e++ - c /= 2 + + objectPath.ensureExists = function (obj, path, value) { + return set(obj, path, value, true) } - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 + objectPath.set = function (obj, path, value, doNotReplace) { + return set(obj, path, value, doNotReplace) } - } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + objectPath.insert = function (obj, path, value, at) { + var arr = objectPath.get(obj, path) + at = ~~at + if (!isArray(arr)) { + arr = [] + objectPath.set(obj, path, arr) + } + arr.splice(at, 0, value) + } - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + objectPath.empty = function (obj, path) { + if (isEmpty(path)) { + return void 0 + } + if (obj == null) { + return void 0 + } - buffer[offset + i - d] |= s * 128 -} + var value, i + if (!(value = objectPath.get(obj, path))) { + return void 0 + } -},{}],413:[function(require,module,exports){ -'use strict'; -var types = [ - require('./nextTick'), - require('./queueMicrotask'), - require('./mutation.js'), - require('./messageChannel'), - require('./stateChange'), - require('./timeout') -]; -var draining; -var currentQueue; -var queueIndex = -1; -var queue = []; -var scheduled = false; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - nextTick(); - } -} + if (typeof value === 'string') { + return objectPath.set(obj, path, '') + } else if (isBoolean(value)) { + return objectPath.set(obj, path, false) + } else if (typeof value === 'number') { + return objectPath.set(obj, path, 0) + } else if (isArray(value)) { + value.length = 0 + } else if (isObject(value)) { + for (i in value) { + if (hasShallowProperty(value, i)) { + delete value[i] + } + } + } else { + return objectPath.set(obj, path, null) + } + } -//named nextTick for less confusing stack traces -function nextTick() { - if (draining) { - return; - } - scheduled = false; - draining = true; - var len = queue.length; - var timeout = setTimeout(cleanUpNextTick); - while (len) { - currentQueue = queue; - queue = []; - while (currentQueue && ++queueIndex < len) { - currentQueue[queueIndex].run(); - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - queueIndex = -1; - draining = false; - clearTimeout(timeout); -} -var scheduleDrain; -var i = -1; -var len = types.length; -while (++i < len) { - if (types[i] && types[i].test && types[i].test()) { - scheduleDrain = types[i].install(nextTick); - break; - } -} -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - var fun = this.fun; - var array = this.array; - switch (array.length) { - case 0: - return fun(); - case 1: - return fun(array[0]); - case 2: - return fun(array[0], array[1]); - case 3: - return fun(array[0], array[1], array[2]); - default: - return fun.apply(null, array); - } + objectPath.push = function (obj, path /*, values */) { + var arr = objectPath.get(obj, path) + if (!isArray(arr)) { + arr = [] + objectPath.set(obj, path, arr) + } -}; -module.exports = immediate; -function immediate(task) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + arr.push.apply(arr, Array.prototype.slice.call(arguments, 2)) } - } - queue.push(new Item(task, args)); - if (!scheduled && !draining) { - scheduled = true; - scheduleDrain(); - } -} - -},{"./messageChannel":414,"./mutation.js":415,"./nextTick":95,"./queueMicrotask":416,"./stateChange":417,"./timeout":418}],414:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; -exports.test = function () { - if (global.setImmediate) { - // we can only get here in IE10 - // which doesn't handel postMessage well - return false; - } - return typeof global.MessageChannel !== 'undefined'; -}; + objectPath.coalesce = function (obj, paths, defaultValue) { + var value -exports.install = function (func) { - var channel = new global.MessageChannel(); - channel.port1.onmessage = func; - return function () { - channel.port2.postMessage(0); - }; -}; -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],415:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; -//based off rsvp https://github.com/tildeio/rsvp.js -//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE -//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js + for (var i = 0, len = paths.length; i < len; i++) { + if ((value = objectPath.get(obj, paths[i])) !== void 0) { + return value + } + } -var Mutation = global.MutationObserver || global.WebKitMutationObserver; + return defaultValue + } -exports.test = function () { - return Mutation; -}; + objectPath.get = function (obj, path, defaultValue) { + if (typeof path === 'number') { + path = [path] + } + if (!path || path.length === 0) { + return obj + } + if (obj == null) { + return defaultValue + } + if (typeof path === 'string') { + return objectPath.get(obj, path.split('.'), defaultValue) + } -exports.install = function (handle) { - var called = 0; - var observer = new Mutation(handle); - var element = global.document.createTextNode(''); - observer.observe(element, { - characterData: true - }); - return function () { - element.data = (called = ++called % 2); - }; -}; -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],416:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; -exports.test = function () { - return typeof global.queueMicrotask === 'function'; -}; + var currentPath = getKey(path[0]) + var nextObj = getShallowPropertySafely(obj, currentPath) + if (nextObj === void 0) { + return defaultValue + } -exports.install = function (func) { - return function () { - global.queueMicrotask(func); - }; -}; + if (path.length === 1) { + return nextObj + } -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],417:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; + return objectPath.get(obj[currentPath], path.slice(1), defaultValue) + } -exports.test = function () { - return 'document' in global && 'onreadystatechange' in global.document.createElement('script'); -}; + objectPath.del = function del (obj, path) { + if (typeof path === 'number') { + path = [path] + } -exports.install = function (handle) { - return function () { - - // Create a - - + +