rxdb-server 15.7.0 → 15.13.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.
Files changed (55) hide show
  1. package/README.md +4 -0
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/plugins/adapter-express/index.js +122 -0
  4. package/dist/cjs/plugins/adapter-express/index.js.map +1 -0
  5. package/dist/cjs/plugins/client-rest/index.js.map +1 -1
  6. package/dist/cjs/plugins/client-rest/utils.js.map +1 -1
  7. package/dist/cjs/plugins/replication-server/helpers.js.map +1 -1
  8. package/dist/cjs/plugins/replication-server/index.js +1 -1
  9. package/dist/cjs/plugins/replication-server/index.js.map +1 -1
  10. package/dist/cjs/plugins/replication-server/types.js.map +1 -1
  11. package/dist/cjs/plugins/server/endpoint-replication.js +22 -20
  12. package/dist/cjs/plugins/server/endpoint-replication.js.map +1 -1
  13. package/dist/cjs/plugins/server/endpoint-rest.js +33 -31
  14. package/dist/cjs/plugins/server/endpoint-rest.js.map +1 -1
  15. package/dist/cjs/plugins/server/helper.js +6 -45
  16. package/dist/cjs/plugins/server/helper.js.map +1 -1
  17. package/dist/cjs/plugins/server/index.js +5 -15
  18. package/dist/cjs/plugins/server/index.js.map +1 -1
  19. package/dist/cjs/plugins/server/rx-server.js +25 -22
  20. package/dist/cjs/plugins/server/rx-server.js.map +1 -1
  21. package/dist/cjs/plugins/server/types.js.map +1 -1
  22. package/dist/esm/index.js.map +1 -1
  23. package/dist/esm/plugins/adapter-express/index.js +115 -0
  24. package/dist/esm/plugins/adapter-express/index.js.map +1 -0
  25. package/dist/esm/plugins/client-rest/index.js.map +1 -1
  26. package/dist/esm/plugins/client-rest/utils.js.map +1 -1
  27. package/dist/esm/plugins/replication-server/helpers.js.map +1 -1
  28. package/dist/esm/plugins/replication-server/index.js +1 -1
  29. package/dist/esm/plugins/replication-server/index.js.map +1 -1
  30. package/dist/esm/plugins/replication-server/types.js.map +1 -1
  31. package/dist/esm/plugins/server/endpoint-replication.js +23 -21
  32. package/dist/esm/plugins/server/endpoint-replication.js.map +1 -1
  33. package/dist/esm/plugins/server/endpoint-rest.js +34 -32
  34. package/dist/esm/plugins/server/endpoint-rest.js.map +1 -1
  35. package/dist/esm/plugins/server/helper.js +6 -42
  36. package/dist/esm/plugins/server/helper.js.map +1 -1
  37. package/dist/esm/plugins/server/index.js +3 -12
  38. package/dist/esm/plugins/server/index.js.map +1 -1
  39. package/dist/esm/plugins/server/rx-server.js +25 -22
  40. package/dist/esm/plugins/server/rx-server.js.map +1 -1
  41. package/dist/esm/plugins/server/types.js.map +1 -1
  42. package/dist/types/plugins/adapter-express/index.d.ts +7 -0
  43. package/dist/types/plugins/server/endpoint-replication.d.ts +3 -3
  44. package/dist/types/plugins/server/endpoint-rest.d.ts +3 -3
  45. package/dist/types/plugins/server/helper.d.ts +6 -8
  46. package/dist/types/plugins/server/index.d.ts +1 -1
  47. package/dist/types/plugins/server/rx-server.d.ts +12 -11
  48. package/dist/types/plugins/server/types.d.ts +26 -3
  49. package/package.json +33 -27
  50. package/plugins/adapter-express/index.cjs +2 -0
  51. package/plugins/adapter-express/index.d.cts +1 -0
  52. package/plugins/adapter-express/index.d.mts +1 -0
  53. package/plugins/adapter-express/index.mjs +1 -0
  54. package/plugins/adapter-express/index.ts +1 -0
  55. package/plugins/adapter-express/package.json +18 -0
@@ -24,6 +24,7 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
24
24
  this.collection = collection;
25
25
  this.serverOnlyFields = serverOnlyFields;
26
26
  this.cors = cors;
