rxdb-server 15.6.1 → 15.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/plugins/client-rest/index.js.map +1 -1
- package/dist/cjs/plugins/client-rest/utils.js.map +1 -1
- package/dist/cjs/plugins/replication-server/helpers.js.map +1 -1
- package/dist/cjs/plugins/replication-server/index.js.map +1 -1
- package/dist/cjs/plugins/replication-server/types.js.map +1 -1
- package/dist/cjs/plugins/server/endpoint-replication.js.map +1 -1
- package/dist/cjs/plugins/server/endpoint-rest.js.map +1 -1
- package/dist/cjs/plugins/server/helper.js.map +1 -1
- package/dist/cjs/plugins/server/index.js.map +1 -1
- package/dist/cjs/plugins/server/rx-server.js.map +1 -1
- package/dist/cjs/plugins/server/types.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/plugins/client-rest/index.js.map +1 -1
- package/dist/esm/plugins/client-rest/utils.js.map +1 -1
- package/dist/esm/plugins/replication-server/helpers.js.map +1 -1
- package/dist/esm/plugins/replication-server/index.js.map +1 -1
- package/dist/esm/plugins/replication-server/types.js.map +1 -1
- package/dist/esm/plugins/server/endpoint-replication.js.map +1 -1
- package/dist/esm/plugins/server/endpoint-rest.js.map +1 -1
- package/dist/esm/plugins/server/helper.js.map +1 -1
- package/dist/esm/plugins/server/index.js.map +1 -1
- package/dist/esm/plugins/server/rx-server.js.map +1 -1
- package/dist/esm/plugins/server/types.js.map +1 -1
- package/package.json +16 -16
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["wrongImport","Error"],"sources":["../../src/index.ts"],"sourcesContent":["export function wrongImport() {\n throw new Error('You should never import this file, only the server plugins');\n}\n"],"mappings":";;;;;;AAAO,SAASA,WAAWA,CAAA,EAAG;EAC1B,MAAM,IAAIC,KAAK,CAAC,4DAA4D,CAAC;AACjF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["wrongImport","Error"],"sources":["../../src/index.ts"],"sourcesContent":["export function wrongImport() {\n throw new Error('You should never import this file, only the server plugins');\n}\n"],"mappings":";;;;;;AAAO,SAASA,WAAWA,CAAA,EAAG;EAC1B,MAAM,IAAIC,KAAK,CAAC,4DAA4D,CAAC;AACjF","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_utils","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_rxjs","_eventsource","_interopRequireDefault","RxRestClient","endpointUrl","headers","eventSource","EventSource","_proto","setHeaders","handleError","response","error","Error","JSON","stringify","query","postRequest","observeQuery","result","Subject","queryAsBase64","btoa","withCredentials","onmessage","event","eventData","parse","data","next","asObservable","ids","set","docs","delete","_delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery, newRxError } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport EventSource from 'eventsource';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: this.headers\n });\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\n\nexport * from './utils.ts';\n"],"mappings":";;;;;;;;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AAkGAC,MAAA,CAAAC,IAAA,CAAAH,MAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAL,MAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAb,MAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AAjGA,IAAAS,KAAA,GAAAb,OAAA;AACA,IAAAc,YAAA,GAAAC,sBAAA,CAAAf,OAAA;AAAsC,IAEzBgB,YAAY,GAAAP,OAAA,CAAAO,YAAA;EACrB,SAAAA,aACoBC,WAAmB,EAC5BC,OAAqB,GAAG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prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_rxjs","_eventsource","_interopRequireDefault","RxRestClient","endpointUrl","headers","eventSource","EventSource","_proto","setHeaders","handleError","response","error","Error","JSON","stringify","query","postRequest","observeQuery","result","Subject","queryAsBase64","btoa","withCredentials","onmessage","event","eventData","parse","data","next","asObservable","ids","set","docs","delete","_delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery, newRxError } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport EventSource from 'eventsource';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: this.headers\n });\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\n\nexport * from './utils.ts';\n"],"mappings":";;;;;;;;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AAkGAC,MAAA,CAAAC,IAAA,CAAAH,MAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAL,MAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAb,MAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AAjGA,IAAAS,KAAA,GAAAb,OAAA;AACA,IAAAc,YAAA,GAAAC,sBAAA,CAAAf,OAAA;AAAsC,IAEzBgB,YAAY,GAAAP,OAAA,CAAAO,YAAA;EACrB,SAAAA,aACoBC,WAAmB,EAC5BC,OAAqB,GAAG,CAAC,CAAC,EACjBC,WAAqC,GAAGC,oBAAW,EACrE;IAAA,KAHkBH,WAAmB,GAAnBA,WAAmB;IAAA,KAC5BC,OAAqB,GAArBA,OAAqB;IAAA,KACZC,WAAqC,GAArCA,WAAqC;EACrD;EAAC,IAAAE,MAAA,GAAAL,YAAA,CAAAX,SAAA;EAAAgB,MAAA,CAELC,UAAU,GAAV,SAAAA,WAAWJ,OAAqB,EAAE;IAC9B,IAAI,CAACA,OAA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AG,IAAAM,kBAAW,EACxB,IAAI,CAACb,WAAW,GAAG,MAAM,EACzB2B,GAAG,EACH,IAAI,CAAC1B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAAH,MAAA,CAEDwB,GAAG,GAAH,SAAAA,IAAIC,IAAiB,EAAE;IACnB,IAAMtB,QAAQ,GAAG,IAAAM,kBAAW,EACxB,IAAI,CAACb,WAAW,GAAG,MAAM,EACzB6B,IAAI,EACJ,IAAI,CAAC5B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAAH,MAAA,CAED0B,MAAM,GAAN,SAAAC,QAAOJ,GAAa,EAAE;IAClB,IAAMpB,QAAQ,GAAG,IAAAM,kBAAW,EACxB,IAAI,CAACb,WAAW,GAAG,SAAS,EAC5B2B,GAAG,EACH,IAAI,CAAC1B,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAA,OAAAR,YAAA;AAAA;AAGE,SAASiC,gBAAgBA,CAC5BhC,WAAmB,EACnBC,OAAqB,EACrBC,WAAqC,GAAGC,oBAAW,EACrD;EAEE,OAAO,IAAIJ,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["postRequest","url","body","headers","request","fetch","method","Object","assign","JSON","stringify","response","json"],"sources":["../../../../src/plugins/client-rest/utils.ts"],"sourcesContent":["import { ById } from 'rxdb/plugins/core';\n\nexport async function postRequest(\n url: string,\n body: any,\n headers: ById<string> = {},\n) {\n const request = await fetch(url, {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, headers),\n body: JSON.stringify(body)\n });\n const response = await request.json();\n return response;\n}\n"],"mappings":";;;;;;AAEO,eAAeA,WAAWA,CAC7BC,GAAW,EACXC,IAAS,EACTC,OAAqB,GAAG,CAAC,CAAC,EAC5B;EACE,IAAMC,OAAO,GAAG,MAAMC,KAAK,CAACJ,GAAG,EAAE;IAC7BK,MAAM,EAAE,MAAM;IACdH,OAAO,EAAEI,MAAM,CAACC,MAAM,CAAC;MACnB,QAAQ,EAAE,kBAAkB;MAC5B,cAAc,EAAE;IACpB,CAAC,EAAEL,OAAO,CAAC;IACXD,IAAI,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI;EAC7B,CAAC,CAAC;EACF,IAAMS,QAAQ,GAAG,MAAMP,OAAO,CAACQ,IAAI,CAAC,CAAC;EACrC,OAAOD,QAAQ;AACnB"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["postRequest","url","body","headers","request","fetch","method","Object","assign","JSON","stringify","response","json"],"sources":["../../../../src/plugins/client-rest/utils.ts"],"sourcesContent":["import { ById } from 'rxdb/plugins/core';\n\nexport async function postRequest(\n url: string,\n body: any,\n headers: ById<string> = {},\n) {\n const request = await fetch(url, {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, headers),\n body: JSON.stringify(body)\n });\n const response = await request.json();\n return response;\n}\n"],"mappings":";;;;;;AAEO,eAAeA,WAAWA,CAC7BC,GAAW,EACXC,IAAS,EACTC,OAAqB,GAAG,CAAC,CAAC,EAC5B;EACE,IAAMC,OAAO,GAAG,MAAMC,KAAK,CAACJ,GAAG,EAAE;IAC7BK,MAAM,EAAE,MAAM;IACdH,OAAO,EAAEI,MAAM,CAACC,MAAM,CAAC;MACnB,QAAQ,EAAE,kBAAkB;MAC5B,cAAc,EAAE;IACpB,CAAC,EAAEL,OAAO,CAAC;IACXD,IAAI,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI;EAC7B,CAAC,CAAC;EACF,IAAMS,QAAQ,GAAG,MAAMP,OAAO,CAACQ,IAAI,CAAC,CAAC;EACrC,OAAOD,QAAQ;AACnB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":["_core","require","parseResponse","replicationState","fetchResponse","status","outdatedClient$","next","nextTick","then","cancel","newRxError","url","unauthorized$","forbidden$","data","json","error","console","log","dir"],"sources":["../../../../src/plugins/replication-server/helpers.ts"],"sourcesContent":["import { newRxError, nextTick } from 'rxdb/plugins/core';\nimport type { RxServerReplicationState } from './index.ts';\n\nexport async function parseResponse(\n replicationState: RxServerReplicationState<any>,\n fetchResponse: Response\n) {\n if (fetchResponse.status === 426) {\n replicationState.outdatedClient$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_OUTDATED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 401) {\n replicationState.unauthorized$.next();\n throw newRxError('RC_UNAUTHORIZED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 403) {\n replicationState.forbidden$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_FORBIDDEN', {\n url: fetchResponse.url\n });\n }\n const data = await fetchResponse.json();\n\n if (data.error) {\n // TODO\n console.log('TODO handle parseResponse error');\n console.dir(data);\n throw data;\n }\n\n return data;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAGO,eAAeC,aAAaA,CAC/BC,gBAA+C,EAC/CC,aAAuB,EACzB;EACE,IAAIA,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACG,eAAe,CAACC,IAAI,CAAC,CAAC;IACvC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,aAAa,EAAE;MAC5BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACU,aAAa,CAACN,IAAI,CAAC,CAAC;IACrC,MAAM,IAAAI,gBAAU,EAAC,iBAAiB,EAAE;MAChCC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACW,UAAU,CAACP,IAAI,CAAC,CAAC;IAClC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,cAAc,EAAE;MAC7BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAMG,IAAI,GAAG,MAAMX,aAAa,CAACY,IAAI,CAAC,CAAC;EAEvC,IAAID,IAAI,CAACE,KAAK,EAAE;IACZ;IACAC,OAAO,CAACC,GAAG,CAAC,iCAAiC,CAAC;IAC9CD,OAAO,CAACE,GAAG,CAACL,IAAI,CAAC;IACjB,MAAMA,IAAI;EACd;EAEA,OAAOA,IAAI;AACf"}
|
|
1
|
+
{"version":3,"file":"helpers.js","names":["_core","require","parseResponse","replicationState","fetchResponse","status","outdatedClient$","next","nextTick","then","cancel","newRxError","url","unauthorized$","forbidden$","data","json","error","console","log","dir"],"sources":["../../../../src/plugins/replication-server/helpers.ts"],"sourcesContent":["import { newRxError, nextTick } from 'rxdb/plugins/core';\nimport type { RxServerReplicationState } from './index.ts';\n\nexport async function parseResponse(\n replicationState: RxServerReplicationState<any>,\n fetchResponse: Response\n) {\n if (fetchResponse.status === 426) {\n replicationState.outdatedClient$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_OUTDATED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 401) {\n replicationState.unauthorized$.next();\n throw newRxError('RC_UNAUTHORIZED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 403) {\n replicationState.forbidden$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_FORBIDDEN', {\n url: fetchResponse.url\n });\n }\n const data = await fetchResponse.json();\n\n if (data.error) {\n // TODO\n console.log('TODO handle parseResponse error');\n console.dir(data);\n throw data;\n }\n\n return data;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAGO,eAAeC,aAAaA,CAC/BC,gBAA+C,EAC/CC,aAAuB,EACzB;EACE,IAAIA,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACG,eAAe,CAACC,IAAI,CAAC,CAAC;IACvC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,aAAa,EAAE;MAC5BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACU,aAAa,CAACN,IAAI,CAAC,CAAC;IACrC,MAAM,IAAAI,gBAAU,EAAC,iBAAiB,EAAE;MAChCC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAIR,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACW,UAAU,CAACP,IAAI,CAAC,CAAC;IAClC,IAAAC,cAAQ,EAAC,CAAC,CAACC,IAAI,CAAC,MAAMN,gBAAgB,CAACO,MAAM,CAAC,CAAC,CAAC;IAChD,MAAM,IAAAC,gBAAU,EAAC,cAAc,EAAE;MAC7BC,GAAG,EAAER,aAAa,CAACQ;IACvB,CAAC,CAAC;EACN;EACA,IAAMG,IAAI,GAAG,MAAMX,aAAa,CAACY,IAAI,CAAC,CAAC;EAEvC,IAAID,IAAI,CAACE,KAAK,EAAE;IACZ;IACAC,OAAO,CAACC,GAAG,CAAC,iCAAiC,CAAC;IAC9CD,OAAO,CAACE,GAAG,CAACL,IAAI,CAAC;IACjB,MAAMA,IAAI;EACd;EAEA,OAAOA,IAAI;AACf","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_core","require","_leaderElection","_replication","_rxjs","_helpers","_eventsource","_interopRequireDefault","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","RxServerReplicationState","_RxReplicationState","_inheritsLoose2","default","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","outdatedClient$","Subject","unauthorized$","forbidden$","onCancel","complete","_proto","setHeaders","flatClone","RxReplicationState","replicateServer","options","newRxError","name","args","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","assign","replicationState","data","parseResponse","documents","checkpoint","ensureNotFalsy","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","EventSource","refreshEventSource","withCredentials","onerror","err","status","next","close","promiseWait","then","onopen","x","onmessage","event","eventData","parse","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n RxStorageDefaultCheckpoint,\n ById,\n addRxPlugin, \n newRxError\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport { ServerSyncOptions } from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport EventSource from 'eventsource';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxStorageDefaultCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxStorageDefaultCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\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<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\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 = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: replicationState.headers\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.status === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAaA,IAAAC,eAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAKA,IAAAG,KAAA,GAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAAAQ,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAA2B,IAEdS,wBAAwB,GAAAJ,OAAA,CAAAI,wBAAA,0BAAAC,mBAAA;EAAA,IAAAC,eAAA,CAAAC,OAAA,EAAAH,wBAAA,EAAAC,mBAAA;EAKjC,SAAAD,yBACoBI,qBAA6B,EAC7BC,UAAmC,EACnCC,IAAoE,EACpEC,IAAwC,EACxCC,IAAa,GAAG,IAAI,EAC7BC,SAAiB,GAAG,IAAI,GAAG,CAAC,EAC5BC,SAAkB,GAAG,IAAI,EACzBC,OAAqB,GAAG,CAAC,CAAC,EACnC;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAX,mBAAA,CAAAP,IAAA,OACIU,qBAAqB,EACrBC,UAAU,EACV,UAAU,EACVC,IAAI,EACJC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IAAI,CAAC;YACbvB,SAAS,EAAE+B,SAAS,CAAC/B,SAAS;YAC9BC,UAAU,EAAE8B,SAAS,CAAC9B;UAC1B,CAAC,CAAC;QACN,CAAC;MACL,CAAC;MACDiB,kBAAkB,CAAC,CAAC;MAEpBrB,gBAAgB,CAAC1B,QAAQ,CAACV,IAAI,CAAC,MAAMuD,WAAW,IAAIA,WAAW,CAACQ,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOZ,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAqB,yCAA4B,EAACvD,OAAO,CAACI,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_core","require","_leaderElection","_replication","_rxjs","_helpers","_eventsource","_interopRequireDefault","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","RxServerReplicationState","_RxReplicationState","_inheritsLoose2","default","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","outdatedClient$","Subject","unauthorized$","forbidden$","onCancel","complete","_proto","setHeaders","flatClone","RxReplicationState","replicateServer","options","newRxError","name","args","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","assign","replicationState","data","parseResponse","documents","checkpoint","ensureNotFalsy","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","EventSource","refreshEventSource","withCredentials","onerror","err","status","next","close","promiseWait","then","onopen","x","onmessage","event","eventData","parse","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n RxStorageDefaultCheckpoint,\n ById,\n addRxPlugin, \n newRxError\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport { ServerSyncOptions } from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport EventSource from 'eventsource';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxStorageDefaultCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxStorageDefaultCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\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<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\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 = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: replicationState.headers\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.status === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAaA,IAAAC,eAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAKA,IAAAG,KAAA,GAAAH,OAAA;AAEA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,YAAA,GAAAC,sBAAA,CAAAN,OAAA;AAEA,IAAAO,MAAA,GAAAP,OAAA;AAAAQ,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAA2B,IAEdS,wBAAwB,GAAAJ,OAAA,CAAAI,wBAAA,0BAAAC,mBAAA;EAAA,IAAAC,eAAA,CAAAC,OAAA,EAAAH,wBAAA,EAAAC,mBAAA;EAKjC,S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;YACHjC,WAAW,CAACsC,IAAI,CAAC,QAAQ,CAAC;UAC9B;QACJ,CAAC;QACDP,WAAW,CAACW,MAAM,GAAIC,CAAC,IAAK;UACxB3C,WAAW,CAACsC,IAAI,CAAC,QAAQ,CAAC;QAC9B,CAAC;QACDP,WAAW,CAACa,SAAS,GAAGC,KAAK,IAAI;UAC7B,IAAMC,SAAS,GAAGtB,IAAI,CAACuB,KAAK,CAACF,KAAK,CAAChC,IAAI,CAAC;UACxCb,WAAW,CAACsC,IAAI,CAAC;YACbvB,SAAS,EAAE+B,SAAS,CAAC/B,SAAS;YAC9BC,UAAU,EAAE8B,SAAS,CAAC9B;UAC1B,CAAC,CAAC;QACN,CAAC;MACL,CAAC;MACDiB,kBAAkB,CAAC,CAAC;MAEpBrB,gBAAgB,CAAC1B,QAAQ,CAACV,IAAI,CAAC,MAAMuD,WAAW,IAAIA,WAAW,CAACQ,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOZ,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEA,IAAAqB,yCAA4B,EAACvD,OAAO,CAACI,iBAAiB,EAAEe,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/replication-server/types.ts"],"sourcesContent":["import type {\n MaybePromise,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxStorageDefaultCheckpoint\n} from 'rxdb/plugins/core';\n\nexport type ServerSyncPullOptions<RxDocType> =\n Omit<ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>, 'handler' | 'stream$'>\n & {\n };\n\nexport type ServerSyncPushOptions<RxDocType> = Omit<ReplicationPushOptions<RxDocType>, 'handler'>\n & {\n};\n\nexport type ServerSyncOptions<RxDocType> = Omit<\n ReplicationOptions<RxDocType, any>,\n 'pull' | 'push'\n> & {\n url: string;\n headers?: { [k: string]: string };\n pull?: ServerSyncPullOptions<RxDocType>;\n push?: ServerSyncPushOptions<RxDocType>;\n\n /**\n * If the EventSource API is not available\n * on the runtime, pass an own implementation here.\n * Mostly used with the \"eventsource\" npm package on Node.js.\n */\n eventSource?: typeof EventSource | any\n};\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/replication-server/types.ts"],"sourcesContent":["import type {\n MaybePromise,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxStorageDefaultCheckpoint\n} from 'rxdb/plugins/core';\n\nexport type ServerSyncPullOptions<RxDocType> =\n Omit<ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>, 'handler' | 'stream$'>\n & {\n };\n\nexport type ServerSyncPushOptions<RxDocType> = Omit<ReplicationPushOptions<RxDocType>, 'handler'>\n & {\n};\n\nexport type ServerSyncOptions<RxDocType> = Omit<\n ReplicationOptions<RxDocType, any>,\n 'pull' | 'push'\n> & {\n url: string;\n headers?: { [k: string]: string };\n pull?: ServerSyncPullOptions<RxDocType>;\n push?: ServerSyncPushOptions<RxDocType>;\n\n /**\n * If the EventSource API is not available\n * on the runtime, pass an own implementation here.\n * Mostly used with the \"eventsource\" npm package on Node.js.\n */\n eventSource?: typeof EventSource | any\n};\n"],"mappings":"","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-replication.js","names":["_core","require","_replicationWebsocket","_rxjs","_utils","_helper","RxServerReplicationEndpoint","exports","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","replicationHandler","getReplicationHandlerByCollection","database","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","mergeServerDocumentFields","mergeServerDocumentFieldsMonad","expressApp","get","req","res","getFromMapOrThrow","id","lwt","parseInt","limit","plainQuery","getChangedDocumentsSinceQuery","storageInstance","useQueryChanges","ensureNotFalsy","prepared","prepareQuery","jsonSchema","result","newCheckpoint","documents","length","lastOfArray","updatedAt","_meta","responseDocuments","map","d","setHeader","json","checkpoint","post","docDataMatcherWrite","getDocAllowedMatcher","rows","body","ids","forEach","row","push","nonAllowedRow","find","closeConnection","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","writeSSEHeaders","docDataMatcherStream","subscription","masterChangeStream$","pipe","mergeMap","changes","authHandler","headers","err","useDocs","filter","f","subscribe","filteredAndModified","write","JSON","stringify","on","unsubscribe","end"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageDefaultCheckpoint,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler = getReplicationHandlerByCollection(this.server.database, collection.name);\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.expressApp.get('/' + this.urlPath + '/pull', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const id = req.query.id ? req.query.id as string : '';\n const lwt = req.query.lwt ? parseInt(req.query.lwt as any, 10) : 0;\n const limit = req.query.limit ? parseInt(req.query.limit as any, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxStorageDefaultCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath],\n updatedAt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n this.server.expressApp.post('/' + this.urlPath + '/push', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = req.body;\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n res.setHeader('Content-Type', 'application/json');\n res.json(conflicts);\n });\n this.server.expressApp.get('/' + this.urlPath + '/pullStream', async (req, res) => {\n writeSSEHeaders(res);\n\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n res.write('data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n res.write('data: ' + JSON.stringify({ documents: responseDocuments, checkpoint: ensureNotFalsy(filteredAndModified).checkpoint }) + '\\n\\n');\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAWA,IAAAC,qBAAA,GAAAD,OAAA;AAQA,IAAAE,KAAA,GAAAF,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ACC,SAAS,CAACH,mBAAmB,CAAC,GAAG,MAAM,CAAC;MACtE,CAAC,MAAM;QACH,IAAM3C,iBAAiB,GAAG,IAAAX,qBAAc,EAACsD,mBAAmB,CAAC,CAAChD,SAAS,CAACM,GAAG,CAACC,CAAC,IAAI9B,sBAAsB,CAAC8B,CAAQ,CAAC,CAAC;QAClHvB,GAAG,CAACiE,KAAK,CAAC,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAAC;UAAEnD,SAAS,EAAEK,iBAAiB;UAAEK,UAAU,EAAE,IAAAhB,qBAAc,EAACsD,mBAAmB,CAAC,CAACtC;QAAW,CAAC,CAAC,GAAG,MAAM,CAAC;MAC/I;IAEJ,CAAC,CAAC;;IAEF;AACZ;AACA;IACY3B,GAAG,CAACqE,EAAE,CAAC,OAAO,EAAE,MAAM;MAClBhB,YAAY,CAACiB,WAAW,CAAC,CAAC;MAC1BrE,GAAG,CAACsE,GAAG,CAAC,CAAC;IACb,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC"}
|
|
1
|
+
{"version":3,"file":"endpoint-replication.js","names":["_core","require","_replicationWebsocket","_rxjs","_utils","_helper","RxServerReplicationEndpoint","exports","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","replicationHandler","getReplicationHandlerByCollection","database","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","mergeServerDocumentFields","mergeServerDocumentFieldsMonad","expressApp","get","req","res","getFromMapOrThrow","id","lwt","parseInt","limit","plainQuery","getChangedDocumentsSinceQuery","storageInstance","useQueryChanges","ensureNotFalsy","prepared","prepareQuery","jsonSchema","result","newCheckpoint","documents","length","lastOfArray","updatedAt","_meta","responseDocuments","map","d","setHeader","json","checkpoint","post","docDataMatcherWrite","getDocAllowedMatcher","rows","body","ids","forEach","row","push","nonAllowedRow","find","closeConnection","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","writeSSEHeaders","docDataMatcherStream","subscription","masterChangeStream$","pipe","mergeMap","changes","authHandler","headers","err","useDocs","filter","f","subscribe","filteredAndModified","write","JSON","stringify","on","unsubscribe","end"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageDefaultCheckpoint,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler = getReplicationHandlerByCollection(this.server.database, collection.name);\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.expressApp.get('/' + this.urlPath + '/pull', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const id = req.query.id ? req.query.id as string : '';\n const lwt = req.query.lwt ? parseInt(req.query.lwt as any, 10) : 0;\n const limit = req.query.limit ? parseInt(req.query.limit as any, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxStorageDefaultCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath],\n updatedAt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n this.server.expressApp.post('/' + this.urlPath + '/push', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = req.body;\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n res.setHeader('Content-Type', 'application/json');\n res.json(conflicts);\n });\n this.server.expressApp.get('/' + this.urlPath + '/pullStream', async (req, res) => {\n writeSSEHeaders(res);\n\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n res.write('data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n res.write('data: ' + JSON.stringify({ documents: responseDocuments, checkpoint: ensureNotFalsy(filteredAndModified).checkpoint }) + '\\n\\n');\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAWA,IAAAC,qBAAA,GAAAD,OAAA;AAQA,IAAAE,KAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AAMA,IAAAI,OAAA,GAAAJ,OAAA;AAWqB,IAQRK,2BAA2B,GAAAC,OAAA,CAAAD,2BAAA,GAKpC,SAAAA,4BACoBE,MAA0B,EAC1BC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,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AAC,CAAC;QAClHvB,GAAG,CAACiE,KAAK,CAAC,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAAC;UAAEnD,SAAS,EAAEK,iBAAiB;UAAEK,UAAU,EAAE,IAAAhB,qBAAc,EAACsD,mBAAmB,CAAC,CAACtC;QAAW,CAAC,CAAC,GAAG,MAAM,CAAC;MAC/I;IAEJ,CAAC,CAAC;;IAEF;AACZ;AACA;IACY3B,GAAG,CAACqE,EAAE,CAAC,OAAO,EAAE,MAAM;MAClBhB,YAAY,CAACiB,WAAW,CAAC,CAAC;MAC1BrE,GAAG,CAACsE,GAAG,CAAC,CAAC;IACb,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-rest.js","names":["_core","require","_rxjs","_utils","_helper","REST_PATHS","exports","RxServerRestEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","_this","type","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","expressApp","post","req","res","getFromMapOrThrow","useQuery","ensureNotFalsy","normalizeMangoQuery","jsonSchema","body","err","closeConnection","rxQuery","find","result","exec","setHeader","json","documents","map","d","toJSON","get","writeSSEHeaders","JSON","parse","atob","subscription","$","pipe","mergeMap","resultData","doc","authHandler","headers","filter","f","subscribe","write","stringify","on","unsubscribe","end","ids","findByIds","resultMap","resultValues","Array","from","values","docMatcher","getDocAllowedMatcher","useDocs","docDataMatcherWrite","docsData","docData","allowed","onWriteError","rxdb","code","push","length","promises","docs","useDocsData","slice","_loop","_docData","id","insert","catch","isAllowed","v","patch","_ret","Promise","all","useIds","docsMap","_loop2","isAllowedDoc","isAllowedChange","remove","_ret2"],"sources":["../../../../src/plugins/server/endpoint-rest.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxError,\n normalizeMangoQuery\n} from 'rxdb/plugins/core';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\n\nexport const REST_PATHS = [\n 'query',\n 'query/observe',\n 'get',\n 'set',\n 'delete',\n\n // TODO\n /*\n 'attachments/add',\n 'attachments/delete',\n 'events'\n */\n] as const;\n\n\nexport class RxServerRestEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'rest';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n const primaryPath = this.collection.schema.primaryPath;\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (\n change.assumedMasterState &&\n docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)\n ) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad(this.serverOnlyFields);\n\n this.server.expressApp.post('/' + this.urlPath + '/query', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n let useQuery: FilledMangoQuery<RxDocType>\n try {\n useQuery = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n req.body\n )\n );\n } catch (err) {\n closeConnection(res, 400, 'Bad Request');\n return;\n }\n const rxQuery = this.collection.find(useQuery as any);\n const result = await rxQuery.exec();\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: result.map(d => removeServerOnlyFields(d.toJSON()))\n });\n });\n\n /**\n * It is not possible to send data with server send events,\n * so we send the query as query parameter in base64\n * like ?query=e3NlbGVjdG9yOiB7fX0=\n */\n this.server.expressApp.get('/' + this.urlPath + '/query/observe', async (req, res) => {\n let authData = getFromMapOrThrow(authDataByRequest, req);\n writeSSEHeaders(res);\n\n const useQuery: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n JSON.parse(atob(req.query.query as string))\n )\n );\n\n const rxQuery = this.collection.find(useQuery as any);\n const subscription = rxQuery.$.pipe(\n mergeMap(async (result) => {\n const resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));\n\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting the new results.\n */\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n return resultData;\n }),\n filter(f => f !== null)\n ).subscribe(resultData => {\n res.write('data: ' + JSON.stringify(resultData) + '\\n\\n');\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n\n\n this.server.expressApp.post('/' + this.urlPath + '/get', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const ids: string[] = req.body;\n\n const rxQuery = this.collection.findByIds(ids);\n const resultMap = await rxQuery.exec();\n const resultValues = Array.from(resultMap.values());\n const docMatcher = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n let useDocs = resultValues.map(d => d.toJSON());\n useDocs = useDocs.filter(d => docMatcher(d as any));\n useDocs = useDocs.map(d => removeServerOnlyFields(d))\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: useDocs\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/set', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let docsData: RxDocType[] = req.body;\n\n for (const docData of docsData) {\n const allowed = docDataMatcherWrite(docData as any);\n if (!allowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n }\n\n function onWriteError(err: RxError, docData: RxDocType) {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n docsData.push(docData);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }\n\n while (docsData.length > 0) {\n const promises: Promise<any>[] = [];\n const docs = await collection.findByIds(docsData.map(d => (d as any)[primaryPath])).exec();\n let useDocsData = docsData.slice();\n docsData = [];\n for (const docData of useDocsData) {\n const id = (docData as any)[primaryPath];\n const doc = docs.get(id);\n if (!doc) {\n promises.push(this.collection.insert(docData).catch(err => onWriteError(err, docData)));\n } else {\n const isAllowed = this.changeValidator(authData, {\n newDocumentState: removeServerOnlyFields(docData as any),\n assumedMasterState: removeServerOnlyFields(doc.toJSON(true))\n });\n if (!isAllowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n promises.push(doc.patch(docData).catch(err => onWriteError(err, docData)));\n }\n }\n await Promise.all(promises);\n }\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/delete', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let ids: string[] = req.body;\n while (ids.length > 0) {\n const useIds = ids.slice(0);\n ids = [];\n const promises: Promise<any>[] = [];\n const docsMap = await this.collection.findByIds(useIds).exec();\n for (const id of useIds) {\n const doc = docsMap.get(id);\n if (doc) {\n const isAllowedDoc = docDataMatcherWrite(doc.toJSON(true) as any);\n if (!isAllowedDoc) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const isAllowedChange = this.changeValidator(authData, {\n newDocumentState: doc.toJSON(true) as any,\n assumedMasterState: doc.toJSON(true) as any\n });\n if (!isAllowedChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n promises.push(doc.remove().catch((err: RxError) => {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n ids.push(id);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }));\n }\n }\n await Promise.all(promises);\n }\n res.setHeader('Content-Type', 'application/json');\n res.json({});\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAYA,IAAAC,KAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AAKA,IAAAG,OAAA,GAAAH,OAAA;AAaO,IAAMI,UAAU,GAAAC,OAAA,CAAAD,UAAA,GAAG,CACtB,OAAO,EACP,eAAe,EACf,KAAK,EACL,KAAK,EACL;;AAEA;AACA;AACJ;AACA;AACA;AACA,EAJI,CAKM;AAAC,IAGEE,oBAAoB,GAAAD,OAAA,CAAAC,oBAAA,GAK7B,SAAAA,qBACoBC,MAA0B,EAC1BC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,eAA6D,EAC7CC,gBAA0B,EAC1BC,IAAa,EAC/B;EAAA,IA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C,CAAC,CAAC;YACF,IAAI,CAAC4D,eAAe,EAAE;cAClB,IAAAtE,uBAAe,EAACR,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC;cAAC;gBAAAqE,CAAA;cAAA;YAE3C;YAEAV,QAAQ,CAACF,IAAI,CAAC5B,GAAG,CAACkD,MAAM,CAAC,CAAC,CAACZ,KAAK,CAAE5D,GAAY,IAAK;cAC/C,IAAIA,GAAG,CAACgD,IAAI,IAAIhD,GAAG,CAACiD,IAAI,KAAK,UAAU,EAAE;gBACrC;gBACAhB,GAAG,CAACiB,IAAI,CAACQ,EAAE,CAAC;cAChB,CAAC,MAAM;gBACH,IAAAzD,uBAAe,EAACR,GAAG,EAAE,GAAG,EAAE,uBAAuB,CAAC;gBAClD,MAAMO,GAAG;cACb;YACJ,CAAC,CAAC,CAAC;UACP;QACJ,CAAC;QAAAyE,KAAA;MA5BD,KAAK,IAAMf,EAAE,IAAIS,MAAM;QAAAM,KAAA,SAAAJ,MAAA,CAAAX,EAAA;QAAA,IAAAe,KAAA,SAAAA,KAAA,CAAAX,CAAA;MAAA;MA6BvB,MAAMG,OAAO,CAACC,GAAG,CAACd,QAAQ,CAAC;IAC/B;IACA3D,GAAG,CAACa,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC;IACjDb,GAAG,CAACc,IAAI,CAAC,CAAC,CAAC,CAAC;EAChB,CAAC,CAAC;AACN,CAAC"}
|
|
1
|
+
{"version":3,"file":"endpoint-rest.js","names":["_core","require","_rxjs","_utils","_helper","REST_PATHS","exports","RxServerRestEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","_this","type","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","expressApp","post","req","res","getFromMapOrThrow","useQuery","ensureNotFalsy","normalizeMangoQuery","jsonSchema","body","err","closeConnection","rxQuery","find","result","exec","setHeader","json","documents","map","d","toJSON","get","writeSSEHeaders","JSON","parse","atob","subscription","$","pipe","mergeMap","resultData","doc","authHandler","headers","filter","f","subscribe","write","stringify","on","unsubscribe","end","ids","findByIds","resultMap","resultValues","Array","from","values","docMatcher","getDocAllowedMatcher","useDocs","docDataMatcherWrite","docsData","docData","allowed","onWriteError","rxdb","code","push","length","promises","docs","useDocsData","slice","_loop","_docData","id","insert","catch","isAllowed","v","patch","_ret","Promise","all","useIds","docsMap","_loop2","isAllowedDoc","isAllowedChange","remove","_ret2"],"sources":["../../../../src/plugins/server/endpoint-rest.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxError,\n normalizeMangoQuery\n} from 'rxdb/plugins/core';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\n\nexport const REST_PATHS = [\n 'query',\n 'query/observe',\n 'get',\n 'set',\n 'delete',\n\n // TODO\n /*\n 'attachments/add',\n 'attachments/delete',\n 'events'\n */\n] as const;\n\n\nexport class RxServerRestEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'rest';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n const primaryPath = this.collection.schema.primaryPath;\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (\n change.assumedMasterState &&\n docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)\n ) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad(this.serverOnlyFields);\n\n this.server.expressApp.post('/' + this.urlPath + '/query', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n let useQuery: FilledMangoQuery<RxDocType>\n try {\n useQuery = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n req.body\n )\n );\n } catch (err) {\n closeConnection(res, 400, 'Bad Request');\n return;\n }\n const rxQuery = this.collection.find(useQuery as any);\n const result = await rxQuery.exec();\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: result.map(d => removeServerOnlyFields(d.toJSON()))\n });\n });\n\n /**\n * It is not possible to send data with server send events,\n * so we send the query as query parameter in base64\n * like ?query=e3NlbGVjdG9yOiB7fX0=\n */\n this.server.expressApp.get('/' + this.urlPath + '/query/observe', async (req, res) => {\n let authData = getFromMapOrThrow(authDataByRequest, req);\n writeSSEHeaders(res);\n\n const useQuery: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n JSON.parse(atob(req.query.query as string))\n )\n );\n\n const rxQuery = this.collection.find(useQuery as any);\n const subscription = rxQuery.$.pipe(\n mergeMap(async (result) => {\n const resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));\n\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting the new results.\n */\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n return resultData;\n }),\n filter(f => f !== null)\n ).subscribe(resultData => {\n res.write('data: ' + JSON.stringify(resultData) + '\\n\\n');\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n\n\n this.server.expressApp.post('/' + this.urlPath + '/get', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const ids: string[] = req.body;\n\n const rxQuery = this.collection.findByIds(ids);\n const resultMap = await rxQuery.exec();\n const resultValues = Array.from(resultMap.values());\n const docMatcher = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n let useDocs = resultValues.map(d => d.toJSON());\n useDocs = useDocs.filter(d => docMatcher(d as any));\n useDocs = useDocs.map(d => removeServerOnlyFields(d))\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: useDocs\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/set', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let docsData: RxDocType[] = req.body;\n\n for (const docData of docsData) {\n const allowed = docDataMatcherWrite(docData as any);\n if (!allowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n }\n\n function onWriteError(err: RxError, docData: RxDocType) {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n docsData.push(docData);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }\n\n while (docsData.length > 0) {\n const promises: Promise<any>[] = [];\n const docs = await collection.findByIds(docsData.map(d => (d as any)[primaryPath])).exec();\n let useDocsData = docsData.slice();\n docsData = [];\n for (const docData of useDocsData) {\n const id = (docData as any)[primaryPath];\n const doc = docs.get(id);\n if (!doc) {\n promises.push(this.collection.insert(docData).catch(err => onWriteError(err, docData)));\n } else {\n const isAllowed = this.changeValidator(authData, {\n newDocumentState: removeServerOnlyFields(docData as any),\n assumedMasterState: removeServerOnlyFields(doc.toJSON(true))\n });\n if (!isAllowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n promises.push(doc.patch(docData).catch(err => onWriteError(err, docData)));\n }\n }\n await Promise.all(promises);\n }\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/delete', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let ids: string[] = req.body;\n while (ids.length > 0) {\n const useIds = ids.slice(0);\n ids = [];\n const promises: Promise<any>[] = [];\n const docsMap = await this.collection.findByIds(useIds).exec();\n for (const id of useIds) {\n const doc = docsMap.get(id);\n if (doc) {\n const isAllowedDoc = docDataMatcherWrite(doc.toJSON(true) as any);\n if (!isAllowedDoc) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const isAllowedChange = this.changeValidator(authData, {\n newDocumentState: doc.toJSON(true) as any,\n assumedMasterState: doc.toJSON(true) as any\n });\n if (!isAllowedChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n promises.push(doc.remove().catch((err: RxError) => {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n ids.push(id);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }));\n }\n }\n await Promise.all(promises);\n }\n res.setHeader('Content-Type', 'application/json');\n res.json({});\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAYA,IAAAC,KAAA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AAC,CAAC,CAAC;EAChB,CAAC,CAAC;AACN,CAAC","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helper.js","names":["_cors","_interopRequireDefault","require","_core","setCors","server","path","cors","useCors","expressApp","options","expressCors","origin","optionsSuccessStatus","blockPreviousVersionPaths","currentVersion","v","_loop","version","all","req","res","closeConnection","response","code","message","responseWrite","error","statusCode","set","write","JSON","stringify","end","addAuthMiddleware","authDataByRequest","WeakMap","auth","next","authData","authHandler","headers","err","defaultMatchingQuery","selector","skip","sort","getDocAllowedMatcher","endpoint","useQuery","queryModifier","normalizeMangoQuery","collection","schema","jsonSchema","docDataMatcher","getQueryMatcher","writeSSEHeaders","writeHead","flushHeaders","docContainsServerOnlyFields","serverOnlyFields","doc","has","find","field","removeServerOnlyFieldsMonad","serverOnlyFieldsStencil","_meta","undefined","_rev","_attachments","forEach","docData","Object","assign","mergeServerDocumentFieldsMonad","useFields","slice","uniqueArray","clientDoc","serverDoc","ret","flatClone","doesContainRegexQuerySelector","Array","isArray","found","item","entries","key","value"],"sources":["../../../../src/plugins/server/helper.ts"],"sourcesContent":["import { RxServer } from './rx-server';\nimport expressCors from 'cors';\nimport type {\n Request,\n Response,\n NextFunction\n} from 'express';\nimport { RxServerAuthData, RxServerEndpoint } from './types';\nimport {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n flatClone,\n getQueryMatcher,\n normalizeMangoQuery,\n uniqueArray\n} from 'rxdb/plugins/core';\n\nexport function setCors(\n server: RxServer<any>,\n path: string,\n cors?: string\n) {\n let useCors = cors;\n if (!useCors) {\n useCors = server.cors;\n }\n if (useCors) {\n server.expressApp.options('/' + path + '/*', expressCors({\n origin: useCors,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200\n }));\n }\n}\n\n/**\n * \"block\" the previous version urls and send a 426 on them so that\n * the clients know they must update.\n */\nexport function blockPreviousVersionPaths(\n server: RxServer<any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n server.expressApp.all('/' + path + '/' + version + '/*', (req, res) => {\n closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n v++;\n }\n}\n\n\nexport async function closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.statusCode = code;\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n}\n\n\nexport function addAuthMiddleware<AuthType>(\n server: RxServer<AuthType>,\n path: string,\n): WeakMap<Request, RxServerAuthData<AuthType>> {\n const authDataByRequest = new WeakMap<Request, RxServerAuthData<AuthType>>();\n async function auth(req: Request, res: Response, next: NextFunction) {\n try {\n const authData = await server.authHandler(req.headers);\n authDataByRequest.set(req, authData);\n next();\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return;\n }\n }\n server.expressApp.all('/' + path + '/*', auth, function (req, res, next) {\n next();\n });\n return authDataByRequest;\n}\n\nconst defaultMatchingQuery: FilledMangoQuery<any> = {\n selector: {},\n skip: 0,\n sort: []\n} as const;\n\nexport function getDocAllowedMatcher<RxDocType, AuthType>(\n endpoint: RxServerEndpoint<AuthType, RxDocType>,\n authData: RxServerAuthData<AuthType>\n) {\n const useQuery: FilledMangoQuery<RxDocType> = endpoint.queryModifier ? endpoint.queryModifier(\n authData,\n normalizeMangoQuery(\n endpoint.collection.schema.jsonSchema,\n {}\n )\n ) : defaultMatchingQuery;\n const docDataMatcher = getQueryMatcher(endpoint.collection.schema.jsonSchema, useQuery);\n return docDataMatcher;\n}\n\nexport function writeSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n}\n\nexport function docContainsServerOnlyFields(\n serverOnlyFields: string[],\n doc: any\n) {\n const has = serverOnlyFields.find(field => {\n return typeof doc[field] !== 'undefined'\n });\n return has;\n}\n\nexport function removeServerOnlyFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n const serverOnlyFieldsStencil: any = {\n _meta: undefined,\n _rev: undefined,\n _attachments: undefined\n };\n serverOnlyFields.forEach(field => serverOnlyFieldsStencil[field] = undefined);\n return (\n docData?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!docData) {\n return docData;\n }\n return Object.assign({}, docData, serverOnlyFieldsStencil);\n }\n}\n\nexport function mergeServerDocumentFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n let useFields = serverOnlyFields.slice(0);\n // useFields.push('_rev');\n // useFields.push('_meta');\n // useFields.push('_attachments');\n useFields = uniqueArray(useFields);\n\n return (\n clientDoc: RxDocType | RxDocumentData<RxDocType>,\n serverDoc?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!serverDoc) {\n return clientDoc;\n }\n const ret = flatClone(clientDoc);\n useFields.forEach(field => {\n (ret as any)[field] = (serverDoc as any)[field];\n });\n return ret;\n }\n}\n\n\n/**\n * $regex queries are dangerous because they can dos-attach the \n * \n * @param selector \n */\nexport function doesContainRegexQuerySelector(selector: MangoQuerySelector<any> | any): boolean {\n if (!selector) {\n return false;\n }\n if (Array.isArray(selector)) {\n const found = !!selector.find(item => doesContainRegexQuerySelector(item));\n return found;\n }\n\n if (typeof selector !== 'object') {\n return false;\n }\n\n const entries = Object.entries(selector);\n for (const [key, value] of entries) {\n if (key === '$regex') {\n return true;\n } else {\n const has = doesContainRegexQuerySelector(value);\n if (has) {\n return true;\n }\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACA,IAAAA,KAAA,GAAAC,sBAAA,CAAAC,OAAA;AAOA,IAAAC,KAAA,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,OAAOD,SAAS;IACpB;IACA,IAAME,GAAG,GAAG,IAAAC,eAAS,EAACH,SAAS,CAAC;IAChCH,SAAS,CAACL,OAAO,CAACP,KAAK,IAAI;MACtBiB,GAAG,CAASjB,KAAK,CAAC,GAAIgB,SAAS,CAAShB,KAAK,CAAC;IACnD,CAAC,CAAC;IACF,OAAOiB,GAAG;EACd,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA;AACO,SAASE,6BAA6BA,CAACxC,QAAuC,EAAW;EAC5F,IAAI,CAACA,QAAQ,EAAE;IACX,OAAO,KAAK;EAChB;EACA,IAAIyC,KAAK,CAACC,OAAO,CAAC1C,QAAQ,CAAC,EAAE;IACzB,IAAM2C,KAAK,GAAG,CAAC,CAAC3C,QAAQ,CAACoB,IAAI,CAACwB,IAAI,IAAIJ,6BAA6B,CAACI,IAAI,CAAC,CAAC;IAC1E,OAAOD,KAAK;EAChB;EAEA,IAAI,OAAO3C,QAAQ,KAAK,QAAQ,EAAE;IAC9B,OAAO,KAAK;EAChB;EAEA,IAAM6C,OAAO,GAAGf,MAAM,CAACe,OAAO,CAAC7C,QAAQ,CAAC;EACxC,KAAK,IAAM,CAAC8C,GAAG,EAAEC,KAAK,CAAC,IAAIF,OAAO,EAAE;IAChC,IAAIC,GAAG,KAAK,QAAQ,EAAE;MAClB,OAAO,IAAI;IACf,CAAC,MAAM;MACH,IAAM3B,GAAG,GAAGqB,6BAA6B,CAACO,KAAK,CAAC;MAChD,IAAI5B,GAAG,EAAE;QACL,OAAO,IAAI;MACf;IACJ;EACJ;EAEA,OAAO,KAAK;AAChB"}
|
|
1
|
+
{"version":3,"file":"helper.js","names":["_cors","_interopRequireDefault","require","_core","setCors","server","path","cors","useCors","expressApp","options","expressCors","origin","optionsSuccessStatus","blockPreviousVersionPaths","currentVersion","v","_loop","version","all","req","res","closeConnection","response","code","message","responseWrite","error","statusCode","set","write","JSON","stringify","end","addAuthMiddleware","authDataByRequest","WeakMap","auth","next","authData","authHandler","headers","err","defaultMatchingQuery","selector","skip","sort","getDocAllowedMatcher","endpoint","useQuery","queryModifier","normalizeMangoQuery","collection","schema","jsonSchema","docDataMatcher","getQueryMatcher","writeSSEHeaders","writeHead","flushHeaders","docContainsServerOnlyFields","serverOnlyFields","doc","has","find","field","removeServerOnlyFieldsMonad","serverOnlyFieldsStencil","_meta","undefined","_rev","_attachments","forEach","docData","Object","assign","mergeServerDocumentFieldsMonad","useFields","slice","uniqueArray","clientDoc","serverDoc","ret","flatClone","doesContainRegexQuerySelector","Array","isArray","found","item","entries","key","value"],"sources":["../../../../src/plugins/server/helper.ts"],"sourcesContent":["import { RxServer } from './rx-server';\nimport expressCors from 'cors';\nimport type {\n Request,\n Response,\n NextFunction\n} from 'express';\nimport { RxServerAuthData, RxServerEndpoint } from './types';\nimport {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n flatClone,\n getQueryMatcher,\n normalizeMangoQuery,\n uniqueArray\n} from 'rxdb/plugins/core';\n\nexport function setCors(\n server: RxServer<any>,\n path: string,\n cors?: string\n) {\n let useCors = cors;\n if (!useCors) {\n useCors = server.cors;\n }\n if (useCors) {\n server.expressApp.options('/' + path + '/*', expressCors({\n origin: useCors,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200\n }));\n }\n}\n\n/**\n * \"block\" the previous version urls and send a 426 on them so that\n * the clients know they must update.\n */\nexport function blockPreviousVersionPaths(\n server: RxServer<any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n server.expressApp.all('/' + path + '/' + version + '/*', (req, res) => {\n closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n v++;\n }\n}\n\n\nexport async function closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.statusCode = code;\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n}\n\n\nexport function addAuthMiddleware<AuthType>(\n server: RxServer<AuthType>,\n path: string,\n): WeakMap<Request, RxServerAuthData<AuthType>> {\n const authDataByRequest = new WeakMap<Request, RxServerAuthData<AuthType>>();\n async function auth(req: Request, res: Response, next: NextFunction) {\n try {\n const authData = await server.authHandler(req.headers);\n authDataByRequest.set(req, authData);\n next();\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return;\n }\n }\n server.expressApp.all('/' + path + '/*', auth, function (req, res, next) {\n next();\n });\n return authDataByRequest;\n}\n\nconst defaultMatchingQuery: FilledMangoQuery<any> = {\n selector: {},\n skip: 0,\n sort: []\n} as const;\n\nexport function getDocAllowedMatcher<RxDocType, AuthType>(\n endpoint: RxServerEndpoint<AuthType, RxDocType>,\n authData: RxServerAuthData<AuthType>\n) {\n const useQuery: FilledMangoQuery<RxDocType> = endpoint.queryModifier ? endpoint.queryModifier(\n authData,\n normalizeMangoQuery(\n endpoint.collection.schema.jsonSchema,\n {}\n )\n ) : defaultMatchingQuery;\n const docDataMatcher = getQueryMatcher(endpoint.collection.schema.jsonSchema, useQuery);\n return docDataMatcher;\n}\n\nexport function writeSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n}\n\nexport function docContainsServerOnlyFields(\n serverOnlyFields: string[],\n doc: any\n) {\n const has = serverOnlyFields.find(field => {\n return typeof doc[field] !== 'undefined'\n });\n return has;\n}\n\nexport function removeServerOnlyFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n const serverOnlyFieldsStencil: any = {\n _meta: undefined,\n _rev: undefined,\n _attachments: undefined\n };\n serverOnlyFields.forEach(field => serverOnlyFieldsStencil[field] = undefined);\n return (\n docData?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!docData) {\n return docData;\n }\n return Object.assign({}, docData, serverOnlyFieldsStencil);\n }\n}\n\nexport function mergeServerDocumentFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n let useFields = serverOnlyFields.slice(0);\n // useFields.push('_rev');\n // useFields.push('_meta');\n // useFields.push('_attachments');\n useFields = uniqueArray(useFields);\n\n return (\n clientDoc: RxDocType | RxDocumentData<RxDocType>,\n serverDoc?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!serverDoc) {\n return clientDoc;\n }\n const ret = flatClone(clientDoc);\n useFields.forEach(field => {\n (ret as any)[field] = (serverDoc as any)[field];\n });\n return ret;\n }\n}\n\n\n/**\n * $regex queries are dangerous because they can dos-attach the \n * \n * @param selector \n */\nexport function doesContainRegexQuerySelector(selector: MangoQuerySelector<any> | any): boolean {\n if (!selector) {\n return false;\n }\n if (Array.isArray(selector)) {\n const found = !!selector.find(item => doesContainRegexQuerySelector(item));\n return found;\n }\n\n if (typeof selector !== 'object') {\n return false;\n }\n\n const entries = Object.entries(selector);\n for (const [key, value] of entries) {\n if (key === '$regex') {\n return true;\n } else {\n const has = doesContainRegexQuerySelector(value);\n if (has) {\n return true;\n }\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACA,IAAAA,KAAA,GAAAC,sBAAA,CAAAC,OAAA;AAOA,IAAAC,KAAA,GAAAD,OAAA;AAWO,SAASE,OAAOA,CACnBC,MAAqB,EACrBC,IAAY,EACZC,IAAa,EACf;EACE,IAAIC,OAAO,GAAGD,IAAI;EAClB,IAAI,CAACC,OAAO,EAAE;IACVA,OAAO,GAAGH,MAAM,CAACE,IAAI;EACzB;EACA,IAAIC,OAAO,EAAE;IACTH,MAAM,CAACI,UAAU,CAACC,OAAO,CAAC,GAAG,GAAGJ,IAAI,GAAG,IAAI,EAAE,IAAAK,aAAW,EAAC;MACrDC,MAAM,EAAEJ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QAAQ,EAAE;IACX,OAAO,KAAK;EAChB;EACA,IAAIyC,KAAK,CAACC,OAAO,CAAC1C,QAAQ,CAAC,EAAE;IACzB,IAAM2C,KAAK,GAAG,CAAC,CAAC3C,QAAQ,CAACoB,IAAI,CAACwB,IAAI,IAAIJ,6BAA6B,CAACI,IAAI,CAAC,CAAC;IAC1E,OAAOD,KAAK;EAChB;EAEA,IAAI,OAAO3C,QAAQ,KAAK,QAAQ,EAAE;IAC9B,OAAO,KAAK;EAChB;EAEA,IAAM6C,OAAO,GAAGf,MAAM,CAACe,OAAO,CAAC7C,QAAQ,CAAC;EACxC,KAAK,IAAM,CAAC8C,GAAG,EAAEC,KAAK,CAAC,IAAIF,OAAO,EAAE;IAChC,IAAIC,GAAG,KAAK,QAAQ,EAAE;MAClB,OAAO,IAAI;IACf,CAAC,MAAM;MACH,IAAM3B,GAAG,GAAGqB,6BAA6B,CAACO,KAAK,CAAC;MAChD,IAAI5B,GAAG,EAAE;QACL,OAAO,IAAI;MACf;IACJ;EACJ;EAEA,OAAO,KAAK;AAChB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_utils","require","_rxServer","_express","_interopRequireDefault","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_endpointReplication","_endpointRest","_helper","startRxServer","options","flatClone","serverApp","app","express","use","json","httpServer","Promise","res","rej","hostname","ret","ensureNotFalsy","listen","port","authHandler","data","validUntil","Date","now","server","RxServer","database","cors"],"sources":["../../../../src/plugins/server/index.ts"],"sourcesContent":["import { ensureNotFalsy, flatClone } from 'rxdb/plugins/utils';\nimport { RxServer } from './rx-server.ts';\nimport { RxServerAuthHandler, RxServerOptions } from './types.ts';\nimport express from 'express';\nimport {\n Server as HttpServer\n} from 'http';\n\nexport * from './types.ts';\nexport * from './endpoint-replication.ts';\nexport * from './endpoint-rest.ts';\nexport * from './helper.ts';\n\nexport async function startRxServer<AuthType>(options: RxServerOptions<AuthType>): Promise<RxServer<AuthType>> {\n options = flatClone(options);\n if (!options.serverApp) {\n const app = express();\n options.serverApp = app;\n }\n\n options.serverApp.use(express.json());\n\n\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const hostname = options.hostname ? options.hostname : 'localhost';\n const ret = ensureNotFalsy(options.serverApp).listen(options.port, hostname, () => {\n res(ret);\n });\n });\n\n const authHandler: RxServerAuthHandler<AuthType> = options.authHandler ? options.authHandler : () => {\n return {\n data: {} as any,\n validUntil: Date.now() * 2\n };\n };\n\n const server = new RxServer<AuthType>(\n options.database,\n authHandler,\n httpServer,\n ensureNotFalsy(options.serverApp),\n options.cors\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,SAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAC,sBAAA,CAAAH,OAAA;AAKA,IAAAI,MAAA,GAAAJ,OAAA;AAAAK,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AACA,IAAAS,oBAAA,GAAAjB,OAAA;AAAAK,MAAA,CAAAC,IAAA,CAAAW,oBAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA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AAI,CAACA,OAAO,CAACE,SAAS,EAAE;IACpB,IAAMC,GAAG,GAAG,IAAAC,gBAAO,EAAC,CAAC;IACrBJ,OAAO,CAACE,SAAS,GAAGC,GAAG;EAC3B;EAEAH,OAAO,CAACE,SAAS,CAACG,GAAG,CAACD,gBAAO,CAACE,IAAI,CAAC,CAAC,CAAC;EAGrC,IAAMC,UAAsB,GAAG,MAAM,IAAIC,OAAO,CAAC,CAACC,GAAG,EAAEC,GAAG,KAAK;IAC3D,IAAMC,QAAQ,GAAGX,OAAO,CAACW,QAAQ,GAAGX,OAAO,CAACW,QAAQ,GAAG,WAAW;IAClE,IAAMC,GAAG,GAAG,IAAAC,qBAAc,EAACb,OAAO,CAACE,SAAS,CAAC,CAACY,MAAM,CAACd,OAAO,CAACe,IAAI,EAAEJ,QAAQ,EAAE,MAAM;MAC/EF,GAAG,CAACG,GAAG,CAAC;IACZ,CAAC,CAAC;EACN,CAAC,CAAC;EAEF,IAAMI,WAA0C,GAAGhB,OAAO,CAACgB,WAAW,GAAGhB,OAAO,CAACgB,WAAW,GAAG,MAAM;IACjG,OAAO;MACHC,IAAI,EAAE,CAAC,CAAQ;MACfC,UAAU,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG;IAC7B,CAAC;EACL,CAAC;EAED,IAAMC,MAAM,GAAG,IAAIC,kBAAQ,CACvBtB,OAAO,CAACuB,QAAQ,EAChBP,WAAW,EACXT,UAAU,EACV,IAAAM,qBAAc,EAACb,OAAO,CAACE,SAAS,CAAC,EACjCF,OAAO,CAACwB,IACZ,CAAC;EAED,OAAOH,MAAM;AACjB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_utils","require","_rxServer","_express","_interopRequireDefault","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_endpointReplication","_endpointRest","_helper","startRxServer","options","flatClone","serverApp","app","express","use","json","httpServer","Promise","res","rej","hostname","ret","ensureNotFalsy","listen","port","authHandler","data","validUntil","Date","now","server","RxServer","database","cors"],"sources":["../../../../src/plugins/server/index.ts"],"sourcesContent":["import { ensureNotFalsy, flatClone } from 'rxdb/plugins/utils';\nimport { RxServer } from './rx-server.ts';\nimport { RxServerAuthHandler, RxServerOptions } from './types.ts';\nimport express from 'express';\nimport {\n Server as HttpServer\n} from 'http';\n\nexport * from './types.ts';\nexport * from './endpoint-replication.ts';\nexport * from './endpoint-rest.ts';\nexport * from './helper.ts';\n\nexport async function startRxServer<AuthType>(options: RxServerOptions<AuthType>): Promise<RxServer<AuthType>> {\n options = flatClone(options);\n if (!options.serverApp) {\n const app = express();\n options.serverApp = app;\n }\n\n options.serverApp.use(express.json());\n\n\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const hostname = options.hostname ? options.hostname : 'localhost';\n const ret = ensureNotFalsy(options.serverApp).listen(options.port, hostname, () => {\n res(ret);\n });\n });\n\n const authHandler: RxServerAuthHandler<AuthType> = options.authHandler ? options.authHandler : () => {\n return {\n data: {} as any,\n validUntil: Date.now() * 2\n };\n };\n\n const server = new RxServer<AuthType>(\n options.database,\n authHandler,\n httpServer,\n ensureNotFalsy(options.serverApp),\n options.cors\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,SAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAC,sBAAA,CAAAH,OAAA;AAKA,IAAAI,MAAA,GAAAJ,OAAA;AAAAK,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO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,SAAS,CAAC,EACjCF,OAAO,CAACwB,IACZ,CAAC;EAED,OAAOH,MAAM;AACjB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rx-server.js","names":["_endpointReplication","require","_endpointRest","RxServer","exports","database","authHandler","httpServer","expressApp","cors","endpoints","closeFn","close","bind","onDestroy","push","_proto","prototype","addReplicationEndpoint","opts","endpoint","RxServerReplicationEndpoint","name","collection","queryModifier","_a","q","changeValidator","serverOnlyFields","addRestEndpoint","RxServerRestEndpoint","filter","fn","Promise","res","rej","err","setImmediate","emit"],"sources":["../../../../src/plugins/server/rx-server.ts"],"sourcesContent":["import type {\n RxCollection,\n RxDatabase\n} from 'rxdb/plugins/core';\nimport { RxServerReplicationEndpoint } from './endpoint-replication.ts';\nimport type {\n RxServerAuthHandler,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport {\n Server as HttpServer\n} from 'http';\nimport { Express } from 'express';\nimport { RxServerRestEndpoint } from './endpoint-rest.ts';\n\nexport class RxServer<AuthType> {\n public readonly endpoints: RxServerEndpoint<AuthType, any>[] = [];\n\n private closeFn = (() => this.close()).bind(this);\n\n constructor(\n public readonly database: RxDatabase,\n public readonly authHandler: RxServerAuthHandler<AuthType>,\n public readonly httpServer: HttpServer,\n public readonly expressApp: Express,\n public readonly cors: string = '*'\n ) {\n database.onDestroy.push(this.closeFn);\n }\n\n public async addReplicationEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerReplicationEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n public async addRestEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerRestEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n async close() {\n this.database.onDestroy = this.database.onDestroy.filter(fn => fn !== this.closeFn);\n await new Promise<void>((res, rej) => {\n this.httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate(() => this.httpServer.emit('close'));\n });\n\n }\n}\n"],"mappings":";;;;;;AAIA,IAAAA,oBAAA,GAAAC,OAAA;AAWA,IAAAC,aAAA,GAAAD,OAAA;AAA0D,IAE7CE,QAAQ,GAAAC,OAAA,CAAAD,QAAA;EAKjB,SAAAA,SACoBE,QAAoB,EACpBC,WAA0C,EAC1CC,UAAsB,EACtBC,UAAmB,EACnBC,IAAY,GAAG,GAAG,EACpC;IAAA,KAVcC,SAAS,GAAsC,EAAE;IAAA,KAEzDC,OAAO,GAAG,CAAC,MAAM,IAAI,CAACC,KAAK,CAAC,CAAC,EAAEC,IAAI,CAAC,IAAI,CAAC;IAAA,KAG7BR,QAAoB,GAApBA,QAAoB;IAAA,KACpBC,WAA0C,GAA1CA,WAA0C;IAAA,KAC1CC,UAAsB,GAAtBA,UAA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;EAAAJ,MAAA,CAEKJ,KAAK,GAAX,eAAAA,MAAA,EAAc;IACV,IAAI,CAACP,QAAQ,CAACS,SAAS,GAAG,IAAI,CAACT,QAAQ,CAACS,SAAS,CAACiB,MAAM,CAACC,EAAE,IAAIA,EAAE,KAAK,IAAI,CAACrB,OAAO,CAAC;IACnF,MAAM,IAAIsB,OAAO,CAAO,CAACC,GAAG,EAAEC,GAAG,KAAK;MAClC,IAAI,CAAC5B,UAAU,CAACK,KAAK,CAAEwB,GAAG,IAAK;QAC3B,IAAIA,GAAG,EAAE;UAAED,GAAG,CAACC,GAAG,CAAC;QAAE,CAAC,MAAM;UAAEF,GAAG,CAAC,CAAC;QAAE;MACzC,CAAC,CAAC;MACF;AACZ;AACA;AACA;AACA;MACYG,YAAY,CAAC,MAAM,IAAI,CAAC9B,UAAU,CAAC+B,IAAI,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC,CAAC;EAEN,CAAC;EAAA,OAAAnC,QAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"rx-server.js","names":["_endpointReplication","require","_endpointRest","RxServer","exports","database","authHandler","httpServer","expressApp","cors","endpoints","closeFn","close","bind","onDestroy","push","_proto","prototype","addReplicationEndpoint","opts","endpoint","RxServerReplicationEndpoint","name","collection","queryModifier","_a","q","changeValidator","serverOnlyFields","addRestEndpoint","RxServerRestEndpoint","filter","fn","Promise","res","rej","err","setImmediate","emit"],"sources":["../../../../src/plugins/server/rx-server.ts"],"sourcesContent":["import type {\n RxCollection,\n RxDatabase\n} from 'rxdb/plugins/core';\nimport { RxServerReplicationEndpoint } from './endpoint-replication.ts';\nimport type {\n RxServerAuthHandler,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport {\n Server as HttpServer\n} from 'http';\nimport { Express } from 'express';\nimport { RxServerRestEndpoint } from './endpoint-rest.ts';\n\nexport class RxServer<AuthType> {\n public readonly endpoints: RxServerEndpoint<AuthType, any>[] = [];\n\n private closeFn = (() => this.close()).bind(this);\n\n constructor(\n public readonly database: RxDatabase,\n public readonly authHandler: RxServerAuthHandler<AuthType>,\n public readonly httpServer: HttpServer,\n public readonly expressApp: Express,\n public readonly cors: string = '*'\n ) {\n database.onDestroy.push(this.closeFn);\n }\n\n public async addReplicationEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerReplicationEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n public async addRestEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerRestEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n async close() {\n this.database.onDestroy = this.database.onDestroy.filter(fn => fn !== this.closeFn);\n await new Promise<void>((res, rej) => {\n this.httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate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,MAAA,CAEYa,eAAe,GAA5B,eAAAA,gBAAwCV,IAYvC,EAAE;IACC,IAAMC,QAAQ,GAAG,IAAIU,kCAAoB,CACrC,IAAI,EACJX,IAAI,CAACG,IAAI,EACTH,IAAI,CAACI,UAAU,EACfJ,IAAI,CAACK,aAAa,GAAGL,IAAI,CAACK,aAAa,GAAG,CAACC,EAAE,EAAEC,CAAC,KAAKA,CAAC,EACtDP,IAAI,CAACQ,eAAe,GAAGR,IAAI,CAACQ,eAAe,GAAG,MAAM,IAAI,EACxDR,IAAI,CAACS,gBAAgB,GAAGT,IAAI,CAACS,gBAAgB,GAAG,EAAE,EAClDT,IAAI,CAACV,IACT,CAAC;IACD,IAAI,CAACC,SAAS,CAACK,IAAI,CAACK,QAAQ,CAAC;IAC7B,OAAOA,QAAQ;EACnB,CAAC;EAAAJ,MAAA,CAEKJ,KAAK,GAAX,eAAAA,MAAA,EAAc;IACV,IAAI,CAACP,QAAQ,CAACS,SAAS,GAAG,IAAI,CAACT,QAAQ,CAACS,SAAS,CAACiB,MAAM,CAACC,EAAE,IAAIA,EAAE,KAAK,IAAI,CAACrB,OAAO,CAAC;IACnF,MAAM,IAAIsB,OAAO,CAAO,CAACC,GAAG,EAAEC,GAAG,KAAK;MAClC,IAAI,CAAC5B,UAAU,CAACK,KAAK,CAAEwB,GAAG,IAAK;QAC3B,IAAIA,GAAG,EAAE;UAAED,GAAG,CAACC,GAAG,CAAC;QAAE,CAAC,MAAM;UAAEF,GAAG,CAAC,CAAC;QAAE;MACzC,CAAC,CAAC;MACF;AACZ;AACA;AACA;AACA;MACYG,YAAY,CAAC,MAAM,IAAI,CAAC9B,UAAU,CAAC+B,IAAI,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC,CAAC;EAEN,CAAC;EAAA,OAAAnC,QAAA;AAAA","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/server/types.ts"],"sourcesContent":["import type {\n FilledMangoQuery,\n RxDatabase,\n RxReplicationWriteToMasterRow,\n MaybePromise,\n RxCollection,\n WithDeleted\n} from 'rxdb/plugins/core';\nimport { IncomingHttpHeaders } from 'http';\nimport { Express } from 'express';\n\nexport type RxServerOptions<AuthType> = {\n database: RxDatabase;\n authHandler?: RxServerAuthHandler<AuthType>;\n serverApp?: Express;\n appOptions?: any;\n /**\n * [default=localhost]\n */\n hostname?: 'localhost' | '0.0.0.0' | string;\n port: number;\n /**\n * Set a origin for allowed CORS requests.\n * Can be overwritten by the cors option of the endpoints.\n * [default='*']\n */\n cors?: '*' | string;\n};\n\nexport type RxServerAuthData<AuthType> = {\n data: AuthType;\n validUntil: number;\n};\n\n/**\n * Returns the auth state by the given request headers.\n * Throws if auth not valid.\n */\nexport type RxServerAuthHandler<AuthType> =\n (headers: IncomingHttpHeaders) => MaybePromise<RxServerAuthData<AuthType>>;\n\n/**\n * Modifies a given query in a way to limit the results\n * to what the authenticated user is allowed to see.\n * For example the query selector\n * input: {\n * selector: {\n * myField: { $gt: 100 }\n * }\n * }\n * could be modified to restrict the results to only return\n * documents that are \"owned\" by the user\n * return: {\n * selector: {\n * myField: { $gt: 100 },\n * userId: { $eq: authData.userId }\n * }\n * }\n * \n * \n */\nexport type RxServerQueryModifier<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n query: FilledMangoQuery<RxDocType>\n) => FilledMangoQuery<RxDocType>;\n\n/**\n * Validates if a given change is allowed to be performed on the server.\n * Returns true if allowed, false if not.\n * If a client tries to make a non-allowed change,\n * the client will be disconnected.\n */\nexport type RxServerChangeValidator<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n change: RxReplicationWriteToMasterRow<RxDocType>\n) => boolean;\n\n\nexport interface RxServerEndpoint<AuthType, RxDocType> {\n collection: RxCollection<RxDocType>;\n name: string;\n type: 'replication' | 'rest' | string;\n urlPath: string;\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>;\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>;\n};\n"],"mappings":";;AAkCA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;AAcC"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/server/types.ts"],"sourcesContent":["import type {\n FilledMangoQuery,\n RxDatabase,\n RxReplicationWriteToMasterRow,\n MaybePromise,\n RxCollection,\n WithDeleted\n} from 'rxdb/plugins/core';\nimport { IncomingHttpHeaders } from 'http';\nimport { Express } from 'express';\n\nexport type RxServerOptions<AuthType> = {\n database: RxDatabase;\n authHandler?: RxServerAuthHandler<AuthType>;\n serverApp?: Express;\n appOptions?: any;\n /**\n * [default=localhost]\n */\n hostname?: 'localhost' | '0.0.0.0' | string;\n port: number;\n /**\n * Set a origin for allowed CORS requests.\n * Can be overwritten by the cors option of the endpoints.\n * [default='*']\n */\n cors?: '*' | string;\n};\n\nexport type RxServerAuthData<AuthType> = {\n data: AuthType;\n validUntil: number;\n};\n\n/**\n * Returns the auth state by the given request headers.\n * Throws if auth not valid.\n */\nexport type RxServerAuthHandler<AuthType> =\n (headers: IncomingHttpHeaders) => MaybePromise<RxServerAuthData<AuthType>>;\n\n/**\n * Modifies a given query in a way to limit the results\n * to what the authenticated user is allowed to see.\n * For example the query selector\n * input: {\n * selector: {\n * myField: { $gt: 100 }\n * }\n * }\n * could be modified to restrict the results to only return\n * documents that are \"owned\" by the user\n * return: {\n * selector: {\n * myField: { $gt: 100 },\n * userId: { $eq: authData.userId }\n * }\n * }\n * \n * \n */\nexport type RxServerQueryModifier<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n query: FilledMangoQuery<RxDocType>\n) => FilledMangoQuery<RxDocType>;\n\n/**\n * Validates if a given change is allowed to be performed on the server.\n * Returns true if allowed, false if not.\n * If a client tries to make a non-allowed change,\n * the client will be disconnected.\n */\nexport type RxServerChangeValidator<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n change: RxReplicationWriteToMasterRow<RxDocType>\n) => boolean;\n\n\nexport interface RxServerEndpoint<AuthType, RxDocType> {\n collection: RxCollection<RxDocType>;\n name: string;\n type: 'replication' | 'rest' | string;\n urlPath: string;\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>;\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>;\n};\n"],"mappings":";;AAkCA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;AAcC","ignoreList":[]}
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["wrongImport","Error"],"sources":["../../src/index.ts"],"sourcesContent":["export function wrongImport() {\n throw new Error('You should never import this file, only the server plugins');\n}\n"],"mappings":"AAAA,OAAO,SAASA,WAAWA,CAAA,EAAG;EAC1B,MAAM,IAAIC,KAAK,CAAC,4DAA4D,CAAC;AACjF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["wrongImport","Error"],"sources":["../../src/index.ts"],"sourcesContent":["export function wrongImport() {\n throw new Error('You should never import this file, only the server plugins');\n}\n"],"mappings":"AAAA,OAAO,SAASA,WAAWA,CAAA,EAAG;EAC1B,MAAM,IAAIC,KAAK,CAAC,4DAA4D,CAAC;AACjF","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["postRequest","Subject","EventSource","RxRestClient","endpointUrl","headers","eventSource","_proto","prototype","setHeaders","handleError","response","error","Error","JSON","stringify","query","observeQuery","result","queryAsBase64","btoa","withCredentials","onmessage","event","eventData","parse","data","next","asObservable","get","ids","set","docs","delete","_delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery, newRxError } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport EventSource from 'eventsource';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: this.headers\n });\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\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,EACrBC,WAAqC,GAAGJ,WAAW,EACrD;EAEE,OAAO,IAAIC,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL;AAGA,cAAc,YAAY"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["postRequest","Subject","EventSource","RxRestClient","endpointUrl","headers","eventSource","_proto","prototype","setHeaders","handleError","response","error","Error","JSON","stringify","query","observeQuery","result","queryAsBase64","btoa","withCredentials","onmessage","event","eventData","parse","data","next","asObservable","get","ids","set","docs","delete","_delete","createRestClient"],"sources":["../../../../src/plugins/client-rest/index.ts"],"sourcesContent":["import { ById, MangoQuery, newRxError } from 'rxdb/plugins/core';\nimport { postRequest } from './utils.ts';\nimport { Observable, Subject } from 'rxjs';\nimport EventSource from 'eventsource';\n\nexport class RxRestClient<RxDocType> {\n constructor(\n public readonly endpointUrl: string,\n public headers: ById<string> = {},\n public readonly eventSource: typeof EventSource | any = EventSource\n ) { }\n\n setHeaders(headers: ById<string>) {\n this.headers = headers;\n }\n\n handleError(response: any) {\n if (response.error) {\n throw new Error('Server returned an error ' + JSON.stringify(response));\n }\n }\n\n async query(query: MangoQuery<RxDocType>): Promise<{ documents: RxDocType[] }> {\n const response = await postRequest(\n this.endpointUrl + '/query',\n query,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n observeQuery(query: MangoQuery<RxDocType>): Observable<RxDocType[]> {\n const result = new Subject<RxDocType[]>;\n const queryAsBase64 = btoa(JSON.stringify(query));\n const eventSource: EventSource = new this.eventSource(\n this.endpointUrl + '/query/observe?query=' + queryAsBase64,\n {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: this.headers\n });\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n result.next(eventData);\n };\n return result.asObservable();\n }\n\n get(ids: string[]): Promise<{ documents: RxDocType[] }> {\n const response = postRequest(\n this.endpointUrl + '/get',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n set(docs: RxDocType[]) {\n const response = postRequest(\n this.endpointUrl + '/set',\n docs,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n\n delete(ids: string[]) {\n const response = postRequest(\n this.endpointUrl + '/delete',\n ids,\n this.headers\n );\n this.handleError(response);\n return response;\n }\n}\n\nexport function createRestClient<RxDocType>(\n endpointUrl: string,\n headers: ById<string>,\n eventSource: typeof EventSource | any = EventSource\n) {\n\n return new RxRestClient<RxDocType>(\n endpointUrl,\n headers,\n eventSource\n );\n}\n\n\nexport * from './utils.ts';\n"],"mappings":"AACA,SAASA,WAAW,QAAQ,YAAY;AACxC,SAAqBC,OAAO,QAAQ,MAAM;AAC1C,OAAOC,WAAW,MAAM,aAAa;AAErC,WAAaC,YAAY;EACrB,SAAAA,aACoBC,WAAmB,EAC5BC,OAAqB,GAAG,CAAC,CAAC,EACjBC,WAAqC,GAAGJ,WAAW,EACrE;IAAA,KAHkBE,WAAmB,GAAnBA,WAAmB;IAAA,KAC5BC,OAAqB,GAArBA,OAAqB;IAAA,KACZC,WAAqC,GAArCA,WAAqC;EACrD;EAAC,IAAAC,MAAA,GAAAJ,YAAA,CAAAK,SAAA;EAAAD,MAAA,CAELE,UAAU,GAAV,SAAAA,WAAWJ,OAAqB,EAAE;IAC9B,IAAI,CAACA,OAAO,GAAGA,OAAO;EAC1B,CAAC;EAAAE,MAAA,CAEDG,WAAW,GAAX,SAAAA,YAAYC,QAAa,EAAE;IACvB,IAAIA,QAAQ,CAACC,KAAK,EAAE;MAChB,MAAM,IAAIC,KAAK,CAAC,2BAA2B,GAAGC,IAAI,CAACC,SAAS,CAACJ,QAAQ,CAAC,CAAC;IAC3E;EACJ,CAAC;EAAAJ,MAAA,CAEKS,KAAK,GAAX,eAAAA,MAAYA,MAA4B,EAAuC;IAC3E,IAAML,QAAQ,GAAG,MAAMX,WAAW,CAC9B,IAAI,CAACI,WAAW,GAAG,QAAQ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C;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAAJ,MAAA,CAED0B,MAAM,GAAN,SAAAC,QAAOJ,GAAa,EAAE;IAClB,IAAMnB,QAAQ,GAAGX,WAAW,CACxB,IAAI,CAACI,WAAW,GAAG,SAAS,EAC5B0B,GAAG,EACH,IAAI,CAACzB,OACT,CAAC;IACD,IAAI,CAACK,WAAW,CAACC,QAAQ,CAAC;IAC1B,OAAOA,QAAQ;EACnB,CAAC;EAAA,OAAAR,YAAA;AAAA;AAGL,OAAO,SAASgC,gBAAgBA,CAC5B/B,WAAmB,EACnBC,OAAqB,EACrBC,WAAqC,GAAGJ,WAAW,EACrD;EAEE,OAAO,IAAIC,YAAY,CACnBC,WAAW,EACXC,OAAO,EACPC,WACJ,CAAC;AACL;AAGA,cAAc,YAAY","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["postRequest","url","body","headers","request","fetch","method","Object","assign","JSON","stringify","response","json"],"sources":["../../../../src/plugins/client-rest/utils.ts"],"sourcesContent":["import { ById } from 'rxdb/plugins/core';\n\nexport async function postRequest(\n url: string,\n body: any,\n headers: ById<string> = {},\n) {\n const request = await fetch(url, {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, headers),\n body: JSON.stringify(body)\n });\n const response = await request.json();\n return response;\n}\n"],"mappings":"AAEA,OAAO,eAAeA,WAAWA,CAC7BC,GAAW,EACXC,IAAS,EACTC,OAAqB,GAAG,CAAC,CAAC,EAC5B;EACE,IAAMC,OAAO,GAAG,MAAMC,KAAK,CAACJ,GAAG,EAAE;IAC7BK,MAAM,EAAE,MAAM;IACdH,OAAO,EAAEI,MAAM,CAACC,MAAM,CAAC;MACnB,QAAQ,EAAE,kBAAkB;MAC5B,cAAc,EAAE;IACpB,CAAC,EAAEL,OAAO,CAAC;IACXD,IAAI,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI;EAC7B,CAAC,CAAC;EACF,IAAMS,QAAQ,GAAG,MAAMP,OAAO,CAACQ,IAAI,CAAC,CAAC;EACrC,OAAOD,QAAQ;AACnB"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["postRequest","url","body","headers","request","fetch","method","Object","assign","JSON","stringify","response","json"],"sources":["../../../../src/plugins/client-rest/utils.ts"],"sourcesContent":["import { ById } from 'rxdb/plugins/core';\n\nexport async function postRequest(\n url: string,\n body: any,\n headers: ById<string> = {},\n) {\n const request = await fetch(url, {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, headers),\n body: JSON.stringify(body)\n });\n const response = await request.json();\n return response;\n}\n"],"mappings":"AAEA,OAAO,eAAeA,WAAWA,CAC7BC,GAAW,EACXC,IAAS,EACTC,OAAqB,GAAG,CAAC,CAAC,EAC5B;EACE,IAAMC,OAAO,GAAG,MAAMC,KAAK,CAACJ,GAAG,EAAE;IAC7BK,MAAM,EAAE,MAAM;IACdH,OAAO,EAAEI,MAAM,CAACC,MAAM,CAAC;MACnB,QAAQ,EAAE,kBAAkB;MAC5B,cAAc,EAAE;IACpB,CAAC,EAAEL,OAAO,CAAC;IACXD,IAAI,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI;EAC7B,CAAC,CAAC;EACF,IAAMS,QAAQ,GAAG,MAAMP,OAAO,CAACQ,IAAI,CAAC,CAAC;EACrC,OAAOD,QAAQ;AACnB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":["newRxError","nextTick","parseResponse","replicationState","fetchResponse","status","outdatedClient$","next","then","cancel","url","unauthorized$","forbidden$","data","json","error","console","log","dir"],"sources":["../../../../src/plugins/replication-server/helpers.ts"],"sourcesContent":["import { newRxError, nextTick } from 'rxdb/plugins/core';\nimport type { RxServerReplicationState } from './index.ts';\n\nexport async function parseResponse(\n replicationState: RxServerReplicationState<any>,\n fetchResponse: Response\n) {\n if (fetchResponse.status === 426) {\n replicationState.outdatedClient$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_OUTDATED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 401) {\n replicationState.unauthorized$.next();\n throw newRxError('RC_UNAUTHORIZED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 403) {\n replicationState.forbidden$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_FORBIDDEN', {\n url: fetchResponse.url\n });\n }\n const data = await fetchResponse.json();\n\n if (data.error) {\n // TODO\n console.log('TODO handle parseResponse error');\n console.dir(data);\n throw data;\n }\n\n return data;\n}\n"],"mappings":"AAAA,SAASA,UAAU,EAAEC,QAAQ,QAAQ,mBAAmB;AAGxD,OAAO,eAAeC,aAAaA,CAC/BC,gBAA+C,EAC/CC,aAAuB,EACzB;EACE,IAAIA,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACG,eAAe,CAACC,IAAI,CAAC,CAAC;IACvCN,QAAQ,CAAC,CAAC,CAACO,IAAI,CAAC,MAAML,gBAAgB,CAACM,MAAM,CAAC,CAAC,CAAC;IAChD,MAAMT,UAAU,CAAC,aAAa,EAAE;MAC5BU,GAAG,EAAEN,aAAa,CAACM;IACvB,CAAC,CAAC;EACN;EACA,IAAIN,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACQ,aAAa,CAACJ,IAAI,CAAC,CAAC;IACrC,MAAMP,UAAU,CAAC,iBAAiB,EAAE;MAChCU,GAAG,EAAEN,aAAa,CAACM;IACvB,CAAC,CAAC;EACN;EACA,IAAIN,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACS,UAAU,CAACL,IAAI,CAAC,CAAC;IAClCN,QAAQ,CAAC,CAAC,CAACO,IAAI,CAAC,MAAML,gBAAgB,CAACM,MAAM,CAAC,CAAC,CAAC;IAChD,MAAMT,UAAU,CAAC,cAAc,EAAE;MAC7BU,GAAG,EAAEN,aAAa,CAACM;IACvB,CAAC,CAAC;EACN;EACA,IAAMG,IAAI,GAAG,MAAMT,aAAa,CAACU,IAAI,CAAC,CAAC;EAEvC,IAAID,IAAI,CAACE,KAAK,EAAE;IACZ;IACAC,OAAO,CAACC,GAAG,CAAC,iCAAiC,CAAC;IAC9CD,OAAO,CAACE,GAAG,CAACL,IAAI,CAAC;IACjB,MAAMA,IAAI;EACd;EAEA,OAAOA,IAAI;AACf"}
|
|
1
|
+
{"version":3,"file":"helpers.js","names":["newRxError","nextTick","parseResponse","replicationState","fetchResponse","status","outdatedClient$","next","then","cancel","url","unauthorized$","forbidden$","data","json","error","console","log","dir"],"sources":["../../../../src/plugins/replication-server/helpers.ts"],"sourcesContent":["import { newRxError, nextTick } from 'rxdb/plugins/core';\nimport type { RxServerReplicationState } from './index.ts';\n\nexport async function parseResponse(\n replicationState: RxServerReplicationState<any>,\n fetchResponse: Response\n) {\n if (fetchResponse.status === 426) {\n replicationState.outdatedClient$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_OUTDATED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 401) {\n replicationState.unauthorized$.next();\n throw newRxError('RC_UNAUTHORIZED', {\n url: fetchResponse.url\n });\n }\n if (fetchResponse.status === 403) {\n replicationState.forbidden$.next();\n nextTick().then(() => replicationState.cancel());\n throw newRxError('RC_FORBIDDEN', {\n url: fetchResponse.url\n });\n }\n const data = await fetchResponse.json();\n\n if (data.error) {\n // TODO\n console.log('TODO handle parseResponse error');\n console.dir(data);\n throw data;\n }\n\n return data;\n}\n"],"mappings":"AAAA,SAASA,UAAU,EAAEC,QAAQ,QAAQ,mBAAmB;AAGxD,OAAO,eAAeC,aAAaA,CAC/BC,gBAA+C,EAC/CC,aAAuB,EACzB;EACE,IAAIA,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACG,eAAe,CAACC,IAAI,CAAC,CAAC;IACvCN,QAAQ,CAAC,CAAC,CAACO,IAAI,CAAC,MAAML,gBAAgB,CAACM,MAAM,CAAC,CAAC,CAAC;IAChD,MAAMT,UAAU,CAAC,aAAa,EAAE;MAC5BU,GAAG,EAAEN,aAAa,CAACM;IACvB,CAAC,CAAC;EACN;EACA,IAAIN,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACQ,aAAa,CAACJ,IAAI,CAAC,CAAC;IACrC,MAAMP,UAAU,CAAC,iBAAiB,EAAE;MAChCU,GAAG,EAAEN,aAAa,CAACM;IACvB,CAAC,CAAC;EACN;EACA,IAAIN,aAAa,CAACC,MAAM,KAAK,GAAG,EAAE;IAC9BF,gBAAgB,CAACS,UAAU,CAACL,IAAI,CAAC,CAAC;IAClCN,QAAQ,CAAC,CAAC,CAACO,IAAI,CAAC,MAAML,gBAAgB,CAACM,MAAM,CAAC,CAAC,CAAC;IAChD,MAAMT,UAAU,CAAC,cAAc,EAAE;MAC7BU,GAAG,EAAEN,aAAa,CAACM;IACvB,CAAC,CAAC;EACN;EACA,IAAMG,IAAI,GAAG,MAAMT,aAAa,CAACU,IAAI,CAAC,CAAC;EAEvC,IAAID,IAAI,CAACE,KAAK,EAAE;IACZ;IACAC,OAAO,CAACC,GAAG,CAAC,iCAAiC,CAAC;IAC9CD,OAAO,CAACE,GAAG,CAACL,IAAI,CAAC;IACjB,MAAMA,IAAI;EACd;EAEA,OAAOA,IAAI;AACf","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","promiseWait","addRxPlugin","newRxError","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","Subject","parseResponse","EventSource","RxServerReplicationState","_RxReplicationState","_inheritsLoose","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","call","outdatedClient$","unauthorized$","forbidden$","onCancel","complete","_proto","prototype","setHeaders","replicateServer","options","name","args","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","Object","assign","replicationState","data","documents","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","refreshEventSource","withCredentials","onerror","err","status","next","close","then","onopen","x","onmessage","event","eventData","parse"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n RxStorageDefaultCheckpoint,\n ById,\n addRxPlugin, \n newRxError\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport { ServerSyncOptions } from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport EventSource from 'eventsource';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxStorageDefaultCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxStorageDefaultCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\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<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\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 = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: replicationState.headers\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.status === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,EAOXC,WAAW,EACXC,UAAU,QACP,mBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,8BAA8B;AACvE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,0BAA0B;AAEjC,SAASC,OAAO,QAAQ,MAAM;AAE9B,SAASC,aAAa,QAAQ,cAAc;AAC5C,OAAOC,WAAW,MAAM,aAAa;AAErC,cAAc,YAAY;AAE1B,WAAaC,wBAAwB,0BAAAC,mBAAA;EAAAC,cAAA,CAAAF,wBAAA,EAAAC,mBAAA;EAKjC,SAAAD,yBACoBG,qBAA6B,EAC7BC,UAAmC,EACnCC,IAAoE,EAC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AAW,CAACoC,IAAI,CAAC,QAAQ,CAAC;QAC9B,CAAC;QACDN,WAAW,CAACW,SAAS,GAAGC,KAAK,IAAI;UAC7B,IAAMC,SAAS,GAAGpB,IAAI,CAACqB,KAAK,CAACF,KAAK,CAAC5B,IAAI,CAAC;UACxCd,WAAW,CAACoC,IAAI,CAAC;YACbrB,SAAS,EAAE4B,SAAS,CAAC5B,SAAS;YAC9BC,UAAU,EAAE2B,SAAS,CAAC3B;UAC1B,CAAC,CAAC;QACN,CAAC;MACL,CAAC;MACDe,kBAAkB,CAAC,CAAC;MAEpBlB,gBAAgB,CAACvB,QAAQ,CAACV,IAAI,CAAC,MAAMkD,WAAW,IAAIA,WAAW,CAACO,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOX,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEAxD,4BAA4B,CAAC0B,OAAO,CAACG,iBAAiB,EAAEc,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","promiseWait","addRxPlugin","newRxError","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","Subject","parseResponse","EventSource","RxServerReplicationState","_RxReplicationState","_inheritsLoose","replicationIdentifier","collection","pull","push","live","retryTime","autoStart","headers","_this","call","outdatedClient$","unauthorized$","forbidden$","onCancel","complete","_proto","prototype","setHeaders","replicateServer","options","name","args","waitForLeadership","pullStream$","replicationPrimitivesPull","handler","checkpointOrNull","batchSize","lwt","id","url","response","fetch","method","Object","assign","replicationState","data","documents","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","changeRows","body","JSON","stringify","conflictsArray","startBefore","start","bind","useEventSource","eventSource","refreshEventSource","withCredentials","onerror","err","status","next","close","then","onopen","x","onmessage","event","eventData","parse"],"sources":["../../../../src/plugins/replication-server/index.ts"],"sourcesContent":["import {\n ensureNotFalsy,\n flatClone,\n promiseWait,\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationPullStreamItem,\n RxStorageDefaultCheckpoint,\n ById,\n addRxPlugin, \n newRxError\n} from 'rxdb/plugins/core';\nimport { RxDBLeaderElectionPlugin } from 'rxdb/plugins/leader-election';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from 'rxdb/plugins/replication';\n\nimport { Subject } from 'rxjs';\nimport { ServerSyncOptions } from './types.ts';\nimport { parseResponse } from './helpers.ts';\nimport EventSource from 'eventsource';\n\nexport * from './types.ts';\n\nexport class RxServerReplicationState<RxDocType> extends RxReplicationState<RxDocType, RxStorageDefaultCheckpoint> {\n public readonly outdatedClient$ = new Subject<void>();\n public readonly unauthorized$ = new Subject<void>();\n public readonly forbidden$ = new Subject<void>();\n\n constructor(\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection<RxDocType>,\n public readonly pull?: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>,\n public readonly push?: ReplicationPushOptions<RxDocType>,\n public readonly live: boolean = true,\n public retryTime: number = 1000 * 5,\n public autoStart: boolean = true,\n public headers: ById<string> = {}\n ) {\n super(\n replicationIdentifier,\n collection,\n '_deleted',\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n this.onCancel.push(() => {\n this.outdatedClient$.complete();\n this.unauthorized$.complete();\n this.forbidden$.complete();\n });\n }\n\n setHeaders(headers: ById<string>): void {\n this.headers = flatClone(headers);\n }\n}\n\nexport function replicateServer<RxDocType>(\n options: ServerSyncOptions<RxDocType>\n): RxServerReplicationState<RxDocType> {\n\n if (!options.pull && !options.push) {\n throw newRxError('UT3', {\n collection: options.collection.name,\n args: {\n replicationIdentifier: options.replicationIdentifier\n }\n });\n }\n\n options.live = typeof options.live === 'undefined' ? true : options.live;\n options.waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n\n const collection = options.collection;\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n const pullStream$: Subject<RxReplicationPullStreamItem<RxDocType, RxStorageDefaultCheckpoint>> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint> | undefined;\n if (options.pull) {\n replicationPrimitivesPull = {\n async handler(checkpointOrNull, batchSize) {\n const lwt = checkpointOrNull && checkpointOrNull.lwt ? checkpointOrNull.lwt : 0;\n const id = checkpointOrNull && checkpointOrNull.id ? checkpointOrNull.id : '';\n const url = options.url + `/pull?lwt=${lwt}&id=${id}&limit=${batchSize}`;\n const response = await fetch(url, {\n method: 'GET',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n });\n const data = await await parseResponse(replicationState, response);\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\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<RxDocType> | undefined;\n if (options.push) {\n replicationPrimitivesPush = {\n async handler(changeRows) {\n const response = await fetch(options.url + '/push', {\n method: 'POST',\n headers: Object.assign({\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }, replicationState.headers),\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await parseResponse(replicationState, response);\n return conflictsArray;\n },\n batchSize: options.push.batchSize,\n modifier: options.push.modifier\n };\n }\n\n const replicationState = new RxServerReplicationState<RxDocType>(\n options.replicationIdentifier,\n collection,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n options.live,\n options.retryTime,\n options.autoStart,\n options.headers\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 = async () => {\n const useEventSource: typeof EventSource = options.eventSource ? options.eventSource : EventSource;\n let eventSource: EventSource;\n const refreshEventSource = () => {\n eventSource = new useEventSource(options.url + '/pullStream', {\n withCredentials: true,\n /**\n * Sending headers is not supported by the Browser EventSource API,\n * only by the npm module we use. In react-native you might have\n * to set another EventSource implementation.\n * @link https://www.npmjs.com/package/eventsource\n */\n headers: replicationState.headers\n });\n // TODO check for 426 errors and handle them\n eventSource.onerror = (err) => {\n if (err.status === 401) {\n replicationState.unauthorized$.next();\n eventSource.close();\n promiseWait(replicationState.retryTime).then(() => refreshEventSource());\n } else {\n pullStream$.next('RESYNC');\n }\n };\n eventSource.onopen = (x) => {\n pullStream$.next('RESYNC');\n }\n eventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n pullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n };\n }\n refreshEventSource();\n\n replicationState.onCancel.push(() => eventSource && eventSource.close());\n return startBefore();\n };\n }\n\n startReplicationOnLeaderShip(options.waitForLeadership, replicationState);\n\n return replicationState;\n}\n"],"mappings":";AAAA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,EAOXC,WAAW,EACXC,UAAU,QACP,mBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,8BAA8B;AACvE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,0BAA0B;AAEjC,SAASC,OAAO,QAAQ,MAAM;AAE9B,SAASC,aAAa,QAAQ,cAAc;AAC5C,OAAOC,WAAW,MAAM,aAAa;AAErC,cAAc,YAAY;AAE1B,WAAaC,wBAAwB,0BAAAC,mBAAA;EAAAC,cAAA,CAAAF,wBAAA,EAAAC,mBAAA;EAKjC,SAAAD,yBACoBG,qBAA6B,EAC7BC,UAAmC,EACnCC,IAAoE,EACpEC,IAAwC,EACxCC,IAAa,GAAG,IAAI,EAC7BC,SAAiB,GAAG,IAAI,GAAG,CAAC,EAC5BC,SAAkB,GAAG,IAAI,EACzBC,OAAqB,GAAG,CAAC,CAAC,EACnC;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAV,mBAAA,CAAAW,IAAA,OACIT,qBAAqB,EACrBC,UAAU,EACV,UAAU,EACVC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAA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;QACN,CAAC;MACL,CAAC;MACDe,kBAAkB,CAAC,CAAC;MAEpBlB,gBAAgB,CAACvB,QAAQ,CAACV,IAAI,CAAC,MAAMkD,WAAW,IAAIA,WAAW,CAACO,KAAK,CAAC,CAAC,CAAC;MACxE,OAAOX,WAAW,CAAC,CAAC;IACxB,CAAC;EACL;EAEAxD,4BAA4B,CAAC0B,OAAO,CAACG,iBAAiB,EAAEc,gBAAgB,CAAC;EAEzE,OAAOA,gBAAgB;AAC3B","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/replication-server/types.ts"],"sourcesContent":["import type {\n MaybePromise,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxStorageDefaultCheckpoint\n} from 'rxdb/plugins/core';\n\nexport type ServerSyncPullOptions<RxDocType> =\n Omit<ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>, 'handler' | 'stream$'>\n & {\n };\n\nexport type ServerSyncPushOptions<RxDocType> = Omit<ReplicationPushOptions<RxDocType>, 'handler'>\n & {\n};\n\nexport type ServerSyncOptions<RxDocType> = Omit<\n ReplicationOptions<RxDocType, any>,\n 'pull' | 'push'\n> & {\n url: string;\n headers?: { [k: string]: string };\n pull?: ServerSyncPullOptions<RxDocType>;\n push?: ServerSyncPushOptions<RxDocType>;\n\n /**\n * If the EventSource API is not available\n * on the runtime, pass an own implementation here.\n * Mostly used with the \"eventsource\" npm package on Node.js.\n */\n eventSource?: typeof EventSource | any\n};\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/replication-server/types.ts"],"sourcesContent":["import type {\n MaybePromise,\n ReplicationOptions,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxStorageDefaultCheckpoint\n} from 'rxdb/plugins/core';\n\nexport type ServerSyncPullOptions<RxDocType> =\n Omit<ReplicationPullOptions<RxDocType, RxStorageDefaultCheckpoint>, 'handler' | 'stream$'>\n & {\n };\n\nexport type ServerSyncPushOptions<RxDocType> = Omit<ReplicationPushOptions<RxDocType>, 'handler'>\n & {\n};\n\nexport type ServerSyncOptions<RxDocType> = Omit<\n ReplicationOptions<RxDocType, any>,\n 'pull' | 'push'\n> & {\n url: string;\n headers?: { [k: string]: string };\n pull?: ServerSyncPullOptions<RxDocType>;\n push?: ServerSyncPushOptions<RxDocType>;\n\n /**\n * If the EventSource API is not available\n * on the runtime, pass an own implementation here.\n * Mostly used with the \"eventsource\" npm package on Node.js.\n */\n eventSource?: typeof EventSource | any\n};\n"],"mappings":"","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-replication.js","names":["prepareQuery","getChangedDocumentsSinceQuery","getReplicationHandlerByCollection","filter","mergeMap","ensureNotFalsy","getFromMapOrThrow","lastOfArray","addAuthMiddleware","blockPreviousVersionPaths","closeConnection","docContainsServerOnlyFields","doesContainRegexQuerySelector","getDocAllowedMatcher","mergeServerDocumentFieldsMonad","removeServerOnlyFieldsMonad","setCors","writeSSEHeaders","RxServerReplicationEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","join","schema","version","urlPath","primaryPath","replicationHandler","database","authDataByRequest","authData","query","selector","Error","change","assumedMasterState","newDocumentState","removeServerOnlyFields","mergeServerDocumentFields","expressApp","get","req","res","id","lwt","parseInt","limit","plainQuery","storageInstance","useQueryChanges","prepared","jsonSchema","result","newCheckpoint","documents","length","updatedAt","_meta","responseDocuments","map","d","setHeader","json","checkpoint","post","docDataMatcherWrite","rows","body","ids","forEach","row","push","nonAllowedRow","find","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","docDataMatcherStream","subscription","masterChangeStream$","pipe","changes","authHandler","headers","err","useDocs","f","subscribe","filteredAndModified","write","JSON","stringify","on","unsubscribe","end"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageDefaultCheckpoint,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler = getReplicationHandlerByCollection(this.server.database, collection.name);\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.expressApp.get('/' + this.urlPath + '/pull', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const id = req.query.id ? req.query.id as string : '';\n const lwt = req.query.lwt ? parseInt(req.query.lwt as any, 10) : 0;\n const limit = req.query.limit ? parseInt(req.query.limit as any, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxStorageDefaultCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath],\n updatedAt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n this.server.expressApp.post('/' + this.urlPath + '/push', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = req.body;\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n res.setHeader('Content-Type', 'application/json');\n res.json(conflicts);\n });\n this.server.expressApp.get('/' + this.urlPath + '/pullStream', async (req, res) => {\n writeSSEHeaders(res);\n\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n res.write('data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n res.write('data: ' + JSON.stringify({ documents: responseDocuments, checkpoint: ensureNotFalsy(filteredAndModified).checkpoint }) + '\\n\\n');\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n }\n}\n"],"mappings":"AAAA,SAOIA,YAAY,EACZC,6BAA6B,QAE1B,mBAAmB;AAC1B,SAASC,iCAAiC,QAAQ,oCAAoC;AAQtF,SAASC,MAAM,EAAEC,QAAQ,QAAQ,MAAM;AACvC,SACIC,cAAc,EACdC,iBAAiB,EACjBC,WAAW,QACR,oBAAoB;AAE3B,SACIC,iBAAiB,EACjBC,yBAAyB,EACzBC,eAAe,EACfC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,oBAAoB,EACpBC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,OAAO,EACPC,eAAe,QACZ,aAAa;AAQpB,WAAaC,2BAA2B,GAKpC,SAAAA,4BACoBC,MAA0B,EAC1BC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,eAA6D,EAC7CC,gBAA0B,EAC1BC,IAAa,EAC/B;EAAA,KAZOC,IAAI,GAAG,aAAa;EAAA,KAKTP,MAA0B,GAA1BA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AAG,CAAC4D,GAAG,CAAC,CAAC;IACb,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC"}
|
|
1
|
+
{"version":3,"file":"endpoint-replication.js","names":["prepareQuery","getChangedDocumentsSinceQuery","getReplicationHandlerByCollection","filter","mergeMap","ensureNotFalsy","getFromMapOrThrow","lastOfArray","addAuthMiddleware","blockPreviousVersionPaths","closeConnection","docContainsServerOnlyFields","doesContainRegexQuerySelector","getDocAllowedMatcher","mergeServerDocumentFieldsMonad","removeServerOnlyFieldsMonad","setCors","writeSSEHeaders","RxServerReplicationEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","type","join","schema","version","urlPath","primaryPath","replicationHandler","database","authDataByRequest","authData","query","selector","Error","change","assumedMasterState","newDocumentState","removeServerOnlyFields","mergeServerDocumentFields","expressApp","get","req","res","id","lwt","parseInt","limit","plainQuery","storageInstance","useQueryChanges","prepared","jsonSchema","result","newCheckpoint","documents","length","updatedAt","_meta","responseDocuments","map","d","setHeader","json","checkpoint","post","docDataMatcherWrite","rows","body","ids","forEach","row","push","nonAllowedRow","find","hasInvalidChange","currentStateDocsArray","findDocumentsById","currentStateDocs","Map","set","useRows","isChangeValid","serverDoc","conflicts","masterWrite","docDataMatcherStream","subscription","masterChangeStream$","pipe","changes","authHandler","headers","err","useDocs","f","subscribe","filteredAndModified","write","JSON","stringify","on","unsubscribe","end"],"sources":["../../../../src/plugins/server/endpoint-replication.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageDefaultCheckpoint,\n StringKeys,\n prepareQuery,\n getChangedDocumentsSinceQuery,\n RxDocumentData\n} from 'rxdb/plugins/core';\nimport { getReplicationHandlerByCollection } from 'rxdb/plugins/replication-websocket';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerAuthData,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow,\n lastOfArray\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n mergeServerDocumentFieldsMonad,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\nexport type RxReplicationEndpointMessageType = {\n id: string;\n method: StringKeys<RxReplicationHandler<any, any>> | 'auth';\n params: any[];\n};\n\nexport class RxServerReplicationEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'replication';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string,\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n\n const primaryPath = this.collection.schema.primaryPath;\n const replicationHandler = getReplicationHandlerByCollection(this.server.database, collection.name);\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (change.assumedMasterState && docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad<RxDocType>(this.serverOnlyFields);\n const mergeServerDocumentFields = mergeServerDocumentFieldsMonad<RxDocType>(this.serverOnlyFields);\n\n this.server.expressApp.get('/' + this.urlPath + '/pull', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const id = req.query.id ? req.query.id as string : '';\n const lwt = req.query.lwt ? parseInt(req.query.lwt as any, 10) : 0;\n const limit = req.query.limit ? parseInt(req.query.limit as any, 10) : 1;\n const plainQuery = getChangedDocumentsSinceQuery<RxDocType, RxStorageDefaultCheckpoint>(\n this.collection.storageInstance,\n limit,\n { id, lwt }\n );\n const useQueryChanges: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n plainQuery\n );\n const prepared = prepareQuery<RxDocType>(\n this.collection.schema.jsonSchema,\n useQueryChanges\n );\n const result = await this.collection.storageInstance.query(prepared);\n\n const newCheckpoint = result.documents.length === 0 ? { id, lwt } : {\n id: ensureNotFalsy(lastOfArray(result.documents))[primaryPath],\n updatedAt: ensureNotFalsy(lastOfArray(result.documents))._meta.lwt\n };\n const responseDocuments = result.documents.map(d => removeServerOnlyFields(d));\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: responseDocuments,\n checkpoint: newCheckpoint\n });\n });\n this.server.expressApp.post('/' + this.urlPath + '/push', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const rows: RxReplicationWriteToMasterRow<RxDocType>[] = req.body;\n const ids: string[] = [];\n rows.forEach(row => ids.push((row.newDocumentState as any)[primaryPath]));\n\n for (const row of rows) {\n // TODO remove this check\n if (row.assumedMasterState && (row.assumedMasterState as any)._meta) {\n throw new Error('body document contains meta!');\n }\n }\n\n // ensure all writes are allowed\n const nonAllowedRow = rows.find(row => {\n if (\n !docDataMatcherWrite(row.newDocumentState as any) ||\n (row.assumedMasterState && !docDataMatcherWrite(row.assumedMasterState as any))\n ) {\n return true;\n }\n });\n if (nonAllowedRow) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n let hasInvalidChange = false;\n\n const currentStateDocsArray = await this.collection.storageInstance.findDocumentsById(ids, true);\n const currentStateDocs = new Map<string, RxDocumentData<RxDocType>>();\n currentStateDocsArray.forEach(d => currentStateDocs.set((d as any)[primaryPath], d));\n\n const useRows: typeof rows = rows.map((row) => {\n const id = (row.newDocumentState as any)[primaryPath];\n const isChangeValid = this.changeValidator(ensureNotFalsy(authData), {\n newDocumentState: removeServerOnlyFields(row.newDocumentState),\n assumedMasterState: removeServerOnlyFields(row.assumedMasterState)\n });\n if (!isChangeValid) {\n hasInvalidChange = true;\n }\n\n const serverDoc = currentStateDocs.get(id);\n return {\n newDocumentState: mergeServerDocumentFields(row.newDocumentState, serverDoc),\n assumedMasterState: mergeServerDocumentFields(row.assumedMasterState as any, serverDoc)\n } as typeof row;\n });\n if (hasInvalidChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const conflicts = await replicationHandler.masterWrite(useRows);\n\n res.setHeader('Content-Type', 'application/json');\n res.json(conflicts);\n });\n this.server.expressApp.get('/' + this.urlPath + '/pullStream', async (req, res) => {\n writeSSEHeaders(res);\n\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherStream = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n const subscription = replicationHandler.masterChangeStream$.pipe(\n mergeMap(async (changes) => {\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting an event.\n */\n let authData: RxServerAuthData<AuthType>;\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n if (changes === 'RESYNC') {\n return changes;\n } else {\n const useDocs = changes.documents.filter(d => docDataMatcherStream(d as any));\n return {\n documents: useDocs,\n checkpoint: changes.checkpoint\n };\n }\n }),\n filter(f => f !== null && (f === 'RESYNC' || f.documents.length > 0))\n ).subscribe(filteredAndModified => {\n if (filteredAndModified === 'RESYNC') {\n res.write('data: ' + JSON.stringify(filteredAndModified) + '\\n\\n');\n } else {\n const responseDocuments = ensureNotFalsy(filteredAndModified).documents.map(d => removeServerOnlyFields(d as any));\n res.write('data: ' + JSON.stringify({ documents: responseDocuments, checkpoint: ensureNotFalsy(filteredAndModified).checkpoint }) + '\\n\\n');\n }\n\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n }\n}\n"],"mappings":"AAAA,SAOIA,YAAY,EACZC,6BAA6B,QAE1B,mBAAmB;AAC1B,SAASC,iCAAiC,QAAQ,oCAAoC;AAQtF,SAASC,MAAM,EAAEC,QAAQ,QAAQ,MAAM;AACvC,SACIC,cAAc,EACdC,iBAAiB,EACjBC,WAAW,QACR,oBAAoB;AAE3B,SACIC,iBAAiB,EACjBC,yBAAyB,EACzBC,eAAe,EACfC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,oBAAoB,EACpBC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,OAAO,EACPC,eAAe,QACZ,aAAa;AAQpB,WAAaC,2BAA2B,GAKpC,SAAAA,4BACoBC,MAA0B,EAC1BC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,eAA6D,EAC7CC,gBAA0B,EAC1BC,IAAa,EAC/B;EAAA,KAZOC,IAAI,GAAG,aAAa;EAAA,KAKTP,MAA0B,GAA1BA,MAA0B;EAAA,KAC1BC,IAAY,GAAZA,IAAY;EAAA,KACZC,UAAmC,GAAnCA,UAAmC;EAAA,KAGnCG,gBAA0B,GAA1BA,gBAA0B;EAAA,KAC1BC,IAAa,GAAbA,IAAa;EAE7BT,OAAO,CAAC,IAAI,CAACG,MAAM,EAAE,CAAC,IAAI,CAACC,IAAI,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC,EAAEF,IAAI,CAAC;EACjDhB,yBAAyB,CAAC,IAAI,CAACU,MAAM,EAAE,CAAC,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C,OAAO;UAClB9B,UAAU,EAAE0B,OAAO,CAAC1B;QACxB,CAAC;MACL;IACJ,CAAC,CAAC,EACFjE,MAAM,CAACgG,CAAC,IAAIA,CAAC,KAAK,IAAI,KAAKA,CAAC,KAAK,QAAQ,IAAIA,CAAC,CAACxC,SAAS,CAACC,MAAM,GAAG,CAAC,CAAC,CACxE,CAAC,CAACwC,SAAS,CAACC,mBAAmB,IAAI;MAC/B,IAAIA,mBAAmB,KAAK,QAAQ,EAAE;QAClCtD,GAAG,CAACuD,KAAK,CAAC,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAACH,mBAAmB,CAAC,GAAG,MAAM,CAAC;MACtE,CAAC,MAAM;QACH,IAAMtC,iBAAiB,GAAG1D,cAAc,CAACgG,mBAAmB,CAAC,CAAC1C,SAAS,CAACK,GAAG,CAACC,CAAC,IAAIvB,sBAAsB,CAACuB,CAAQ,CAAC,CAAC;QAClHlB,GAAG,CAACuD,KAAK,CAAC,QAAQ,GAAGC,IAAI,CAACC,SAAS,CAAC;UAAE7C,SAAS,EAAEI,iBAAiB;UAAEK,UAAU,EAAE/D,cAAc,CAACgG,mBAAmB,CAAC,CAACjC;QAAW,CAAC,CAAC,GAAG,MAAM,CAAC;MAC/I;IAEJ,CAAC,CAAC;;IAEF;AACZ;AACA;IACYtB,GAAG,CAAC2D,EAAE,CAAC,OAAO,EAAE,MAAM;MAClBd,YAAY,CAACe,WAAW,CAAC,CAAC;MAC1B3D,GAAG,CAAC4D,GAAG,CAAC,CAAC;IACb,CAAC,CAAC;EACN,CAAC,CAAC;AACN,CAAC","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint-rest.js","names":["normalizeMangoQuery","filter","mergeMap","ensureNotFalsy","getFromMapOrThrow","addAuthMiddleware","blockPreviousVersionPaths","closeConnection","docContainsServerOnlyFields","doesContainRegexQuerySelector","getDocAllowedMatcher","removeServerOnlyFieldsMonad","setCors","writeSSEHeaders","REST_PATHS","RxServerRestEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","_this","type","join","schema","version","urlPath","primaryPath","authDataByRequest","authData","query","selector","Error","change","assumedMasterState","newDocumentState","removeServerOnlyFields","expressApp","post","req","res","useQuery","jsonSchema","body","err","rxQuery","find","result","exec","setHeader","json","documents","map","d","toJSON","get","JSON","parse","atob","subscription","$","pipe","resultData","doc","authHandler","headers","f","subscribe","write","stringify","on","unsubscribe","end","ids","findByIds","resultMap","resultValues","Array","from","values","docMatcher","useDocs","docDataMatcherWrite","docsData","docData","allowed","onWriteError","rxdb","code","push","length","promises","docs","useDocsData","slice","_loop","_docData","id","insert","catch","isAllowed","v","patch","_ret","Promise","all","useIds","docsMap","_loop2","isAllowedDoc","isAllowedChange","remove","_ret2"],"sources":["../../../../src/plugins/server/endpoint-rest.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxError,\n normalizeMangoQuery\n} from 'rxdb/plugins/core';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\n\nexport const REST_PATHS = [\n 'query',\n 'query/observe',\n 'get',\n 'set',\n 'delete',\n\n // TODO\n /*\n 'attachments/add',\n 'attachments/delete',\n 'events'\n */\n] as const;\n\n\nexport class RxServerRestEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'rest';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n const primaryPath = this.collection.schema.primaryPath;\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (\n change.assumedMasterState &&\n docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)\n ) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad(this.serverOnlyFields);\n\n this.server.expressApp.post('/' + this.urlPath + '/query', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n let useQuery: FilledMangoQuery<RxDocType>\n try {\n useQuery = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n req.body\n )\n );\n } catch (err) {\n closeConnection(res, 400, 'Bad Request');\n return;\n }\n const rxQuery = this.collection.find(useQuery as any);\n const result = await rxQuery.exec();\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: result.map(d => removeServerOnlyFields(d.toJSON()))\n });\n });\n\n /**\n * It is not possible to send data with server send events,\n * so we send the query as query parameter in base64\n * like ?query=e3NlbGVjdG9yOiB7fX0=\n */\n this.server.expressApp.get('/' + this.urlPath + '/query/observe', async (req, res) => {\n let authData = getFromMapOrThrow(authDataByRequest, req);\n writeSSEHeaders(res);\n\n const useQuery: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n JSON.parse(atob(req.query.query as string))\n )\n );\n\n const rxQuery = this.collection.find(useQuery as any);\n const subscription = rxQuery.$.pipe(\n mergeMap(async (result) => {\n const resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));\n\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting the new results.\n */\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n return resultData;\n }),\n filter(f => f !== null)\n ).subscribe(resultData => {\n res.write('data: ' + JSON.stringify(resultData) + '\\n\\n');\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n\n\n this.server.expressApp.post('/' + this.urlPath + '/get', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const ids: string[] = req.body;\n\n const rxQuery = this.collection.findByIds(ids);\n const resultMap = await rxQuery.exec();\n const resultValues = Array.from(resultMap.values());\n const docMatcher = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n let useDocs = resultValues.map(d => d.toJSON());\n useDocs = useDocs.filter(d => docMatcher(d as any));\n useDocs = useDocs.map(d => removeServerOnlyFields(d))\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: useDocs\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/set', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let docsData: RxDocType[] = req.body;\n\n for (const docData of docsData) {\n const allowed = docDataMatcherWrite(docData as any);\n if (!allowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n }\n\n function onWriteError(err: RxError, docData: RxDocType) {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n docsData.push(docData);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }\n\n while (docsData.length > 0) {\n const promises: Promise<any>[] = [];\n const docs = await collection.findByIds(docsData.map(d => (d as any)[primaryPath])).exec();\n let useDocsData = docsData.slice();\n docsData = [];\n for (const docData of useDocsData) {\n const id = (docData as any)[primaryPath];\n const doc = docs.get(id);\n if (!doc) {\n promises.push(this.collection.insert(docData).catch(err => onWriteError(err, docData)));\n } else {\n const isAllowed = this.changeValidator(authData, {\n newDocumentState: removeServerOnlyFields(docData as any),\n assumedMasterState: removeServerOnlyFields(doc.toJSON(true))\n });\n if (!isAllowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n promises.push(doc.patch(docData).catch(err => onWriteError(err, docData)));\n }\n }\n await Promise.all(promises);\n }\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/delete', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let ids: string[] = req.body;\n while (ids.length > 0) {\n const useIds = ids.slice(0);\n ids = [];\n const promises: Promise<any>[] = [];\n const docsMap = await this.collection.findByIds(useIds).exec();\n for (const id of useIds) {\n const doc = docsMap.get(id);\n if (doc) {\n const isAllowedDoc = docDataMatcherWrite(doc.toJSON(true) as any);\n if (!isAllowedDoc) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const isAllowedChange = this.changeValidator(authData, {\n newDocumentState: doc.toJSON(true) as any,\n assumedMasterState: doc.toJSON(true) as any\n });\n if (!isAllowedChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n promises.push(doc.remove().catch((err: RxError) => {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n ids.push(id);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }));\n }\n }\n await Promise.all(promises);\n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B,CAAC;IACjDT,GAAG,CAACU,IAAI,CAAC,CAAC,CAAC,CAAC;EAChB,CAAC,CAAC;AACN,CAAC"}
|
|
1
|
+
{"version":3,"file":"endpoint-rest.js","names":["normalizeMangoQuery","filter","mergeMap","ensureNotFalsy","getFromMapOrThrow","addAuthMiddleware","blockPreviousVersionPaths","closeConnection","docContainsServerOnlyFields","doesContainRegexQuerySelector","getDocAllowedMatcher","removeServerOnlyFieldsMonad","setCors","writeSSEHeaders","REST_PATHS","RxServerRestEndpoint","server","name","collection","queryModifier","changeValidator","serverOnlyFields","cors","_this","type","join","schema","version","urlPath","primaryPath","authDataByRequest","authData","query","selector","Error","change","assumedMasterState","newDocumentState","removeServerOnlyFields","expressApp","post","req","res","useQuery","jsonSchema","body","err","rxQuery","find","result","exec","setHeader","json","documents","map","d","toJSON","get","JSON","parse","atob","subscription","$","pipe","resultData","doc","authHandler","headers","f","subscribe","write","stringify","on","unsubscribe","end","ids","findByIds","resultMap","resultValues","Array","from","values","docMatcher","useDocs","docDataMatcherWrite","docsData","docData","allowed","onWriteError","rxdb","code","push","length","promises","docs","useDocsData","slice","_loop","_docData","id","insert","catch","isAllowed","v","patch","_ret","Promise","all","useIds","docsMap","_loop2","isAllowedDoc","isAllowedChange","remove","_ret2"],"sources":["../../../../src/plugins/server/endpoint-rest.ts"],"sourcesContent":["import {\n FilledMangoQuery,\n RxCollection,\n RxError,\n normalizeMangoQuery\n} from 'rxdb/plugins/core';\nimport type { RxServer } from './rx-server.ts';\nimport type {\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport { filter, mergeMap } from 'rxjs';\nimport {\n ensureNotFalsy,\n getFromMapOrThrow\n} from 'rxdb/plugins/utils';\n\nimport {\n addAuthMiddleware,\n blockPreviousVersionPaths,\n closeConnection,\n docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n removeServerOnlyFieldsMonad,\n setCors,\n writeSSEHeaders\n} from './helper.ts';\n\n\nexport const REST_PATHS = [\n 'query',\n 'query/observe',\n 'get',\n 'set',\n 'delete',\n\n // TODO\n /*\n 'attachments/add',\n 'attachments/delete',\n 'events'\n */\n] as const;\n\n\nexport class RxServerRestEndpoint<AuthType, RxDocType> implements RxServerEndpoint<AuthType, RxDocType> {\n readonly type = 'rest';\n readonly urlPath: string;\n readonly changeValidator: RxServerChangeValidator<AuthType, RxDocType>;\n readonly queryModifier: RxServerQueryModifier<AuthType, RxDocType>;\n constructor(\n public readonly server: RxServer<AuthType>,\n public readonly name: string,\n public readonly collection: RxCollection<RxDocType>,\n queryModifier: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator: RxServerChangeValidator<AuthType, RxDocType>,\n public readonly serverOnlyFields: string[],\n public readonly cors?: string\n ) {\n setCors(this.server, [this.name].join('/'), cors);\n blockPreviousVersionPaths(this.server, [this.name].join('/'), collection.schema.version);\n\n this.urlPath = [this.name, collection.schema.version].join('/');\n const primaryPath = this.collection.schema.primaryPath;\n const authDataByRequest = addAuthMiddleware(\n this.server,\n this.urlPath\n );\n\n this.queryModifier = (authData, query) => {\n if (doesContainRegexQuerySelector(query.selector)) {\n throw new Error('$regex queries not allowed because of DOS-attacks');\n }\n return queryModifier(authData, query);\n }\n this.changeValidator = (authData, change) => {\n if (\n (\n change.assumedMasterState &&\n docContainsServerOnlyFields(serverOnlyFields, change.assumedMasterState)\n ) ||\n docContainsServerOnlyFields(serverOnlyFields, change.newDocumentState)\n ) {\n return false;\n }\n return changeValidator(authData, change);\n }\n const removeServerOnlyFields = removeServerOnlyFieldsMonad(this.serverOnlyFields);\n\n this.server.expressApp.post('/' + this.urlPath + '/query', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n let useQuery: FilledMangoQuery<RxDocType>\n try {\n useQuery = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n req.body\n )\n );\n } catch (err) {\n closeConnection(res, 400, 'Bad Request');\n return;\n }\n const rxQuery = this.collection.find(useQuery as any);\n const result = await rxQuery.exec();\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: result.map(d => removeServerOnlyFields(d.toJSON()))\n });\n });\n\n /**\n * It is not possible to send data with server send events,\n * so we send the query as query parameter in base64\n * like ?query=e3NlbGVjdG9yOiB7fX0=\n */\n this.server.expressApp.get('/' + this.urlPath + '/query/observe', async (req, res) => {\n let authData = getFromMapOrThrow(authDataByRequest, req);\n writeSSEHeaders(res);\n\n const useQuery: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n JSON.parse(atob(req.query.query as string))\n )\n );\n\n const rxQuery = this.collection.find(useQuery as any);\n const subscription = rxQuery.$.pipe(\n mergeMap(async (result) => {\n const resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));\n\n /**\n * The auth-data might be expired\n * so we re-run the auth parsing each time\n * before emitting the new results.\n */\n try {\n authData = await server.authHandler(req.headers);\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n return resultData;\n }),\n filter(f => f !== null)\n ).subscribe(resultData => {\n res.write('data: ' + JSON.stringify(resultData) + '\\n\\n');\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n req.on('close', () => {\n subscription.unsubscribe();\n res.end();\n });\n });\n\n\n this.server.expressApp.post('/' + this.urlPath + '/get', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const ids: string[] = req.body;\n\n const rxQuery = this.collection.findByIds(ids);\n const resultMap = await rxQuery.exec();\n const resultValues = Array.from(resultMap.values());\n const docMatcher = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n let useDocs = resultValues.map(d => d.toJSON());\n useDocs = useDocs.filter(d => docMatcher(d as any));\n useDocs = useDocs.map(d => removeServerOnlyFields(d))\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n documents: useDocs\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/set', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let docsData: RxDocType[] = req.body;\n\n for (const docData of docsData) {\n const allowed = docDataMatcherWrite(docData as any);\n if (!allowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n }\n\n function onWriteError(err: RxError, docData: RxDocType) {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n docsData.push(docData);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }\n\n while (docsData.length > 0) {\n const promises: Promise<any>[] = [];\n const docs = await collection.findByIds(docsData.map(d => (d as any)[primaryPath])).exec();\n let useDocsData = docsData.slice();\n docsData = [];\n for (const docData of useDocsData) {\n const id = (docData as any)[primaryPath];\n const doc = docs.get(id);\n if (!doc) {\n promises.push(this.collection.insert(docData).catch(err => onWriteError(err, docData)));\n } else {\n const isAllowed = this.changeValidator(authData, {\n newDocumentState: removeServerOnlyFields(docData as any),\n assumedMasterState: removeServerOnlyFields(doc.toJSON(true))\n });\n if (!isAllowed) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n promises.push(doc.patch(docData).catch(err => onWriteError(err, docData)));\n }\n }\n await Promise.all(promises);\n }\n\n res.setHeader('Content-Type', 'application/json');\n res.json({\n });\n });\n\n this.server.expressApp.post('/' + this.urlPath + '/delete', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let ids: string[] = req.body;\n while (ids.length > 0) {\n const useIds = ids.slice(0);\n ids = [];\n const promises: Promise<any>[] = [];\n const docsMap = await this.collection.findByIds(useIds).exec();\n for (const id of useIds) {\n const doc = docsMap.get(id);\n if (doc) {\n const isAllowedDoc = docDataMatcherWrite(doc.toJSON(true) as any);\n if (!isAllowedDoc) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n const isAllowedChange = this.changeValidator(authData, {\n newDocumentState: doc.toJSON(true) as any,\n assumedMasterState: doc.toJSON(true) as any\n });\n if (!isAllowedChange) {\n closeConnection(res, 403, 'Forbidden');\n return;\n }\n\n promises.push(doc.remove().catch((err: RxError) => {\n if (err.rxdb && err.code === 'CONFLICT') {\n // just retry on conflicts\n ids.push(id);\n } else {\n closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }));\n }\n }\n await Promise.all(promises);\n }\n res.setHeader('Content-Type', 'application/json');\n res.json({});\n });\n }\n}\n"],"mappings":"AAAA,SAIIA,mBAAmB,QAChB,mBAAmB;AAO1B,SAASC,MAAM,EAAEC,QAAQ,QAAQ,MAAM;AACvC,SACIC,cAAc,EACdC,iBAAiB,QACd,oBAAoB;AAE3B,SACIC,iBAAiB,EACjBC,yBAAyB,EACzBC,eAAe,EACfC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,oBAAoB,EACpBC,2BAA2B,EAC3BC,OAAO,EACPC,eAAe,QACZ,aAAa;AAGpB,OAAO,IAAMC,UAAU,GAAG,CACtB,OAAO,EACP,eAAe,EACf,KAAK,EACL,KAAK,EACL;;AAEA;AACA;AACJ;AACA;AACA;AACA,EAJI,CAKM;AAGV,WAAaC,oBAAoB,GAK7B,SAAAA,qBACoBC,MAA0B,EAC1BC,IAAY,EACZC,UAAmC,EACnDC,aAAyD,EACzDC,eAA6D,EAC7CC,gBAA0B,EAC1BC,IAAa,EAC/B;EAAA,IAAAC,KAAA;EAAA,KAZOC,IAAI,GAAG,MAAM;EAAA,KAKFR,MAA0B,GAA1BA,MAA0B;EAAA,KAC1BC,IAAY,GAAZA,IAAY;EAAA,KACZC,UAAmC,GAAnCA,UAAmC;EAAA,KAGnCG,gBAA0B,GAA1BA,gBAA0B;EAAA,KAC1BC,IAAa,GAAbA,IAAa;EAE7BV,OAAO,CAAC,IAAI,CAACI,MAAM,EAAE,CAAC,IAAI,CAACC,IAAI,CAAC,CAACQ,IA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AAG;cACb;YACJ,CAAC,CAAC,CAAC;UACP;QACJ,CAAC;QAAAoE,KAAA;MA5BD,KAAK,IAAMf,EAAE,IAAIS,MAAM;QAAAM,KAAA,SAAAJ,MAAA,CAAAX,EAAA;QAAA,IAAAe,KAAA,SAAAA,KAAA,CAAAX,CAAA;MAAA;MA6BvB,MAAMG,OAAO,CAACC,GAAG,CAACd,QAAQ,CAAC;IAC/B;IACAnD,GAAG,CAACS,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC;IACjDT,GAAG,CAACU,IAAI,CAAC,CAAC,CAAC,CAAC;EAChB,CAAC,CAAC;AACN,CAAC","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helper.js","names":["expressCors","flatClone","getQueryMatcher","normalizeMangoQuery","uniqueArray","setCors","server","path","cors","useCors","expressApp","options","origin","optionsSuccessStatus","blockPreviousVersionPaths","currentVersion","v","_loop","version","all","req","res","closeConnection","response","code","message","responseWrite","error","statusCode","set","write","JSON","stringify","end","addAuthMiddleware","authDataByRequest","WeakMap","auth","next","authData","authHandler","headers","err","defaultMatchingQuery","selector","skip","sort","getDocAllowedMatcher","endpoint","useQuery","queryModifier","collection","schema","jsonSchema","docDataMatcher","writeSSEHeaders","writeHead","flushHeaders","docContainsServerOnlyFields","serverOnlyFields","doc","has","find","field","removeServerOnlyFieldsMonad","serverOnlyFieldsStencil","_meta","undefined","_rev","_attachments","forEach","docData","Object","assign","mergeServerDocumentFieldsMonad","useFields","slice","clientDoc","serverDoc","ret","doesContainRegexQuerySelector","Array","isArray","found","item","entries","key","value"],"sources":["../../../../src/plugins/server/helper.ts"],"sourcesContent":["import { RxServer } from './rx-server';\nimport expressCors from 'cors';\nimport type {\n Request,\n Response,\n NextFunction\n} from 'express';\nimport { RxServerAuthData, RxServerEndpoint } from './types';\nimport {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n flatClone,\n getQueryMatcher,\n normalizeMangoQuery,\n uniqueArray\n} from 'rxdb/plugins/core';\n\nexport function setCors(\n server: RxServer<any>,\n path: string,\n cors?: string\n) {\n let useCors = cors;\n if (!useCors) {\n useCors = server.cors;\n }\n if (useCors) {\n server.expressApp.options('/' + path + '/*', expressCors({\n origin: useCors,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200\n }));\n }\n}\n\n/**\n * \"block\" the previous version urls and send a 426 on them so that\n * the clients know they must update.\n */\nexport function blockPreviousVersionPaths(\n server: RxServer<any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n server.expressApp.all('/' + path + '/' + version + '/*', (req, res) => {\n closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n v++;\n }\n}\n\n\nexport async function closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.statusCode = code;\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n}\n\n\nexport function addAuthMiddleware<AuthType>(\n server: RxServer<AuthType>,\n path: string,\n): WeakMap<Request, RxServerAuthData<AuthType>> {\n const authDataByRequest = new WeakMap<Request, RxServerAuthData<AuthType>>();\n async function auth(req: Request, res: Response, next: NextFunction) {\n try {\n const authData = await server.authHandler(req.headers);\n authDataByRequest.set(req, authData);\n next();\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return;\n }\n }\n server.expressApp.all('/' + path + '/*', auth, function (req, res, next) {\n next();\n });\n return authDataByRequest;\n}\n\nconst defaultMatchingQuery: FilledMangoQuery<any> = {\n selector: {},\n skip: 0,\n sort: []\n} as const;\n\nexport function getDocAllowedMatcher<RxDocType, AuthType>(\n endpoint: RxServerEndpoint<AuthType, RxDocType>,\n authData: RxServerAuthData<AuthType>\n) {\n const useQuery: FilledMangoQuery<RxDocType> = endpoint.queryModifier ? endpoint.queryModifier(\n authData,\n normalizeMangoQuery(\n endpoint.collection.schema.jsonSchema,\n {}\n )\n ) : defaultMatchingQuery;\n const docDataMatcher = getQueryMatcher(endpoint.collection.schema.jsonSchema, useQuery);\n return docDataMatcher;\n}\n\nexport function writeSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n}\n\nexport function docContainsServerOnlyFields(\n serverOnlyFields: string[],\n doc: any\n) {\n const has = serverOnlyFields.find(field => {\n return typeof doc[field] !== 'undefined'\n });\n return has;\n}\n\nexport function removeServerOnlyFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n const serverOnlyFieldsStencil: any = {\n _meta: undefined,\n _rev: undefined,\n _attachments: undefined\n };\n serverOnlyFields.forEach(field => serverOnlyFieldsStencil[field] = undefined);\n return (\n docData?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!docData) {\n return docData;\n }\n return Object.assign({}, docData, serverOnlyFieldsStencil);\n }\n}\n\nexport function mergeServerDocumentFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n let useFields = serverOnlyFields.slice(0);\n // useFields.push('_rev');\n // useFields.push('_meta');\n // useFields.push('_attachments');\n useFields = uniqueArray(useFields);\n\n return (\n clientDoc: RxDocType | RxDocumentData<RxDocType>,\n serverDoc?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!serverDoc) {\n return clientDoc;\n }\n const ret = flatClone(clientDoc);\n useFields.forEach(field => {\n (ret as any)[field] = (serverDoc as any)[field];\n });\n return ret;\n }\n}\n\n\n/**\n * $regex queries are dangerous because they can dos-attach the \n * \n * @param selector \n */\nexport function doesContainRegexQuerySelector(selector: MangoQuerySelector<any> | any): boolean {\n if (!selector) {\n return false;\n }\n if (Array.isArray(selector)) {\n const found = !!selector.find(item => doesContainRegexQuerySelector(item));\n return found;\n }\n\n if (typeof selector !== 'object') {\n return false;\n }\n\n const entries = Object.entries(selector);\n for (const [key, value] of entries) {\n if (key === '$regex') {\n return true;\n } else {\n const has = doesContainRegexQuerySelector(value);\n if (has) {\n return true;\n }\n }\n }\n\n return false;\n}\n"],"mappings":"AACA,OAAOA,WAAW,MAAM,MAAM;AAO9B,SAKIC,SAAS,EACTC,eAAe,EACfC,mBAAmB,EACnBC,WAAW,QACR,mBAAmB;AAE1B,OAAO,SAASC,OAAOA,CACnBC,MAAqB,EACrBC,IAAY,EACZC,IAAa,EACf;EACE,IAAIC,OAAO,GAAGD,IAAI;EAClB,IAAI,CAACC,OAAO,EAAE;IACVA,OAAO,GAAGH,MAAM,CAACE,IAAI;EACzB;EACA,IAAIC,OAAO,EAAE;IACTH,MAAM,CAACI,UAAU,CAACC,OAAO,CAAC,GAAG,GAAGJ,IAAI,GAAG,IAAI,EAAEP,WAAW,CAAC;MACrDY,MAAM,EAAEH,OAAO;MACf;MACAI,oBAAoB,EAAE;IAC1B,CAAC,CAAC,CAAC;EACP;AACJ;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAASC,yBAAyBA,CACrCR,MAAqB,EACrBC,IAAY,EACZQ,cAAsB,EAExB;EACE,IAAIC,CAAC,GAAG,CAAC;EAAC,IAAAC,KAAA,YAAAA,CAAA,EACiB;IACvB,IAAMC,OAAO,GAAGF,CAAC;IACjBV,MAAM,CAACI,UAAU,CAACS,GAAG,CAAC,GAAG,GAAGZ,IAAI,GAAG,GAAG,GAAGW,OAAO,GAAG,IAAI,EAAE,CAACE,GAAG,EAAEC,GAAG,KAAK;MACnEC,eAAe,CAACD,GAAG,EAAE,GAAG,EAAE,mBAAmB,GAAGH,OAAO,GAAG,cAAc,GAAGH,cAAc,GAAG,GAAG,CAAC;IACpG,CAAC,CAAC;IACFC,CAAC,EAAE;EACP,CAAC;EAND,OAAOA,CA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G,GAAGmB,6BAA6B,CAACO,KAAK,CAAC;MAChD,IAAI1B,GAAG,EAAE;QACL,OAAO,IAAI;MACf;IACJ;EACJ;EAEA,OAAO,KAAK;AAChB"}
|
|
1
|
+
{"version":3,"file":"helper.js","names":["expressCors","flatClone","getQueryMatcher","normalizeMangoQuery","uniqueArray","setCors","server","path","cors","useCors","expressApp","options","origin","optionsSuccessStatus","blockPreviousVersionPaths","currentVersion","v","_loop","version","all","req","res","closeConnection","response","code","message","responseWrite","error","statusCode","set","write","JSON","stringify","end","addAuthMiddleware","authDataByRequest","WeakMap","auth","next","authData","authHandler","headers","err","defaultMatchingQuery","selector","skip","sort","getDocAllowedMatcher","endpoint","useQuery","queryModifier","collection","schema","jsonSchema","docDataMatcher","writeSSEHeaders","writeHead","flushHeaders","docContainsServerOnlyFields","serverOnlyFields","doc","has","find","field","removeServerOnlyFieldsMonad","serverOnlyFieldsStencil","_meta","undefined","_rev","_attachments","forEach","docData","Object","assign","mergeServerDocumentFieldsMonad","useFields","slice","clientDoc","serverDoc","ret","doesContainRegexQuerySelector","Array","isArray","found","item","entries","key","value"],"sources":["../../../../src/plugins/server/helper.ts"],"sourcesContent":["import { RxServer } from './rx-server';\nimport expressCors from 'cors';\nimport type {\n Request,\n Response,\n NextFunction\n} from 'express';\nimport { RxServerAuthData, RxServerEndpoint } from './types';\nimport {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n RxReplicationWriteToMasterRow,\n flatClone,\n getQueryMatcher,\n normalizeMangoQuery,\n uniqueArray\n} from 'rxdb/plugins/core';\n\nexport function setCors(\n server: RxServer<any>,\n path: string,\n cors?: string\n) {\n let useCors = cors;\n if (!useCors) {\n useCors = server.cors;\n }\n if (useCors) {\n server.expressApp.options('/' + path + '/*', expressCors({\n origin: useCors,\n // some legacy browsers (IE11, various SmartTVs) choke on 204\n optionsSuccessStatus: 200\n }));\n }\n}\n\n/**\n * \"block\" the previous version urls and send a 426 on them so that\n * the clients know they must update.\n */\nexport function blockPreviousVersionPaths(\n server: RxServer<any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n server.expressApp.all('/' + path + '/' + version + '/*', (req, res) => {\n closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n v++;\n }\n}\n\n\nexport async function closeConnection(response: Response, code: number, message: string) {\n const responseWrite = {\n code,\n error: true,\n message\n };\n response.statusCode = code;\n response.set(\"Connection\", \"close\");\n await response.write(JSON.stringify(responseWrite));\n response.end();\n}\n\n\nexport function addAuthMiddleware<AuthType>(\n server: RxServer<AuthType>,\n path: string,\n): WeakMap<Request, RxServerAuthData<AuthType>> {\n const authDataByRequest = new WeakMap<Request, RxServerAuthData<AuthType>>();\n async function auth(req: Request, res: Response, next: NextFunction) {\n try {\n const authData = await server.authHandler(req.headers);\n authDataByRequest.set(req, authData);\n next();\n } catch (err) {\n closeConnection(res, 401, 'Unauthorized');\n return;\n }\n }\n server.expressApp.all('/' + path + '/*', auth, function (req, res, next) {\n next();\n });\n return authDataByRequest;\n}\n\nconst defaultMatchingQuery: FilledMangoQuery<any> = {\n selector: {},\n skip: 0,\n sort: []\n} as const;\n\nexport function getDocAllowedMatcher<RxDocType, AuthType>(\n endpoint: RxServerEndpoint<AuthType, RxDocType>,\n authData: RxServerAuthData<AuthType>\n) {\n const useQuery: FilledMangoQuery<RxDocType> = endpoint.queryModifier ? endpoint.queryModifier(\n authData,\n normalizeMangoQuery(\n endpoint.collection.schema.jsonSchema,\n {}\n )\n ) : defaultMatchingQuery;\n const docDataMatcher = getQueryMatcher(endpoint.collection.schema.jsonSchema, useQuery);\n return docDataMatcher;\n}\n\nexport function writeSSEHeaders(res: Response) {\n res.writeHead(200, {\n /**\n * Use exact these headers to make is less likely\n * for people to have problems.\n * @link https://www.youtube.com/watch?v=0PcMuYGJPzM\n */\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache',\n /**\n * Required for nginx\n * @link https://stackoverflow.com/q/61029079/3443137\n */\n 'X-Accel-Buffering': 'no'\n });\n res.flushHeaders();\n}\n\nexport function docContainsServerOnlyFields(\n serverOnlyFields: string[],\n doc: any\n) {\n const has = serverOnlyFields.find(field => {\n return typeof doc[field] !== 'undefined'\n });\n return has;\n}\n\nexport function removeServerOnlyFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n const serverOnlyFieldsStencil: any = {\n _meta: undefined,\n _rev: undefined,\n _attachments: undefined\n };\n serverOnlyFields.forEach(field => serverOnlyFieldsStencil[field] = undefined);\n return (\n docData?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!docData) {\n return docData;\n }\n return Object.assign({}, docData, serverOnlyFieldsStencil);\n }\n}\n\nexport function mergeServerDocumentFieldsMonad<RxDocType>(serverOnlyFields: string[]) {\n let useFields = serverOnlyFields.slice(0);\n // useFields.push('_rev');\n // useFields.push('_meta');\n // useFields.push('_attachments');\n useFields = uniqueArray(useFields);\n\n return (\n clientDoc: RxDocType | RxDocumentData<RxDocType>,\n serverDoc?: RxDocType | RxDocumentData<RxDocType>\n ) => {\n if (!serverDoc) {\n return clientDoc;\n }\n const ret = flatClone(clientDoc);\n useFields.forEach(field => {\n (ret as any)[field] = (serverDoc as any)[field];\n });\n return ret;\n }\n}\n\n\n/**\n * $regex queries are dangerous because they can dos-attach the \n * \n * @param selector \n */\nexport function doesContainRegexQuerySelector(selector: MangoQuerySelector<any> | any): boolean {\n if (!selector) {\n return false;\n }\n if (Array.isArray(selector)) {\n const found = !!selector.find(item => doesContainRegexQuerySelector(item));\n return found;\n }\n\n if (typeof selector !== 'object') {\n return false;\n }\n\n const entries = Object.entries(selector);\n for (const [key, value] of entries) {\n if (key === '$regex') {\n return true;\n } else {\n const has = doesContainRegexQuerySelector(value);\n if (has) {\n return true;\n }\n }\n }\n\n return false;\n}\n"],"mappings":"AACA,OAAOA,WAAW,MAAM,MAAM;AAO9B,SAKIC,SAAS,EACTC,eAAe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,CACHE,SAAgD,EAChDC,SAAiD,KAChD;IACD,IAAI,CAACA,SAAS,EAAE;MACZ,OAAOD,SAAS;IACpB;IACA,IAAME,GAAG,GAAG9E,SAAS,CAAC4E,SAAS,CAAC;IAChCF,SAAS,CAACL,OAAO,CAACP,KAAK,IAAI;MACtBgB,GAAG,CAAShB,KAAK,CAAC,GAAIe,SAAS,CAASf,KAAK,CAAC;IACnD,CAAC,CAAC;IACF,OAAOgB,GAAG;EACd,CAAC;AACL;;AAGA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6BA,CAACpC,QAAuC,EAAW;EAC5F,IAAI,CAACA,QAAQ,EAAE;IACX,OAAO,KAAK;EAChB;EACA,IAAIqC,KAAK,CAACC,OAAO,CAACtC,QAAQ,CAAC,EAAE;IACzB,IAAMuC,KAAK,GAAG,CAAC,CAACvC,QAAQ,CAACkB,IAAI,CAACsB,IAAI,IAAIJ,6BAA6B,CAACI,IAAI,CAAC,CAAC;IAC1E,OAAOD,KAAK;EAChB;EAEA,IAAI,OAAOvC,QAAQ,KAAK,QAAQ,EAAE;IAC9B,OAAO,KAAK;EAChB;EAEA,IAAMyC,OAAO,GAAGb,MAAM,CAACa,OAAO,CAACzC,QAAQ,CAAC;EACxC,KAAK,IAAM,CAAC0C,GAAG,EAAEC,KAAK,CAAC,IAAIF,OAAO,EAAE;IAChC,IAAIC,GAAG,KAAK,QAAQ,EAAE;MAClB,OAAO,IAAI;IACf,CAAC,MAAM;MACH,IAAMzB,GAAG,GAAGmB,6BAA6B,CAACO,KAAK,CAAC;MAChD,IAAI1B,GAAG,EAAE;QACL,OAAO,IAAI;MACf;IACJ;EACJ;EAEA,OAAO,KAAK;AAChB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","RxServer","express","startRxServer","options","serverApp","app","use","json","httpServer","Promise","res","rej","hostname","ret","listen","port","authHandler","data","validUntil","Date","now","server","database","cors"],"sources":["../../../../src/plugins/server/index.ts"],"sourcesContent":["import { ensureNotFalsy, flatClone } from 'rxdb/plugins/utils';\nimport { RxServer } from './rx-server.ts';\nimport { RxServerAuthHandler, RxServerOptions } from './types.ts';\nimport express from 'express';\nimport {\n Server as HttpServer\n} from 'http';\n\nexport * from './types.ts';\nexport * from './endpoint-replication.ts';\nexport * from './endpoint-rest.ts';\nexport * from './helper.ts';\n\nexport async function startRxServer<AuthType>(options: RxServerOptions<AuthType>): Promise<RxServer<AuthType>> {\n options = flatClone(options);\n if (!options.serverApp) {\n const app = express();\n options.serverApp = app;\n }\n\n options.serverApp.use(express.json());\n\n\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const hostname = options.hostname ? options.hostname : 'localhost';\n const ret = ensureNotFalsy(options.serverApp).listen(options.port, hostname, () => {\n res(ret);\n });\n });\n\n const authHandler: RxServerAuthHandler<AuthType> = options.authHandler ? options.authHandler : () => {\n return {\n data: {} as any,\n validUntil: Date.now() * 2\n };\n };\n\n const server = new RxServer<AuthType>(\n options.database,\n authHandler,\n httpServer,\n ensureNotFalsy(options.serverApp),\n options.cors\n );\n\n return server;\n}\n"],"mappings":"AAAA,SAASA,cAAc,EAAEC,SAAS,QAAQ,oBAAoB;AAC9D,SAASC,QAAQ,QAAQ,gBAAgB;AAEzC,OAAOC,OAAO,MAAM,SAAS;AAK7B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,oBAAoB;AAClC,cAAc,aAAa;AAE3B,OAAO,eAAeC,aAAaA,CAAWC,OAAkC,EAA+B;EAC3GA,OAAO,GAAGJ,SAAS,CAACI,OAAO,CAAC;EAC5B,IAAI,CAACA,OAAO,CAACC,SAAS,EAAE;IACpB,IAAMC,GAAG,GAAGJ,OAAO,CAAC,CAAC;IACrBE,OAAO,CAACC,SAAS,GAAGC,GAAG;EAC3B;EAEAF,OAAO,CAACC,SAAS,CAACE,GAAG,CAACL,OAAO,CAACM,IAAI,CAAC,CAAC,CAAC;EAGrC,IAAMC,UAAsB,GAAG,MAAM,IAAIC,OAAO,CAAC,CAACC,GAAG,EAAEC,GAAG,KAAK;IAC3D,IAAMC,QAAQ,GAAGT,OAAO,CAACS,QAAQ,GAAGT,OAAO,CAACS,QAAQ,GAAG,WAAW;IAClE,IAAMC,GAAG,GAAGf,cAAc,CAACK,OAAO,CAACC,SAAS,CAAC,CAACU,MAAM,CAACX,OAAO,CAACY,IAAI,EAAEH,QAAQ,EAAE,MAAM;MAC/EF,GAAG,CAACG,GAAG,CAAC;IACZ,CAAC,CAAC;EACN,CAAC,CAAC;EAEF,IAAMG,WAA0C,GAAGb,OAAO,CAACa,WAAW,GAAGb,OAAO,CAACa,WAAW,GAAG,MAAM;IACjG,OAAO;MACHC,IAAI,EAAE,CAAC,CAAQ;MACfC,UAAU,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG;IAC7B,CAAC;EACL,CAAC;EAED,IAAMC,MAAM,GAAG,IAAIrB,QAAQ,CACvBG,OAAO,CAACmB,QAAQ,EAChBN,WAAW,EACXR,UAAU,EACVV,cAAc,CAACK,OAAO,CAACC,SAAS,CAAC,EACjCD,OAAO,CAACoB,IACZ,CAAC;EAED,OAAOF,MAAM;AACjB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","RxServer","express","startRxServer","options","serverApp","app","use","json","httpServer","Promise","res","rej","hostname","ret","listen","port","authHandler","data","validUntil","Date","now","server","database","cors"],"sources":["../../../../src/plugins/server/index.ts"],"sourcesContent":["import { ensureNotFalsy, flatClone } from 'rxdb/plugins/utils';\nimport { RxServer } from './rx-server.ts';\nimport { RxServerAuthHandler, RxServerOptions } from './types.ts';\nimport express from 'express';\nimport {\n Server as HttpServer\n} from 'http';\n\nexport * from './types.ts';\nexport * from './endpoint-replication.ts';\nexport * from './endpoint-rest.ts';\nexport * from './helper.ts';\n\nexport async function startRxServer<AuthType>(options: RxServerOptions<AuthType>): Promise<RxServer<AuthType>> {\n options = flatClone(options);\n if (!options.serverApp) {\n const app = express();\n options.serverApp = app;\n }\n\n options.serverApp.use(express.json());\n\n\n const httpServer: HttpServer = await new Promise((res, rej) => {\n const hostname = options.hostname ? options.hostname : 'localhost';\n const ret = ensureNotFalsy(options.serverApp).listen(options.port, hostname, () => {\n res(ret);\n });\n });\n\n const authHandler: RxServerAuthHandler<AuthType> = options.authHandler ? options.authHandler : () => {\n return {\n data: {} as any,\n validUntil: Date.now() * 2\n };\n };\n\n const server = new RxServer<AuthType>(\n options.database,\n authHandler,\n httpServer,\n ensureNotFalsy(options.serverApp),\n options.cors\n );\n\n return server;\n}\n"],"mappings":"AAAA,SAASA,cAAc,EAAEC,SAAS,QAAQ,oBAAoB;AAC9D,SAASC,QAAQ,QAAQ,gBAAgB;AAEzC,OAAOC,OAAO,MAAM,SAAS;AAK7B,cAAc,YAAY;AAC1B,cAAc,2BAA2B;AACzC,cAAc,oBAAoB;AAClC,cAAc,aAAa;AAE3B,OAAO,eAAeC,aAAaA,CAAWC,OAAkC,EAA+B;EAC3GA,OAAO,GAAGJ,SAAS,CAACI,OAAO,CAAC;EAC5B,IAAI,CAACA,OAAO,CAACC,SAAS,EAAE;IACpB,IAAMC,GAAG,GAAGJ,OAAO,CAAC,CAAC;IACrBE,OAAO,CAACC,SAAS,GAAGC,GAAG;EAC3B;EAEAF,OAAO,CAACC,SAAS,CAACE,GAAG,CAACL,OAAO,CAACM,IAAI,CAAC,CAAC,CAAC;EAGrC,IAAMC,UAAsB,GAAG,MAAM,IAAIC,OAAO,CAAC,CAACC,GAAG,EAAEC,GAAG,KAAK;IAC3D,IAAMC,QAAQ,GAAGT,OAAO,CAACS,QAAQ,GAAGT,OAAO,CAACS,QAAQ,GAAG,WAAW;IAClE,IAAMC,GAAG,GAAGf,cAAc,CAACK,OAAO,CAACC,SAAS,CAAC,CAACU,MAAM,CAACX,OAAO,CAACY,IAAI,EAAEH,QAAQ,EAAE,MAAM;MAC/EF,GAAG,CAACG,GAAG,CAAC;IACZ,CAAC,CAAC;EACN,CAAC,CAAC;EAEF,IAAMG,WAA0C,GAAGb,OAAO,CAACa,WAAW,GAAGb,OAAO,CAACa,WAAW,GAAG,MAAM;IACjG,OAAO;MACHC,IAAI,EAAE,CAAC,CAAQ;MACfC,UAAU,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG;IAC7B,CAAC;EACL,CAAC;EAED,IAAMC,MAAM,GAAG,IAAIrB,QAAQ,CACvBG,OAAO,CAACmB,QAAQ,EAChBN,WAAW,EACXR,UAAU,EACVV,cAAc,CAACK,OAAO,CAACC,SAAS,CAAC,EACjCD,OAAO,CAACoB,IACZ,CAAC;EAED,OAAOF,MAAM;AACjB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rx-server.js","names":["RxServerReplicationEndpoint","RxServerRestEndpoint","RxServer","database","authHandler","httpServer","expressApp","cors","endpoints","closeFn","close","bind","onDestroy","push","_proto","prototype","addReplicationEndpoint","opts","endpoint","name","collection","queryModifier","_a","q","changeValidator","serverOnlyFields","addRestEndpoint","filter","fn","Promise","res","rej","err","setImmediate","emit"],"sources":["../../../../src/plugins/server/rx-server.ts"],"sourcesContent":["import type {\n RxCollection,\n RxDatabase\n} from 'rxdb/plugins/core';\nimport { RxServerReplicationEndpoint } from './endpoint-replication.ts';\nimport type {\n RxServerAuthHandler,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport {\n Server as HttpServer\n} from 'http';\nimport { Express } from 'express';\nimport { RxServerRestEndpoint } from './endpoint-rest.ts';\n\nexport class RxServer<AuthType> {\n public readonly endpoints: RxServerEndpoint<AuthType, any>[] = [];\n\n private closeFn = (() => this.close()).bind(this);\n\n constructor(\n public readonly database: RxDatabase,\n public readonly authHandler: RxServerAuthHandler<AuthType>,\n public readonly httpServer: HttpServer,\n public readonly expressApp: Express,\n public readonly cors: string = '*'\n ) {\n database.onDestroy.push(this.closeFn);\n }\n\n public async addReplicationEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerReplicationEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n public async addRestEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerRestEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n async close() {\n this.database.onDestroy = this.database.onDestroy.filter(fn => fn !== this.closeFn);\n await new Promise<void>((res, rej) => {\n this.httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate(() => this.httpServer.emit('close'));\n });\n\n }\n}\n"],"mappings":"AAIA,SAASA,2BAA2B,QAAQ,2BAA2B;AAWvE,SAASC,oBAAoB,QAAQ,oBAAoB;AAEzD,WAAaC,QAAQ;EAKjB,SAAAA,SACoBC,QAAoB,EACpBC,WAA0C,EAC1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,GAAG,CAACC,EAAE,EAAEC,CAAC,KAAKA,CAAC,EACtDN,IAAI,CAACO,eAAe,GAAGP,IAAI,CAACO,eAAe,GAAG,MAAM,IAAI,EACxDP,IAAI,CAACQ,gBAAgB,GAAGR,IAAI,CAACQ,gBAAgB,GAAG,EAAE,EAClDR,IAAI,CAACV,IACT,CAAC;IACD,IAAI,CAACC,SAAS,CAACK,IAAI,CAACK,QAAQ,CAAC;IAC7B,OAAOA,QAAQ;EACnB,CAAC;EAAAJ,MAAA,CAEKJ,KAAK,GAAX,eAAAA,MAAA,EAAc;IACV,IAAI,CAACP,QAAQ,CAACS,SAAS,GAAG,IAAI,CAACT,QAAQ,CAACS,SAAS,CAACe,MAAM,CAACC,EAAE,IAAIA,EAAE,KAAK,IAAI,CAACnB,OAAO,CAAC;IACnF,MAAM,IAAIoB,OAAO,CAAO,CAACC,GAAG,EAAEC,GAAG,KAAK;MAClC,IAAI,CAAC1B,UAAU,CAACK,KAAK,CAAEsB,GAAG,IAAK;QAC3B,IAAIA,GAAG,EAAE;UAAED,GAAG,CAACC,GAAG,CAAC;QAAE,CAAC,MAAM;UAAEF,GAAG,CAAC,CAAC;QAAE;MACzC,CAAC,CAAC;MACF;AACZ;AACA;AACA;AACA;MACYG,YAAY,CAAC,MAAM,IAAI,CAAC5B,UAAU,CAAC6B,IAAI,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC,CAAC;EAEN,CAAC;EAAA,OAAAhC,QAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"rx-server.js","names":["RxServerReplicationEndpoint","RxServerRestEndpoint","RxServer","database","authHandler","httpServer","expressApp","cors","endpoints","closeFn","close","bind","onDestroy","push","_proto","prototype","addReplicationEndpoint","opts","endpoint","name","collection","queryModifier","_a","q","changeValidator","serverOnlyFields","addRestEndpoint","filter","fn","Promise","res","rej","err","setImmediate","emit"],"sources":["../../../../src/plugins/server/rx-server.ts"],"sourcesContent":["import type {\n RxCollection,\n RxDatabase\n} from 'rxdb/plugins/core';\nimport { RxServerReplicationEndpoint } from './endpoint-replication.ts';\nimport type {\n RxServerAuthHandler,\n RxServerChangeValidator,\n RxServerEndpoint,\n RxServerQueryModifier\n} from './types.ts';\nimport {\n Server as HttpServer\n} from 'http';\nimport { Express } from 'express';\nimport { RxServerRestEndpoint } from './endpoint-rest.ts';\n\nexport class RxServer<AuthType> {\n public readonly endpoints: RxServerEndpoint<AuthType, any>[] = [];\n\n private closeFn = (() => this.close()).bind(this);\n\n constructor(\n public readonly database: RxDatabase,\n public readonly authHandler: RxServerAuthHandler<AuthType>,\n public readonly httpServer: HttpServer,\n public readonly expressApp: Express,\n public readonly cors: string = '*'\n ) {\n database.onDestroy.push(this.closeFn);\n }\n\n public async addReplicationEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerReplicationEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n public async addRestEndpoint<RxDocType>(opts: {\n name: string,\n collection: RxCollection<RxDocType>,\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>,\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>,\n /**\n * Set a origin for allowed CORS requests.\n * Overwrites the cors option of the server.\n * [default='*']\n */\n cors?: '*' | string,\n serverOnlyFields?: string[]\n }) {\n const endpoint = new RxServerRestEndpoint(\n this,\n opts.name,\n opts.collection,\n opts.queryModifier ? opts.queryModifier : (_a, q) => q,\n opts.changeValidator ? opts.changeValidator : () => true,\n opts.serverOnlyFields ? opts.serverOnlyFields : [],\n opts.cors\n );\n this.endpoints.push(endpoint);\n return endpoint;\n }\n\n async close() {\n this.database.onDestroy = this.database.onDestroy.filter(fn => fn !== this.closeFn);\n await new Promise<void>((res, rej) => {\n this.httpServer.close((err) => {\n if (err) { rej(err); } else { res(); }\n });\n /**\n * By default it will await all ongoing connections\n * before it closes. So we have to close it directly.\n * @link https://stackoverflow.com/a/36830072/3443137\n */\n setImmediate(() => this.httpServer.emit('close'));\n });\n\n }\n}\n"],"mappings":"AAIA,SAASA,2BAA2B,QAAQ,2BAA2B;AAWvE,SAASC,oBAAoB,QAAQ,oBAAoB;AAEzD,WAAaC,QAAQ;EAKjB,SAAAA,SACoBC,QAAoB,EACpBC,WAA0C,EAC1CC,UAAsB,EACtBC,UAAmB,EACnBC,IAAY,GAAG,GAAG,EACpC;IAAA,KAVcC,SAAS,GAAsC,EAAE;IAAA,KAEzDC,OAAO,GAAG,CAAC,MAAM,IAAI,CAACC,KAAK,CAAC,CAAC,EAAEC,IAAI,CAAC,IAAI,CAAC;IAAA,KAG7BR,QAAoB,GAApBA,QAAoB;IAAA,KACpBC,WAA0C,GAA1CA,WAA0C;IAAA,KAC1CC,UAAsB,GAAtBA,UAAsB;IAAA,KACtBC,UAAmB,GAAnBA,UAAmB;IAAA,KACnBC,IAAY,GAAZA,IAAY;IAE5BJ,QAAQ,CAACS,SAAS,CAACC,IAAI,CAAC,IAAI,CAACJ,OAAO,CAAC;EACzC;EAAC,IAAAK,MAAA,GAAAZ,QAAA,CAAAa,SAAA;EAAAD,MAAA,CAEYE,sBAAsB,GAAnC,eAAAA,uBAA+CC,IAY9C,EAAE;IACC,IAAMC,QAAQ,GAAG,IAAIlB,2BAA2B,CAC5C,IAAI,EACJiB,IAAI,CAACE,IAAI,EACTF,IAAI,CAACG,UAAU,EACfH,IAAI,CAACI,aAAa,GAAGJ,IAAI,CAACI,aAAa,GAAG,CAACC,EAAE,EAAEC,CAAC,KAAKA,CAAC,EACtDN,IAA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;MACYG,YAAY,CAAC,MAAM,IAAI,CAAC5B,UAAU,CAAC6B,IAAI,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC,CAAC;EAEN,CAAC;EAAA,OAAAhC,QAAA;AAAA","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/server/types.ts"],"sourcesContent":["import type {\n FilledMangoQuery,\n RxDatabase,\n RxReplicationWriteToMasterRow,\n MaybePromise,\n RxCollection,\n WithDeleted\n} from 'rxdb/plugins/core';\nimport { IncomingHttpHeaders } from 'http';\nimport { Express } from 'express';\n\nexport type RxServerOptions<AuthType> = {\n database: RxDatabase;\n authHandler?: RxServerAuthHandler<AuthType>;\n serverApp?: Express;\n appOptions?: any;\n /**\n * [default=localhost]\n */\n hostname?: 'localhost' | '0.0.0.0' | string;\n port: number;\n /**\n * Set a origin for allowed CORS requests.\n * Can be overwritten by the cors option of the endpoints.\n * [default='*']\n */\n cors?: '*' | string;\n};\n\nexport type RxServerAuthData<AuthType> = {\n data: AuthType;\n validUntil: number;\n};\n\n/**\n * Returns the auth state by the given request headers.\n * Throws if auth not valid.\n */\nexport type RxServerAuthHandler<AuthType> =\n (headers: IncomingHttpHeaders) => MaybePromise<RxServerAuthData<AuthType>>;\n\n/**\n * Modifies a given query in a way to limit the results\n * to what the authenticated user is allowed to see.\n * For example the query selector\n * input: {\n * selector: {\n * myField: { $gt: 100 }\n * }\n * }\n * could be modified to restrict the results to only return\n * documents that are \"owned\" by the user\n * return: {\n * selector: {\n * myField: { $gt: 100 },\n * userId: { $eq: authData.userId }\n * }\n * }\n * \n * \n */\nexport type RxServerQueryModifier<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n query: FilledMangoQuery<RxDocType>\n) => FilledMangoQuery<RxDocType>;\n\n/**\n * Validates if a given change is allowed to be performed on the server.\n * Returns true if allowed, false if not.\n * If a client tries to make a non-allowed change,\n * the client will be disconnected.\n */\nexport type RxServerChangeValidator<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n change: RxReplicationWriteToMasterRow<RxDocType>\n) => boolean;\n\n\nexport interface RxServerEndpoint<AuthType, RxDocType> {\n collection: RxCollection<RxDocType>;\n name: string;\n type: 'replication' | 'rest' | string;\n urlPath: string;\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>;\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>;\n};\n"],"mappings":"AAkCA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;AAcC;AAAC;AAAA"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/server/types.ts"],"sourcesContent":["import type {\n FilledMangoQuery,\n RxDatabase,\n RxReplicationWriteToMasterRow,\n MaybePromise,\n RxCollection,\n WithDeleted\n} from 'rxdb/plugins/core';\nimport { IncomingHttpHeaders } from 'http';\nimport { Express } from 'express';\n\nexport type RxServerOptions<AuthType> = {\n database: RxDatabase;\n authHandler?: RxServerAuthHandler<AuthType>;\n serverApp?: Express;\n appOptions?: any;\n /**\n * [default=localhost]\n */\n hostname?: 'localhost' | '0.0.0.0' | string;\n port: number;\n /**\n * Set a origin for allowed CORS requests.\n * Can be overwritten by the cors option of the endpoints.\n * [default='*']\n */\n cors?: '*' | string;\n};\n\nexport type RxServerAuthData<AuthType> = {\n data: AuthType;\n validUntil: number;\n};\n\n/**\n * Returns the auth state by the given request headers.\n * Throws if auth not valid.\n */\nexport type RxServerAuthHandler<AuthType> =\n (headers: IncomingHttpHeaders) => MaybePromise<RxServerAuthData<AuthType>>;\n\n/**\n * Modifies a given query in a way to limit the results\n * to what the authenticated user is allowed to see.\n * For example the query selector\n * input: {\n * selector: {\n * myField: { $gt: 100 }\n * }\n * }\n * could be modified to restrict the results to only return\n * documents that are \"owned\" by the user\n * return: {\n * selector: {\n * myField: { $gt: 100 },\n * userId: { $eq: authData.userId }\n * }\n * }\n * \n * \n */\nexport type RxServerQueryModifier<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n query: FilledMangoQuery<RxDocType>\n) => FilledMangoQuery<RxDocType>;\n\n/**\n * Validates if a given change is allowed to be performed on the server.\n * Returns true if allowed, false if not.\n * If a client tries to make a non-allowed change,\n * the client will be disconnected.\n */\nexport type RxServerChangeValidator<AuthType, RxDocType> = (\n authData: RxServerAuthData<AuthType>,\n change: RxReplicationWriteToMasterRow<RxDocType>\n) => boolean;\n\n\nexport interface RxServerEndpoint<AuthType, RxDocType> {\n collection: RxCollection<RxDocType>;\n name: string;\n type: 'replication' | 'rest' | string;\n urlPath: string;\n queryModifier?: RxServerQueryModifier<AuthType, RxDocType>;\n changeValidator?: RxServerChangeValidator<AuthType, RxDocType>;\n};\n"],"mappings":"AAkCA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;AACA;;AAcC;AAAC;AAAA","ignoreList":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rxdb-server",
|
|
3
|
-
"version": "15.
|
|
3
|
+
"version": "15.10.0",
|
|
4
4
|
"description": "RxDB Server Plugin",
|
|
5
5
|
"license": "SSPL",
|
|
6
6
|
"author": "pubkey",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"@types/eventsource": "1.1.15",
|
|
75
75
|
"@types/express": "4.17.21",
|
|
76
76
|
"array-push-at-sort-position": "4.0.1",
|
|
77
|
-
"async-test-util": "2.
|
|
77
|
+
"async-test-util": "2.4.0",
|
|
78
78
|
"eth-crypto": "2.6.0",
|
|
79
79
|
"eventsource": "2.0.2",
|
|
80
80
|
"percom": "1.1.3",
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
85
|
"@babel/cli": "7.23.9",
|
|
86
|
-
"@babel/core": "7.
|
|
86
|
+
"@babel/core": "7.24.0",
|
|
87
87
|
"@babel/plugin-external-helpers": "7.23.3",
|
|
88
88
|
"@babel/plugin-proposal-class-properties": "7.18.6",
|
|
89
89
|
"@babel/plugin-proposal-object-rest-spread": "7.20.7",
|
|
@@ -91,17 +91,17 @@
|
|
|
91
91
|
"@babel/plugin-transform-member-expression-literals": "7.23.3",
|
|
92
92
|
"@babel/plugin-transform-modules-commonjs": "7.23.3",
|
|
93
93
|
"@babel/plugin-transform-property-literals": "7.23.3",
|
|
94
|
-
"@babel/plugin-transform-runtime": "7.
|
|
94
|
+
"@babel/plugin-transform-runtime": "7.24.0",
|
|
95
95
|
"@babel/plugin-transform-spread": "7.23.3",
|
|
96
96
|
"@babel/plugin-transform-template-literals": "7.23.3",
|
|
97
97
|
"@babel/plugin-transform-typescript": "7.23.6",
|
|
98
98
|
"@babel/polyfill": "7.12.1",
|
|
99
|
-
"@babel/preset-env": "7.
|
|
99
|
+
"@babel/preset-env": "7.24.0",
|
|
100
100
|
"@babel/preset-typescript": "7.23.3",
|
|
101
|
-
"@babel/types": "7.
|
|
102
|
-
"@faker-js/faker": "8.4.
|
|
101
|
+
"@babel/types": "7.24.0",
|
|
102
|
+
"@faker-js/faker": "8.4.1",
|
|
103
103
|
"@types/mocha": "10.0.6",
|
|
104
|
-
"@types/node": "20.11.
|
|
104
|
+
"@types/node": "20.11.24",
|
|
105
105
|
"@types/sqlite3": "3.1.11",
|
|
106
106
|
"@types/websql": "0.0.30",
|
|
107
107
|
"babel-loader": "9.1.3",
|
|
@@ -109,31 +109,31 @@
|
|
|
109
109
|
"concurrently": "8.2.2",
|
|
110
110
|
"cross-env": "7.0.3",
|
|
111
111
|
"detect-browser": "5.3.0",
|
|
112
|
-
"express": "4.18.
|
|
112
|
+
"express": "4.18.3",
|
|
113
113
|
"get-port": "5.1.1",
|
|
114
114
|
"http-server": "14.1.1",
|
|
115
|
-
"karma": "6.4.
|
|
115
|
+
"karma": "6.4.3",
|
|
116
116
|
"karma-chrome-launcher": "3.2.0",
|
|
117
117
|
"karma-detect-browsers": "2.3.3",
|
|
118
|
-
"karma-firefox-launcher": "2.1.
|
|
118
|
+
"karma-firefox-launcher": "2.1.3",
|
|
119
119
|
"karma-mocha": "2.0.1",
|
|
120
120
|
"karma-sourcemap-loader": "0.4.0",
|
|
121
121
|
"karma-spec-reporter": "0.0.36",
|
|
122
122
|
"karma-typescript": "5.5.4",
|
|
123
123
|
"karma-webpack": "5.0.1",
|
|
124
|
-
"mini-css-extract-plugin": "2.8.
|
|
124
|
+
"mini-css-extract-plugin": "2.8.1",
|
|
125
125
|
"minify-all-js": "0.1.9",
|
|
126
|
-
"mocha": "10.
|
|
126
|
+
"mocha": "10.3.0",
|
|
127
127
|
"rimraf": "5.0.5",
|
|
128
|
-
"rxdb": "15.
|
|
128
|
+
"rxdb": "15.10.0",
|
|
129
129
|
"rxjs": "7.8.1",
|
|
130
130
|
"ts-loader": "9.5.1",
|
|
131
131
|
"ts-mocha": "10.0.0",
|
|
132
132
|
"ts-node": "10.9.2",
|
|
133
133
|
"typescript": "5.3.3",
|
|
134
|
-
"webpack": "5.90.
|
|
134
|
+
"webpack": "5.90.3",
|
|
135
135
|
"webpack-bundle-analyzer": "4.10.1",
|
|
136
136
|
"webpack-cli": "5.1.4",
|
|
137
|
-
"webpack-dev-server": "
|
|
137
|
+
"webpack-dev-server": "5.0.2"
|
|
138
138
|
}
|
|
139
139
|
}
|