27
+ var adapter = server.adapter;
27
28
  (0, _helper.setCors)(this.server, [this.name].join('/'), cors);
28
29
  (0, _helper.blockPreviousVersionPaths)(this.server, [this.name].join('/'), collection.schema.version);
29
30
  this.urlPath = [this.name, collection.schema.version].join('/');
@@ -42,19 +43,20 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
42
43
  return changeValidator(authData, change);
43
44
  };
44
45
  var removeServerOnlyFields = (0, _helper.removeServerOnlyFieldsMonad)(this.serverOnlyFields);
45
- this.server.expressApp.post('/' + this.urlPath + '/query', async (req, res) => {
46
+ this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/query', async (req, res) => {
47
+ (0, _utils.ensureNotFalsy)(adapter.getRequestBody(req), 'req body is empty');
46
48
  var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
47
49
  var useQuery;
48
50
  try {
49
- useQuery = this.queryModifier((0, _utils.ensureNotFalsy)(authData), (0, _core.normalizeMangoQuery)(this.collection.schema.jsonSchema, req.body));
51
+ useQuery = this.queryModifier((0, _utils.ensureNotFalsy)(authData), (0, _core.normalizeMangoQuery)(this.collection.schema.jsonSchema, adapter.getRequestBody(req)));
50
52
  } catch (err) {
51
- (0, _helper.closeConnection)(res, 400, 'Bad Request');
53
+ adapter.closeConnection(res, 400, 'Bad Request');
52
54
  return;
53
55
  }
54
56
  var rxQuery = this.collection.find(useQuery);
55
57
  var result = await rxQuery.exec();
56
- res.setHeader('Content-Type', 'application/json');
57
- res.json({
58
+ adapter.setResponseHeader(res, 'Content-Type', 'application/json');
59
+ adapter.endResponseJson(res, {
58
60
  documents: result.map(d => removeServerOnlyFields(d.toJSON()))
59
61
  });
60
62
  });
@@ -64,10 +66,10 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
64
66
  * so we send the query as query parameter in base64
65
67
  * like ?query=e3NlbGVjdG9yOiB7fX0=
66
68
  */
67
- this.server.expressApp.get('/' + this.urlPath + '/query/observe', async (req, res) => {
69
+ this.server.adapter.get(this.server.serverApp, '/' + this.urlPath + '/query/observe', async (req, res) => {
68
70
  var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
69
- (0, _helper.writeSSEHeaders)(res);
70
- var useQuery = this.queryModifier((0, _utils.ensureNotFalsy)(authData), (0, _core.normalizeMangoQuery)(this.collection.schema.jsonSchema, JSON.parse(atob(req.query.query))));
71
+ adapter.setSSEHeaders(res);
72
+ var useQuery = this.queryModifier((0, _utils.ensureNotFalsy)(authData), (0, _core.normalizeMangoQuery)(this.collection.schema.jsonSchema, JSON.parse(atob(adapter.getRequestQuery(req).query))));
71
73
  var rxQuery = this.collection.find(useQuery);
72
74
  var subscription = rxQuery.$.pipe((0, _rxjs.mergeMap)(async result => {
73
75
  var resultData = result.map(doc => removeServerOnlyFields(doc.toJSON()));
@@ -78,27 +80,27 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
78
80
  * before emitting the new results.
79
81
  */
80
82
  try {
81
- authData = await server.authHandler(req.headers);
83
+ authData = await server.authHandler(adapter.getRequestHeaders(req));
82
84
  } catch (err) {
83
- (0, _helper.closeConnection)(res, 401, 'Unauthorized');
85
+ adapter.closeConnection(res, 401, 'Unauthorized');
84
86
  return null;
85
87
  }
86
88
  return resultData;
87
89
  }), (0, _rxjs.filter)(f => f !== null)).subscribe(resultData => {
88
- res.write('data: ' + JSON.stringify(resultData) + '\n\n');
90
+ adapter.responseWrite(res, 'data: ' + JSON.stringify(resultData) + '\n\n');
89
91
  });
90
92
 
91
93
  /**
92
94
  * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363
93
95
  */
94
- req.on('close', () => {
96
+ adapter.onRequestClose(req, () => {
95
97
  subscription.unsubscribe();
96
- res.end();
98
+ adapter.endResponse(req);
97
99
  });
98
100
  });
99
- this.server.expressApp.post('/' + this.urlPath + '/get', async (req, res) => {
101
+ this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/get', async (req, res) => {
100
102
  var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
101
- var ids = req.body;
103
+ var ids = adapter.getRequestBody(req);
102
104
  var rxQuery = this.collection.findByIds(ids);
103
105
  var resultMap = await rxQuery.exec();
104
106
  var resultValues = Array.from(resultMap.values());
@@ -106,19 +108,19 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
106
108
  var useDocs = resultValues.map(d => d.toJSON());
107
109
  useDocs = useDocs.filter(d => docMatcher(d));
108
110
  useDocs = useDocs.map(d => removeServerOnlyFields(d));
109
- res.setHeader('Content-Type', 'application/json');
110
- res.json({
111
+ adapter.setResponseHeader(res, 'Content-Type', 'application/json');
112
+ adapter.endResponseJson(res, {
111
113
  documents: useDocs
112
114
  });
113
115
  });
114
- this.server.expressApp.post('/' + this.urlPath + '/set', async (req, res) => {
116
+ this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/set', async (req, res) => {
115
117
  var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
116
118
  var docDataMatcherWrite = (0, _helper.getDocAllowedMatcher)(this, (0, _utils.ensureNotFalsy)(authData));
117
- var docsData = req.body;
119
+ var docsData = adapter.getRequestBody(req);
118
120
  for (var docData of docsData) {
119
121
  var allowed = docDataMatcherWrite(docData);
120
122
  if (!allowed) {
121
- (0, _helper.closeConnection)(res, 403, 'Forbidden');
123
+ adapter.closeConnection(res, 403, 'Forbidden');
122
124
  return;
123
125
  }
124
126
  }
@@ -127,7 +129,7 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
127
129
  // just retry on conflicts
128
130
  docsData.push(docData);
129
131
  } else {
130
- (0, _helper.closeConnection)(res, 500, 'Internal Server Error');
132
+ adapter.closeConnection(res, 500, 'Internal Server Error');
131
133
  throw err;
132
134
  }
133
135
  }
@@ -147,7 +149,7 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
147
149
  assumedMasterState: removeServerOnlyFields(doc.toJSON(true))
148
150
  });
149
151
  if (!isAllowed) {
150
- (0, _helper.closeConnection)(res, 403, 'Forbidden');
152
+ adapter.closeConnection(res, 403, 'Forbidden');
151
153
  return {
152
154
  v: void 0
153
155
  };
@@ -162,13 +164,13 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
162
164
  }
163
165
  await Promise.all(promises);
164
166
  }
165
- res.setHeader('Content-Type', 'application/json');
166
- res.json({});
167
+ adapter.setResponseHeader(res, 'Content-Type', 'application/json');
168
+ adapter.endResponseJson(res, {});
167
169
  });
168
- this.server.expressApp.post('/' + this.urlPath + '/delete', async (req, res) => {
170
+ this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/delete', async (req, res) => {
169
171
  var authData = (0, _utils.getFromMapOrThrow)(authDataByRequest, req);
170
172
  var docDataMatcherWrite = (0, _helper.getDocAllowedMatcher)(this, (0, _utils.ensureNotFalsy)(authData));
171
- var ids = req.body;
173
+ var ids = adapter.getRequestBody(req);
172
174
  while (ids.length > 0) {
173
175
  var useIds = ids.slice(0);
174
176
  ids = [];
@@ -179,7 +181,7 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
179
181
  if (doc) {
180
182
  var isAllowedDoc = docDataMatcherWrite(doc.toJSON(true));
181
183
  if (!isAllowedDoc) {
182
- (0, _helper.closeConnection)(res, 403, 'Forbidden');
184
+ adapter.closeConnection(res, 403, 'Forbidden');
183
185
  return {
184
186
  v: void 0
185
187
  };
@@ -189,7 +191,7 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
189
191
  assumedMasterState: doc.toJSON(true)
190
192
  });
191
193
  if (!isAllowedChange) {
192
- (0, _helper.closeConnection)(res, 403, 'Forbidden');
194
+ adapter.closeConnection(res, 403, 'Forbidden');
193
195
  return {
194
196
  v: void 0
195
197
  };
@@ -199,7 +201,7 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
199
201
  // just retry on conflicts
200
202
  ids.push(id);
201
203
  } else {
202
- (0, _helper.closeConnection)(res, 500, 'Internal Server Error');
204
+ adapter.closeConnection(res, 500, 'Internal Server Error');
203
205
  throw err;
204
206
  }
205
207
  }));
@@ -212,8 +214,8 @@ var RxServerRestEndpoint = exports.RxServerRestEndpoint = function RxServerRestE
212
214
  }
213
215
  await Promise.all(promises);
214
216
  }
215
- res.setHeader('Content-Type', 'application/json');
216
- res.json({});
217
+ adapter.setResponseHeader(res, 'Content-Type', 'application/json');
218
+ adapter.endResponseJson(res, {});
217
219
  });
218
220
  };
219
221
  //# sourceMappingURL=endpoint-rest.js.map
@@ -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,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;EAE7B,IAAAG,eAAO,EAAC,IAAI,CAACT,MAAM,EAAE,CAAC,IAAI,CAACC,IAAI,CAAC,CAACS,IAAI,CAAC,GAAG,CAAC,EAAEJ,IAAI,CAAC;EACjD,IA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AACQ,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","adapter","setCors","join","blockPreviousVersionPaths","schema","version","urlPath","primaryPath","authDataByRequest","addAuthMiddleware","authData","query","doesContainRegexQuerySelector","selector","Error","change","assumedMasterState","docContainsServerOnlyFields","newDocumentState","removeServerOnlyFields","removeServerOnlyFieldsMonad","post","serverApp","req","res","ensureNotFalsy","getRequestBody","getFromMapOrThrow","useQuery","normalizeMangoQuery","jsonSchema","err","closeConnection","rxQuery","find","result","exec","setResponseHeader","endResponseJson","documents","map","d","toJSON","get","setSSEHeaders","JSON","parse","atob","getRequestQuery","subscription","$","pipe","mergeMap","resultData","doc","authHandler","getRequestHeaders","filter","f","subscribe","responseWrite","stringify","onRequestClose","unsubscribe","endResponse","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 docContainsServerOnlyFields,\n doesContainRegexQuerySelector,\n getDocAllowedMatcher,\n removeServerOnlyFieldsMonad,\n setCors\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<ServerAppType, 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<ServerAppType, 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 const adapter = server.adapter;\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.adapter.post(this.server.serverApp, '/' + this.urlPath + '/query', async (req, res) => {\n ensureNotFalsy(adapter.getRequestBody(req), 'req body is empty');\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 adapter.getRequestBody(req)\n )\n );\n } catch (err) {\n adapter.closeConnection(res, 400, 'Bad Request');\n return;\n }\n const rxQuery = this.collection.find(useQuery as any);\n const result = await rxQuery.exec();\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, {\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.adapter.get(this.server.serverApp, '/' + this.urlPath + '/query/observe', async (req, res) => {\n let authData = getFromMapOrThrow(authDataByRequest, req);\n adapter.setSSEHeaders(res);\n\n const useQuery: FilledMangoQuery<RxDocType> = this.queryModifier(\n ensureNotFalsy(authData),\n normalizeMangoQuery(\n this.collection.schema.jsonSchema,\n JSON.parse(atob(adapter.getRequestQuery(req).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(adapter.getRequestHeaders(req));\n } catch (err) {\n adapter.closeConnection(res, 401, 'Unauthorized');\n return null;\n }\n\n return resultData;\n }),\n filter(f => f !== null)\n ).subscribe(resultData => {\n adapter.responseWrite(res, 'data: ' + JSON.stringify(resultData) + '\\n\\n');\n });\n\n /**\n * @link https://youtu.be/0PcMuYGJPzM?si=AxkczxcMaUwhh8k9&t=363\n */\n adapter.onRequestClose(req, () => {\n subscription.unsubscribe();\n adapter.endResponse(req);\n });\n });\n\n\n this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/get', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const ids: string[] = adapter.getRequestBody(req);\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 adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, {\n documents: useDocs\n });\n });\n\n this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/set', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let docsData: RxDocType[] = adapter.getRequestBody(req);\n\n for (const docData of docsData) {\n const allowed = docDataMatcherWrite(docData as any);\n if (!allowed) {\n adapter.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 adapter.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 adapter.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 adapter.setResponseHeader(res, 'Content-Type', 'application/json')\n adapter.endResponseJson(res, {});\n });\n\n this.server.adapter.post(this.server.serverApp, '/' + this.urlPath + '/delete', async (req, res) => {\n const authData = getFromMapOrThrow(authDataByRequest, req);\n const docDataMatcherWrite = getDocAllowedMatcher(this, ensureNotFalsy(authData));\n\n let ids: string[] = adapter.getRequestBody(req);\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 adapter.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 adapter.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 adapter.closeConnection(res, 500, 'Internal Server Error');\n throw err;\n }\n }));\n }\n }\n await Promise.all(promises);\n }\n adapter.setResponseHeader(res, 'Content-Type', 'application/json');\n adapter.endResponseJson(res, {});\n });\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAY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,CAAC5B,GAAG,CAACkD,MAAM,CAAC,CAAC,CAACZ,KAAK,CAAE7D,GAAY,IAAK;cAC/C,IAAIA,GAAG,CAACiD,IAAI,IAAIjD,GAAG,CAACkD,IAAI,KAAK,UAAU,EAAE;gBACrC;gBACAhB,GAAG,CAACiB,IAAI,CAACQ,EAAE,CAAC;cAChB,CAAC,MAAM;gBACH1F,OAAO,CAACgC,eAAe,CAACR,GAAG,EAAE,GAAG,EAAE,uBAAuB,CAAC;gBAC1D,MAAMO,GAAG;cACb;YACJ,CAAC,CAAC,CAAC;UACP;QACJ,CAAC;QAAA0E,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;IACApF,OAAO,CAACqC,iBAAiB,CAACb,GAAG,EAAE,cAAc,EAAE,kBAAkB,CAAC;IAClExB,OAAO,CAACsC,eAAe,CAACd,GAAG,EAAE,CAAC,CAAC,CAAC;EACpC,CAAC,CAAC;AACN,CAAC","ignoreList":[]}
@@ -1,20 +1,16 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
3
  Object.defineProperty(exports, "__esModule", {
5
4
  value: true
6
5
  });
7
6
  exports.addAuthMiddleware = addAuthMiddleware;
8
7
  exports.blockPreviousVersionPaths = blockPreviousVersionPaths;
9
- exports.closeConnection = closeConnection;
10
8
  exports.docContainsServerOnlyFields = docContainsServerOnlyFields;
11
9
  exports.doesContainRegexQuerySelector = doesContainRegexQuerySelector;
12
10
  exports.getDocAllowedMatcher = getDocAllowedMatcher;
13
11
  exports.mergeServerDocumentFieldsMonad = mergeServerDocumentFieldsMonad;
14
12
  exports.removeServerOnlyFieldsMonad = removeServerOnlyFieldsMonad;
15
13
  exports.setCors = setCors;
16
- exports.writeSSEHeaders = writeSSEHeaders;
17
- var _cors = _interopRequireDefault(require("cors"));
18
14
  var _core = require("rxdb/plugins/core");
19
15
  function setCors(server, path, cors) {
20
16
  var useCors = cors;
@@ -22,11 +18,7 @@ function setCors(server, path, cors) {
22
18
  useCors = server.cors;
23
19
  }
24
20
  if (useCors) {
25
- server.expressApp.options('/' + path + '/*', (0, _cors.default)({
26
- origin: useCors,
27
- // some legacy browsers (IE11, various SmartTVs) choke on 204
28
- optionsSuccessStatus: 200
29
- }));
21
+ server.adapter.setCors(server.serverApp, path, useCors);
30
22
  }
31
23
  }
32
24
 
@@ -38,8 +30,8 @@ function blockPreviousVersionPaths(server, path, currentVersion) {
38
30
  var v = 0;
39
31
  var _loop = function () {
40
32
  var version = v;
41
- server.expressApp.all('/' + path + '/' + version + '/*', (req, res) => {
42
- closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');
33
+ server.adapter.all(server.serverApp, '/' + path + '/' + version + '/*', (req, res) => {
34
+ server.adapter.closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');
43
35
  });
44
36
  v++;
45
37
  };
@@ -47,17 +39,6 @@ function blockPreviousVersionPaths(server, path, currentVersion) {
47
39
  _loop();
48
40
  }
49
41
  }
50
- async function closeConnection(response, code, message) {
51
- var responseWrite = {
52
- code,
53
- error: true,
54
- message
55
- };
56
- response.statusCode = code;
57
- response.set("Connection", "close");
58
- await response.write(JSON.stringify(responseWrite));
59
- response.end();
60
- }
61
42
  function addAuthMiddleware(server, path) {
62
43
  var authDataByRequest = new WeakMap();
63
44
  async function auth(req, res, next) {
@@ -66,13 +47,11 @@ function addAuthMiddleware(server, path) {
66
47
  authDataByRequest.set(req, authData);
67
48
  next();
68
49
  } catch (err) {
69
- closeConnection(res, 401, 'Unauthorized');
50
+ server.adapter.closeConnection(res, 401, 'Unauthorized');
70
51
  return;
71
52
  }
72
53
  }
73
- server.expressApp.all('/' + path + '/*', auth, function (req, res, next) {
74
- next();
75
- });
54
+ server.adapter.all(server.serverApp, '/' + path + '/*', auth);
76
55
  return authDataByRequest;
77
56
  }
78
57
  var defaultMatchingQuery = {
@@ -85,24 +64,6 @@ function getDocAllowedMatcher(endpoint, authData) {
85
64
  var docDataMatcher = (0, _core.getQueryMatcher)(endpoint.collection.schema.jsonSchema, useQuery);
86
65
  return docDataMatcher;
87
66
  }
88
- function writeSSEHeaders(res) {
89
- res.writeHead(200, {
90
- /**
91
- * Use exact these headers to make is less likely
92
- * for people to have problems.
93
- * @link https://www.youtube.com/watch?v=0PcMuYGJPzM
94
- */
95
- 'Content-Type': 'text/event-stream; charset=utf-8',
96
- 'Connection': 'keep-alive',
97
- 'Cache-Control': 'no-cache',
98
- /**
99
- * Required for nginx
100
- * @link https://stackoverflow.com/q/61029079/3443137
101
- */
102
- 'X-Accel-Buffering': 'no'
103
- });
104
- res.flushHeaders();
105
- }
106
67
  function docContainsServerOnlyFields(serverOnlyFields, doc) {
107
68
  var has = serverOnlyFields.find(field => {
108
69
  return typeof doc[field] !== 'undefined';
@@ -142,7 +103,7 @@ function mergeServerDocumentFieldsMonad(serverOnlyFields) {
142
103
  }
143
104
 
144
105
  /**
145
- * $regex queries are dangerous because they can dos-attach the
106
+ * $regex queries are dangerous because they can dos-attack the server.
146
107
  *
147
108
  * @param selector
148
109
  */
@@ -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,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,OAAO;MACf;MACAK,oBAAoB,EAAE;IAC1B,CAAC,CAAC,CAAC;EACP;AACJ;;AAEA;AACA;AACA;AACA;AACO,SAASC,yBAAyBA,CACrCT,MAAqB,EACrBC,IAAY,EACZS,cAAsB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AAI,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":["_core","require","setCors","server","path","cors","useCors","adapter","serverApp","blockPreviousVersionPaths","currentVersion","v","_loop","version","all","req","res","closeConnection","addAuthMiddleware","authDataByRequest","WeakMap","auth","next","authData","authHandler","headers","set","err","defaultMatchingQuery","selector","skip","sort","getDocAllowedMatcher","endpoint","useQuery","queryModifier","normalizeMangoQuery","collection","schema","jsonSchema","docDataMatcher","getQueryMatcher","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 type {\n Request,\n Response,\n NextFunction\n} from 'express';\nimport type { RxServerAdapter, RxServerAuthData, RxServerEndpoint } from './types';\nimport {\n FilledMangoQuery,\n MangoQuerySelector,\n RxDocumentData,\n flatClone,\n getQueryMatcher,\n normalizeMangoQuery,\n uniqueArray\n} from 'rxdb/plugins/core';\n\nexport function setCors(\n server: RxServer<any, 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.adapter.setCors(server.serverApp, path, useCors);\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, any>,\n path: string,\n currentVersion: number\n\n) {\n let v = 0;\n while (v < currentVersion) {\n const version = v;\n server.adapter.all(server.serverApp, '/' + path + '/' + version + '/*', (req, res) => {\n server.adapter.closeConnection(res, 426, 'Outdated version ' + version + ' (newest is ' + currentVersion + ')');\n });\n v++;\n }\n}\n\n\nexport function addAuthMiddleware<AuthType>(\n server: RxServer<any, AuthType>,\n path: string,\n): WeakMap<Request, RxServerAuthData<AuthType>> {\n const authDataByRequest = new WeakMap<Request, RxServerAuthData<AuthType>>();\n async function auth(req: any, res: any, next: NextFunction) {\n try {\n const authData = await server.authHandler(req.headers);\n authDataByRequest.set(req, authData);\n next();\n } catch (err) {\n server.adapter.closeConnection(res, 401, 'Unauthorized');\n return;\n }\n }\n server.adapter.all(server.serverApp, '/' + path + '/*', auth);\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\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-attack the server.\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":";;;;;;;;;;;;;AAOA,IAAAA,KAAA,GAAAC,OAAA;AAUO,SAASC,OAAOA,CACnBC,MAA0B,EAC1BC,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,CAAC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J;EAEA,OAAO,KAAK;AAChB","ignoreList":[]}
@@ -1,16 +1,14 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
3
  Object.defineProperty(exports, "__esModule", {
5
4
  value: true
6
5
  });
7
6
  var _exportNames = {
8
- startRxServer: true
7
+ createRxServer: true
9
8
  };
10
- exports.startRxServer = startRxServer;
9
+ exports.createRxServer = createRxServer;
11
10
  var _utils = require("rxdb/plugins/utils");
12
11
  var _rxServer = require("./rx-server.js");
13
- var _express = _interopRequireDefault(require("express"));
14
12
  var _types = require("./types.js");
15
13
  Object.keys(_types).forEach(function (key) {
16
14
  if (key === "default" || key === "__esModule") return;
@@ -59,26 +57,18 @@ Object.keys(_helper).forEach(function (key) {
59
57
  }
60
58
  });
61
59
  });
62
- async function startRxServer(options) {
60
+ async function createRxServer(options) {
63
61
  options = (0, _utils.flatClone)(options);
64
62
  if (!options.serverApp) {
65
- var app = (0, _express.default)();
66
- options.serverApp = app;
63
+ options.serverApp = await options.adapter.create();
67
64
  }
68
- options.serverApp.use(_express.default.json());
69
- var httpServer = await new Promise((res, rej) => {
70
- var hostname = options.hostname ? options.hostname : 'localhost';
71
- var ret = (0, _utils.ensureNotFalsy)(options.serverApp).listen(options.port, hostname, () => {
72
- res(ret);
73
- });
74
- });
75
65
  var authHandler = options.authHandler ? options.authHandler : () => {
76
66
  return {
77
67
  data: {},
78
68
  validUntil: Date.now() * 2
79
69
  };
80
70
  };
81
- var server = new _rxServer.RxServer(options.database, authHandler, httpServer, (0, _utils.ensureNotFalsy)(options.serverApp), options.cors);
71
+ var server = new _rxServer.RxServer(options, authHandler, (0, _utils.ensureNotFalsy)(options.serverApp), options.cors);
82
72
  return server;
83
73
  }
84
74
  //# sourceMappingURL=index.js.map
@@ -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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C,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","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_endpointReplication","_endpointRest","_helper","createRxServer","options","flatClone","serverApp","adapter","create","authHandler","data","validUntil","Date","now","server","RxServer","ensureNotFalsy","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';\n\nexport * from './types.ts';\nexport * from './endpoint-replication.ts';\nexport * from './endpoint-rest.ts';\nexport * from './helper.ts';\n\nexport async function createRxServer<ServerAdapterType, AuthType>(\n options: RxServerOptions<ServerAdapterType, AuthType>\n): Promise<RxServer<ServerAdapterType, AuthType>> {\n options = flatClone(options);\n if (!options.serverApp) {\n options.serverApp = await options.adapter.create();\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<ServerAdapterType, AuthType>(\n options,\n authHandler,\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;AAGA,IAAAE,MAAA,GAAAF,OAAA;AAAAG,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YA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A,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,MAAAW,OAAA,CAAAX,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAG,OAAA,CAAAX,GAAA;IAAA;EAAA;AAAA;AAEO,eAAeY,cAAcA,CAChCC,OAAqD,EACP;EAC9CA,OAAO,GAAG,IAAAC,gBAAS,EAACD,OAAO,CAAC;EAC5B,IAAI,CAACA,OAAO,CAACE,SAAS,EAAE;IACpBF,OAAO,CAACE,SAAS,GAAG,MAAMF,OAAO,CAACG,OAAO,CAACC,MAAM,CAAC,CAAC;EACtD;EACA,IAAMC,WAA0C,GAAGL,OAAO,CAACK,WAAW,GAAGL,OAAO,CAACK,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,CACvBX,OAAO,EACPK,WAAW,EACX,IAAAO,qBAAc,EAACZ,OAAO,CAACE,SAAS,CAAC,EACjCF,OAAO,CAACa,IACZ,CAAC;EAED,OAAOH,MAAM;AACjB","ignoreList":[]}
@@ -7,44 +7,47 @@ exports.RxServer = void 0;
7
7
  var _endpointReplication = require("./endpoint-replication.js");
8
8
  var _endpointRest = require("./endpoint-rest.js");
9
9
  var RxServer = exports.RxServer = /*#__PURE__*/function () {
10
- function RxServer(database, authHandler, httpServer, expressApp, cors = '*') {
10
+ function RxServer(options, authHandler, serverApp, cors = '*') {
11
11
  this.endpoints = [];
12
12
  this.closeFn = (() => this.close()).bind(this);
13
- this.database = database;
13
+ this.options = options;
14
14
  this.authHandler = authHandler;
15
- this.httpServer = httpServer;
16
- this.expressApp = expressApp;
15
+ this.serverApp = serverApp;
17
16
  this.cors = cors;
18
- database.onDestroy.push(this.closeFn);
17
+ this.database = options.database;
18
+ this.adapter = options.adapter;
19
+ options.database.onDestroy.push(this.closeFn);
19
20
  }
20
21
  var _proto = RxServer.prototype;
21
- _proto.addReplicationEndpoint = async function addReplicationEndpoint(opts) {
22
+ _proto.ensureNotStarted = function ensureNotStarted() {
23
+ if (this.listenPromise) {
24
+ throw new Error('This operation cannot be run after the RxServer has been started already');
25
+ }
26
+ };
27
+ _proto.addReplicationEndpoint = function addReplicationEndpoint(opts) {
28
+ this.ensureNotStarted();
22
29
  var endpoint = new _endpointReplication.RxServerReplicationEndpoint(this, opts.name, opts.collection, opts.queryModifier ? opts.queryModifier : (_a, q) => q, opts.changeValidator ? opts.changeValidator : () => true, opts.serverOnlyFields ? opts.serverOnlyFields : [], opts.cors);
23
30
  this.endpoints.push(endpoint);
24
31
  return endpoint;
25
32
  };
26
- _proto.addRestEndpoint = async function addRestEndpoint(opts) {
33
+ _proto.addRestEndpoint = function addRestEndpoint(opts) {
34
+ this.ensureNotStarted();
27
35
  var endpoint = new _endpointRest.RxServerRestEndpoint(this, opts.name, opts.collection, opts.queryModifier ? opts.queryModifier : (_a, q) => q, opts.changeValidator ? opts.changeValidator : () => true, opts.serverOnlyFields ? opts.serverOnlyFields : [], opts.cors);
28
36
  this.endpoints.push(endpoint);
29
37
  return endpoint;
30
38
  };
39
+ _proto.start = async function start() {
40
+ this.ensureNotStarted();
41
+ var hostname = this.options.hostname ? this.options.hostname : 'localhost';
42
+ this.listenPromise = this.options.adapter.listen(this.serverApp, this.options.port, hostname);
43
+ return this.listenPromise;
44
+ };
31
45
  _proto.close = async function close() {
32
46
  this.database.onDestroy = this.database.onDestroy.filter(fn => fn !== this.closeFn);
33
- await new Promise((res, rej) => {
34
- this.httpServer.close(err => {
35
- if (err) {
36
- rej(err);
37
- } else {
38
- res();
39
- }
40
- });
41
- /**
42
- * By default it will await all ongoing connections
43
- * before it closes. So we have to close it directly.
44
- * @link https://stackoverflow.com/a/36830072/3443137
45
- */
46
- setImmediate(() => this.httpServer.emit('close'));
47
- });
47
+ if (this.listenPromise) {
48
+ await this.listenPromise;
49
+ await this.options.adapter.close(this.serverApp);
50
+ }
48
51
  };
49
52
  return RxServer;
50
53
  }();