@niledatabase/server 3.0.0-alpha.9 → 3.0.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 (75) hide show
  1. package/dist/express.d.mts +24 -0
  2. package/dist/express.d.ts +24 -0
  3. package/dist/express.js +147 -0
  4. package/dist/express.js.map +1 -0
  5. package/dist/express.mjs +144 -0
  6. package/dist/express.mjs.map +1 -0
  7. package/dist/index.d.mts +323 -0
  8. package/dist/index.d.ts +323 -5
  9. package/dist/index.js +2382 -5
  10. package/dist/index.js.map +1 -0
  11. package/dist/index.mjs +2377 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/package.json +17 -4
  14. package/dist/Api.d.ts +0 -22
  15. package/dist/Server.d.ts +0 -29
  16. package/dist/api/handlers/DELETE.d.ts +0 -3
  17. package/dist/api/handlers/GET.d.ts +0 -3
  18. package/dist/api/handlers/POST.d.ts +0 -3
  19. package/dist/api/handlers/PUT.d.ts +0 -3
  20. package/dist/api/handlers/index.d.ts +0 -8
  21. package/dist/api/routes/auth/callback.d.ts +0 -3
  22. package/dist/api/routes/auth/csrf.d.ts +0 -3
  23. package/dist/api/routes/auth/error.d.ts +0 -3
  24. package/dist/api/routes/auth/index.d.ts +0 -7
  25. package/dist/api/routes/auth/providers.d.ts +0 -3
  26. package/dist/api/routes/auth/session.d.ts +0 -4
  27. package/dist/api/routes/auth/signin.d.ts +0 -33
  28. package/dist/api/routes/auth/signout.d.ts +0 -3
  29. package/dist/api/routes/me/index.d.ts +0 -4
  30. package/dist/api/routes/tenants/GET.d.ts +0 -32
  31. package/dist/api/routes/tenants/POST.d.ts +0 -45
  32. package/dist/api/routes/tenants/[tenantId]/DELETE.d.ts +0 -34
  33. package/dist/api/routes/tenants/[tenantId]/users/GET.d.ts +0 -35
  34. package/dist/api/routes/tenants/[tenantId]/users/POST.d.ts +0 -44
  35. package/dist/api/routes/tenants/[tenantId]/users/PUT.d.ts +0 -29
  36. package/dist/api/routes/tenants/[tenantId]/users/[userId]/DELETE.d.ts +0 -30
  37. package/dist/api/routes/tenants/[tenantId]/users/index.d.ts +0 -4
  38. package/dist/api/routes/tenants/index.d.ts +0 -4
  39. package/dist/api/routes/users/GET.d.ts +0 -34
  40. package/dist/api/routes/users/POST.d.ts +0 -66
  41. package/dist/api/routes/users/[userId]/PUT.d.ts +0 -40
  42. package/dist/api/routes/users/index.d.ts +0 -4
  43. package/dist/api/swagger.d.ts +0 -152
  44. package/dist/api/types.d.ts +0 -18
  45. package/dist/api/utils/auth.d.ts +0 -14
  46. package/dist/api/utils/request.d.ts +0 -4
  47. package/dist/api/utils/routes/apiRoutes.d.ts +0 -14
  48. package/dist/api/utils/routes/defaultRoutes.d.ts +0 -2
  49. package/dist/api/utils/routes/makeRestUrl.d.ts +0 -1
  50. package/dist/api/utils/routes/proxyRoutes.d.ts +0 -12
  51. package/dist/api/utils/routes/urlMatches.d.ts +0 -1
  52. package/dist/auth/index.d.ts +0 -13
  53. package/dist/db/DBManager.d.ts +0 -12
  54. package/dist/db/NileInstance.d.ts +0 -14
  55. package/dist/db/PoolProxy.d.ts +0 -3
  56. package/dist/db/index.d.ts +0 -1
  57. package/dist/db/isUUID.d.ts +0 -1
  58. package/dist/server.cjs.development.js +0 -3976
  59. package/dist/server.cjs.development.js.map +0 -1
  60. package/dist/server.cjs.production.min.js +0 -2
  61. package/dist/server.cjs.production.min.js.map +0 -1
  62. package/dist/server.esm.js +0 -3974
  63. package/dist/server.esm.js.map +0 -1
  64. package/dist/tenants/index.d.ts +0 -21
  65. package/dist/types.d.ts +0 -37
  66. package/dist/users/index.d.ts +0 -52
  67. package/dist/utils/Config/envVars.d.ts +0 -22
  68. package/dist/utils/Config/index.d.ts +0 -47
  69. package/dist/utils/Event/index.d.ts +0 -12
  70. package/dist/utils/Logger.d.ts +0 -7
  71. package/dist/utils/Requester/index.d.ts +0 -23
  72. package/dist/utils/Requester/types.d.ts +0 -88
  73. package/dist/utils/ResponseError.d.ts +0 -4
  74. package/dist/utils/Server/index.d.ts +0 -4
  75. package/dist/utils/fetch.d.ts +0 -9
@@ -1,3976 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- require('dotenv/config');
6
- var pg = require('pg');
7
- var jose = require('jose');
8
-
9
- function _regeneratorRuntime() {
10
- _regeneratorRuntime = function () {
11
- return e;
12
- };
13
- var t,
14
- e = {},
15
- r = Object.prototype,
16
- n = r.hasOwnProperty,
17
- o = Object.defineProperty || function (t, e, r) {
18
- t[e] = r.value;
19
- },
20
- i = "function" == typeof Symbol ? Symbol : {},
21
- a = i.iterator || "@@iterator",
22
- c = i.asyncIterator || "@@asyncIterator",
23
- u = i.toStringTag || "@@toStringTag";
24
- function define(t, e, r) {
25
- return Object.defineProperty(t, e, {
26
- value: r,
27
- enumerable: !0,
28
- configurable: !0,
29
- writable: !0
30
- }), t[e];
31
- }
32
- try {
33
- define({}, "");
34
- } catch (t) {
35
- define = function (t, e, r) {
36
- return t[e] = r;
37
- };
38
- }
39
- function wrap(t, e, r, n) {
40
- var i = e && e.prototype instanceof Generator ? e : Generator,
41
- a = Object.create(i.prototype),
42
- c = new Context(n || []);
43
- return o(a, "_invoke", {
44
- value: makeInvokeMethod(t, r, c)
45
- }), a;
46
- }
47
- function tryCatch(t, e, r) {
48
- try {
49
- return {
50
- type: "normal",
51
- arg: t.call(e, r)
52
- };
53
- } catch (t) {
54
- return {
55
- type: "throw",
56
- arg: t
57
- };
58
- }
59
- }
60
- e.wrap = wrap;
61
- var h = "suspendedStart",
62
- l = "suspendedYield",
63
- f = "executing",
64
- s = "completed",
65
- y = {};
66
- function Generator() {}
67
- function GeneratorFunction() {}
68
- function GeneratorFunctionPrototype() {}
69
- var p = {};
70
- define(p, a, function () {
71
- return this;
72
- });
73
- var d = Object.getPrototypeOf,
74
- v = d && d(d(values([])));
75
- v && v !== r && n.call(v, a) && (p = v);
76
- var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
77
- function defineIteratorMethods(t) {
78
- ["next", "throw", "return"].forEach(function (e) {
79
- define(t, e, function (t) {
80
- return this._invoke(e, t);
81
- });
82
- });
83
- }
84
- function AsyncIterator(t, e) {
85
- function invoke(r, o, i, a) {
86
- var c = tryCatch(t[r], t, o);
87
- if ("throw" !== c.type) {
88
- var u = c.arg,
89
- h = u.value;
90
- return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
91
- invoke("next", t, i, a);
92
- }, function (t) {
93
- invoke("throw", t, i, a);
94
- }) : e.resolve(h).then(function (t) {
95
- u.value = t, i(u);
96
- }, function (t) {
97
- return invoke("throw", t, i, a);
98
- });
99
- }
100
- a(c.arg);
101
- }
102
- var r;
103
- o(this, "_invoke", {
104
- value: function (t, n) {
105
- function callInvokeWithMethodAndArg() {
106
- return new e(function (e, r) {
107
- invoke(t, n, e, r);
108
- });
109
- }
110
- return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
111
- }
112
- });
113
- }
114
- function makeInvokeMethod(e, r, n) {
115
- var o = h;
116
- return function (i, a) {
117
- if (o === f) throw Error("Generator is already running");
118
- if (o === s) {
119
- if ("throw" === i) throw a;
120
- return {
121
- value: t,
122
- done: !0
123
- };
124
- }
125
- for (n.method = i, n.arg = a;;) {
126
- var c = n.delegate;
127
- if (c) {
128
- var u = maybeInvokeDelegate(c, n);
129
- if (u) {
130
- if (u === y) continue;
131
- return u;
132
- }
133
- }
134
- if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
135
- if (o === h) throw o = s, n.arg;
136
- n.dispatchException(n.arg);
137
- } else "return" === n.method && n.abrupt("return", n.arg);
138
- o = f;
139
- var p = tryCatch(e, r, n);
140
- if ("normal" === p.type) {
141
- if (o = n.done ? s : l, p.arg === y) continue;
142
- return {
143
- value: p.arg,
144
- done: n.done
145
- };
146
- }
147
- "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
148
- }
149
- };
150
- }
151
- function maybeInvokeDelegate(e, r) {
152
- var n = r.method,
153
- o = e.iterator[n];
154
- if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
155
- var i = tryCatch(o, e.iterator, r.arg);
156
- if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
157
- var a = i.arg;
158
- return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
159
- }
160
- function pushTryEntry(t) {
161
- var e = {
162
- tryLoc: t[0]
163
- };
164
- 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
165
- }
166
- function resetTryEntry(t) {
167
- var e = t.completion || {};
168
- e.type = "normal", delete e.arg, t.completion = e;
169
- }
170
- function Context(t) {
171
- this.tryEntries = [{
172
- tryLoc: "root"
173
- }], t.forEach(pushTryEntry, this), this.reset(!0);
174
- }
175
- function values(e) {
176
- if (e || "" === e) {
177
- var r = e[a];
178
- if (r) return r.call(e);
179
- if ("function" == typeof e.next) return e;
180
- if (!isNaN(e.length)) {
181
- var o = -1,
182
- i = function next() {
183
- for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
184
- return next.value = t, next.done = !0, next;
185
- };
186
- return i.next = i;
187
- }
188
- }
189
- throw new TypeError(typeof e + " is not iterable");
190
- }
191
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
192
- value: GeneratorFunctionPrototype,
193
- configurable: !0
194
- }), o(GeneratorFunctionPrototype, "constructor", {
195
- value: GeneratorFunction,
196
- configurable: !0
197
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
198
- var e = "function" == typeof t && t.constructor;
199
- return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
200
- }, e.mark = function (t) {
201
- return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
202
- }, e.awrap = function (t) {
203
- return {
204
- __await: t
205
- };
206
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
207
- return this;
208
- }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
209
- void 0 === i && (i = Promise);
210
- var a = new AsyncIterator(wrap(t, r, n, o), i);
211
- return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
212
- return t.done ? t.value : a.next();
213
- });
214
- }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
215
- return this;
216
- }), define(g, "toString", function () {
217
- return "[object Generator]";
218
- }), e.keys = function (t) {
219
- var e = Object(t),
220
- r = [];
221
- for (var n in e) r.push(n);
222
- return r.reverse(), function next() {
223
- for (; r.length;) {
224
- var t = r.pop();
225
- if (t in e) return next.value = t, next.done = !1, next;
226
- }
227
- return next.done = !0, next;
228
- };
229
- }, e.values = values, Context.prototype = {
230
- constructor: Context,
231
- reset: function (e) {
232
- if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
233
- },
234
- stop: function () {
235
- this.done = !0;
236
- var t = this.tryEntries[0].completion;
237
- if ("throw" === t.type) throw t.arg;
238
- return this.rval;
239
- },
240
- dispatchException: function (e) {
241
- if (this.done) throw e;
242
- var r = this;
243
- function handle(n, o) {
244
- return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
245
- }
246
- for (var o = this.tryEntries.length - 1; o >= 0; --o) {
247
- var i = this.tryEntries[o],
248
- a = i.completion;
249
- if ("root" === i.tryLoc) return handle("end");
250
- if (i.tryLoc <= this.prev) {
251
- var c = n.call(i, "catchLoc"),
252
- u = n.call(i, "finallyLoc");
253
- if (c && u) {
254
- if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
255
- if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
256
- } else if (c) {
257
- if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
258
- } else {
259
- if (!u) throw Error("try statement without catch or finally");
260
- if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
261
- }
262
- }
263
- }
264
- },
265
- abrupt: function (t, e) {
266
- for (var r = this.tryEntries.length - 1; r >= 0; --r) {
267
- var o = this.tryEntries[r];
268
- if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
269
- var i = o;
270
- break;
271
- }
272
- }
273
- i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
274
- var a = i ? i.completion : {};
275
- return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
276
- },
277
- complete: function (t, e) {
278
- if ("throw" === t.type) throw t.arg;
279
- return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
280
- },
281
- finish: function (t) {
282
- for (var e = this.tryEntries.length - 1; e >= 0; --e) {
283
- var r = this.tryEntries[e];
284
- if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
285
- }
286
- },
287
- catch: function (t) {
288
- for (var e = this.tryEntries.length - 1; e >= 0; --e) {
289
- var r = this.tryEntries[e];
290
- if (r.tryLoc === t) {
291
- var n = r.completion;
292
- if ("throw" === n.type) {
293
- var o = n.arg;
294
- resetTryEntry(r);
295
- }
296
- return o;
297
- }
298
- }
299
- throw Error("illegal catch attempt");
300
- },
301
- delegateYield: function (e, r, n) {
302
- return this.delegate = {
303
- iterator: values(e),
304
- resultName: r,
305
- nextLoc: n
306
- }, "next" === this.method && (this.arg = t), y;
307
- }
308
- }, e;
309
- }
310
- function _toPrimitive(t, r) {
311
- if ("object" != typeof t || !t) return t;
312
- var e = t[Symbol.toPrimitive];
313
- if (void 0 !== e) {
314
- var i = e.call(t, r || "default");
315
- if ("object" != typeof i) return i;
316
- throw new TypeError("@@toPrimitive must return a primitive value.");
317
- }
318
- return ("string" === r ? String : Number)(t);
319
- }
320
- function _toPropertyKey(t) {
321
- var i = _toPrimitive(t, "string");
322
- return "symbol" == typeof i ? i : i + "";
323
- }
324
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
325
- try {
326
- var info = gen[key](arg);
327
- var value = info.value;
328
- } catch (error) {
329
- reject(error);
330
- return;
331
- }
332
- if (info.done) {
333
- resolve(value);
334
- } else {
335
- Promise.resolve(value).then(_next, _throw);
336
- }
337
- }
338
- function _asyncToGenerator(fn) {
339
- return function () {
340
- var self = this,
341
- args = arguments;
342
- return new Promise(function (resolve, reject) {
343
- var gen = fn.apply(self, args);
344
- function _next(value) {
345
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
346
- }
347
- function _throw(err) {
348
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
349
- }
350
- _next(undefined);
351
- });
352
- };
353
- }
354
- function _defineProperties(target, props) {
355
- for (var i = 0; i < props.length; i++) {
356
- var descriptor = props[i];
357
- descriptor.enumerable = descriptor.enumerable || false;
358
- descriptor.configurable = true;
359
- if ("value" in descriptor) descriptor.writable = true;
360
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
361
- }
362
- }
363
- function _createClass(Constructor, protoProps, staticProps) {
364
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
365
- if (staticProps) _defineProperties(Constructor, staticProps);
366
- Object.defineProperty(Constructor, "prototype", {
367
- writable: false
368
- });
369
- return Constructor;
370
- }
371
- function _extends() {
372
- _extends = Object.assign ? Object.assign.bind() : function (target) {
373
- for (var i = 1; i < arguments.length; i++) {
374
- var source = arguments[i];
375
- for (var key in source) {
376
- if (Object.prototype.hasOwnProperty.call(source, key)) {
377
- target[key] = source[key];
378
- }
379
- }
380
- }
381
- return target;
382
- };
383
- return _extends.apply(this, arguments);
384
- }
385
- function _inheritsLoose(subClass, superClass) {
386
- subClass.prototype = Object.create(superClass.prototype);
387
- subClass.prototype.constructor = subClass;
388
- _setPrototypeOf(subClass, superClass);
389
- }
390
- function _setPrototypeOf(o, p) {
391
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
392
- o.__proto__ = p;
393
- return o;
394
- };
395
- return _setPrototypeOf(o, p);
396
- }
397
- function _objectWithoutPropertiesLoose(source, excluded) {
398
- if (source == null) return {};
399
- var target = {};
400
- var sourceKeys = Object.keys(source);
401
- var key, i;
402
- for (i = 0; i < sourceKeys.length; i++) {
403
- key = sourceKeys[i];
404
- if (excluded.indexOf(key) >= 0) continue;
405
- target[key] = source[key];
406
- }
407
- return target;
408
- }
409
- function _unsupportedIterableToArray(o, minLen) {
410
- if (!o) return;
411
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
412
- var n = Object.prototype.toString.call(o).slice(8, -1);
413
- if (n === "Object" && o.constructor) n = o.constructor.name;
414
- if (n === "Map" || n === "Set") return Array.from(o);
415
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
416
- }
417
- function _arrayLikeToArray(arr, len) {
418
- if (len == null || len > arr.length) len = arr.length;
419
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
420
- return arr2;
421
- }
422
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
423
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
424
- if (it) return (it = it.call(o)).next.bind(it);
425
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
426
- if (it) o = it;
427
- var i = 0;
428
- return function () {
429
- if (i >= o.length) return {
430
- done: true
431
- };
432
- return {
433
- done: false,
434
- value: o[i++]
435
- };
436
- };
437
- }
438
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
439
- }
440
-
441
- function Logger(config) {
442
- for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
443
- params[_key - 1] = arguments[_key];
444
- }
445
- return {
446
- info: function info() {
447
- if (config != null && config.debug) {
448
- var _console;
449
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
450
- args[_key2] = arguments[_key2];
451
- }
452
- // eslint-disable-next-line no-console
453
- (_console = console).info.apply(_console, ['[niledb]'].concat(params, args));
454
- }
455
- },
456
- warn: function warn() {
457
- if (config != null && config.debug) {
458
- var _console2;
459
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
460
- args[_key3] = arguments[_key3];
461
- }
462
- // eslint-disable-next-line no-console
463
- (_console2 = console).warn.apply(_console2, ['[niledb]'].concat(params, args));
464
- }
465
- },
466
- error: function error() {
467
- var _console3;
468
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
469
- args[_key4] = arguments[_key4];
470
- }
471
- // eslint-disable-next-line no-console
472
- (_console3 = console).error.apply(_console3, ['[niledb]', '[ERROR]'].concat(params, args));
473
- }
474
- };
475
- }
476
-
477
- var getDatabaseId = function getDatabaseId(cfg) {
478
- var config = cfg.config,
479
- logger = cfg.logger;
480
- var _Logger = Logger(config, '[databaseId]'),
481
- info = _Logger.info;
482
- if (config != null && config.databaseId) {
483
- logger && info(logger, 'config', config.databaseId);
484
- return String(config == null ? void 0 : config.databaseId);
485
- }
486
- if (process.env.NILEDB_POSTGRES_URL) {
487
- var pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
488
- return pgUrl.pathname.substring(1);
489
- }
490
- logger && info(logger, 'env', process.env.NILEDB_ID);
491
- return process.env.NILEDB_ID;
492
- };
493
- var getUsername = function getUsername(cfg) {
494
- var config = cfg.config,
495
- logger = cfg.logger;
496
- var _Logger2 = Logger(config, '[username]'),
497
- info = _Logger2.info;
498
- if (config != null && config.user) {
499
- logger && info(logger, 'config', config.user);
500
- return String(config == null ? void 0 : config.user);
501
- }
502
- logger && info(logger, 'NILEDB_USER', process.env.NILEDB_USER);
503
- return process.env.NILEDB_USER;
504
- };
505
- var getPassword = function getPassword(cfg) {
506
- var config = cfg.config,
507
- logger = cfg.logger;
508
- var log = logProtector(logger);
509
- var _Logger3 = Logger(config, '[password]'),
510
- info = _Logger3.info;
511
- if (config != null && config.password) {
512
- log && info(logger, 'config', config.password);
513
- return String(config.password);
514
- }
515
- log && info(logger, 'NILEDB_PASSWORD', process.env.NILEDB_PASSWORD);
516
- return process.env.NILEDB_PASSWORD;
517
- };
518
- var getInfoBearer = function getInfoBearer(cfg) {
519
- return getUsername(cfg) + ":" + getPassword(cfg);
520
- };
521
- var getToken = function getToken(cfg) {
522
- var _config$api;
523
- var config = cfg.config,
524
- logger = cfg.logger;
525
- var _Logger4 = Logger(config, '[token]'),
526
- info = _Logger4.info;
527
- if (config != null && (_config$api = config.api) != null && _config$api.token) {
528
- var _config$api2, _config$api3;
529
- logger && info(logger, 'config', (_config$api2 = config.api) == null ? void 0 : _config$api2.token);
530
- return String((_config$api3 = config.api) == null ? void 0 : _config$api3.token);
531
- }
532
- if (process.env.NILEDB_TOKEN) {
533
- logger && info(logger, 'NILEDB_TOKEN', process.env.NILEDB_TOKEN);
534
- return process.env.NILEDB_TOKEN;
535
- }
536
- return undefined;
537
- };
538
- var getDatabaseName = function getDatabaseName(cfg) {
539
- var config = cfg.config,
540
- logger = cfg.logger;
541
- var _Logger5 = Logger(config, '[databaseName]'),
542
- info = _Logger5.info;
543
- if (config != null && config.databaseName) {
544
- logger && info(logger, 'config', config.databaseName);
545
- return String(config.databaseName);
546
- }
547
- if (process.env.NILEDB_NAME) {
548
- logger && info(logger, 'NILEDB_NAME', process.env.NILEDB_NAME);
549
- return process.env.NILEDB_NAME;
550
- }
551
- return null;
552
- };
553
- var getTenantId = function getTenantId(cfg) {
554
- var config = cfg.config,
555
- logger = cfg.logger;
556
- var _Logger6 = Logger(config, '[tenantId]'),
557
- info = _Logger6.info;
558
- if (config != null && config.tenantId) {
559
- logger && info(logger, 'config', config.tenantId);
560
- return config.tenantId;
561
- }
562
- if (process.env.NILEDB_TENANT) {
563
- logger && info(logger, 'NILEDB_TENANT', process.env.NILEDB_TENANT);
564
- return process.env.NILEDB_TENANT;
565
- }
566
- return null;
567
- };
568
- var getLocal = function getLocal(cfg) {
569
- var config = cfg.config,
570
- logger = cfg.logger;
571
- if (process.env.NILEDB_LOCAL) {
572
- var _Logger7 = Logger(config, '[local]'),
573
- info = _Logger7.info;
574
- logger && info(logger, 'NILEDB_LOCAL', process.env.NILEDB_LOCAL);
575
- var apiUrl = new URL(process.env.NILEDB_LOCAL);
576
- return apiUrl.href;
577
- }
578
- return 'http://localhost:3000';
579
- };
580
- /**
581
- * @param cfg various overrides
582
- * @returns the url for REST to use
583
- */
584
- var getBasePath = function getBasePath(cfg) {
585
- var _config$api4;
586
- var config = cfg.config,
587
- logger = cfg.logger;
588
- var _Logger8 = Logger(config, '[basePath]'),
589
- info = _Logger8.info;
590
- var basePath = config == null || (_config$api4 = config.api) == null ? void 0 : _config$api4.basePath;
591
- var version = '';
592
- if (!/\/v\d\//.test(String(basePath))) {
593
- var _config$api5, _config$api$version, _config$api6;
594
- version = (config == null || (_config$api5 = config.api) == null ? void 0 : _config$api5.version) === 1 ? '' : "/v" + ((_config$api$version = config == null || (_config$api6 = config.api) == null ? void 0 : _config$api6.version) != null ? _config$api$version : 2);
595
- }
596
- if (basePath) {
597
- logger && info(logger, 'config', basePath);
598
- return "" + basePath + version;
599
- }
600
- if (process.env.NILEDB_API_URL) {
601
- logger && info(logger, 'NILEDB_API_URL', process.env.NILEDB_API_URL);
602
- var apiUrl = new URL(process.env.NILEDB_API_URL);
603
- return apiUrl.href;
604
- }
605
- throw new Error('NILEDB_API_URL is missing.');
606
- };
607
- var getControlPlane = function getControlPlane(cfg) {
608
- var config = cfg.config,
609
- logger = cfg.logger;
610
- var _Logger9 = Logger(config, '[basePath]'),
611
- info = _Logger9.info;
612
- if (process.env.NILEDB_CONFIGURE) {
613
- logger && info(logger, 'NILEDB_CONFIGURE', process.env.NILEDB_CONFIGURE);
614
- return process.env.NILEDB_CONFIGURE;
615
- }
616
- if (config != null && config.configureUrl) {
617
- logger && info(logger, 'NILEDB_CONFIGURE', config.configureUrl);
618
- return config.configureUrl;
619
- }
620
- logger && info(logger, 'default', 'https://global.thenile.dev');
621
- return 'https://global.thenile.dev';
622
- };
623
- function getDbHost(cfg) {
624
- var config = cfg.config,
625
- logger = cfg.logger;
626
- var _Logger10 = Logger(config, '[db.host]'),
627
- info = _Logger10.info;
628
- if (config != null && config.db && config.db.host) {
629
- logger && info(logger, 'config', config == null ? void 0 : config.db.host);
630
- return config.db.host;
631
- }
632
- if (process.env.NILEDB_POSTGRES_URL) {
633
- var pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
634
- logger && info(logger, 'NILEDB_POSTGRES_URL', pgUrl.host);
635
- return pgUrl.host;
636
- }
637
- if (process.env.NILEDB_HOST) {
638
- logger && info(logger, 'NILEDB_HOST', process.env.NILEDB_HOST);
639
- return process.env.NILEDB_HOST;
640
- }
641
- logger && info(logger, 'default', 'db.thenile.dev');
642
- return 'db.thenile.dev';
643
- }
644
- function getDbPort(cfg) {
645
- var _config$db;
646
- var config = cfg.config,
647
- logger = cfg.logger;
648
- var _Logger11 = Logger(config, '[db.port]'),
649
- info = _Logger11.info;
650
- if (config != null && (_config$db = config.db) != null && _config$db.port && config.db.port != null) {
651
- var _config$db2;
652
- logger && info(logger, 'config', config == null ? void 0 : config.db.port);
653
- return Number((_config$db2 = config.db) == null ? void 0 : _config$db2.port);
654
- }
655
- if (process.env.NILEDB_PORT) {
656
- logger && info(logger, 'config', process.env.NILEDB_PORT);
657
- return Number(process.env.NILEDB_PORT);
658
- }
659
- logger && info(logger, 'default', 5432);
660
- return 5432;
661
- }
662
- // don't let people accidentally log secrets to production
663
- var logProtector = function logProtector(logger) {
664
- return logger ;
665
- };
666
-
667
- var _excluded$2 = ["host", "port"],
668
- _excluded2 = ["host", "port"];
669
- var ApiConfig = /*#__PURE__*/function () {
670
- function ApiConfig(_ref) {
671
- var basePath = _ref.basePath,
672
- cookieKey = _ref.cookieKey,
673
- token = _ref.token,
674
- version = _ref.version,
675
- localPath = _ref.localPath;
676
- this.cookieKey = void 0;
677
- this.basePath = void 0;
678
- this.version = void 0;
679
- this.localPath = void 0;
680
- this._token = void 0;
681
- this.basePath = basePath;
682
- this.cookieKey = cookieKey;
683
- this.version = version;
684
- this._token = token;
685
- this.localPath = localPath != null ? localPath : 'http://localhost:3000';
686
- }
687
- return _createClass(ApiConfig, [{
688
- key: "token",
689
- get: function get() {
690
- return this._token;
691
- },
692
- set: function set(value) {
693
- this._token = value;
694
- }
695
- }]);
696
- }();
697
- var Config = /*#__PURE__*/function () {
698
- function Config(_config, logger) {
699
- var _this = this,
700
- _config$db2,
701
- _config$api$cookieKey2,
702
- _config$api3,
703
- _config$api$version2,
704
- _config$api4;
705
- this.user = void 0;
706
- this.password = void 0;
707
- this.databaseId = void 0;
708
- this.databaseName = void 0;
709
- this.routePrefix = void 0;
710
- this.routes = void 0;
711
- this.debug = void 0;
712
- this.db = void 0;
713
- this.api = void 0;
714
- this._tenantId = void 0;
715
- this._userId = void 0;
716
- this.configure = /*#__PURE__*/function () {
717
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config) {
718
- var _config$db, _envVarConfig$config, _config$api$cookieKey, _config$api, _config$api$version, _config$api2;
719
- var _Logger, info, error, envVarConfig, _ref3, host, port, dbConfig, configuredHost, configuredPort, basePath, cp, databaseName, url, res, database, possibleError, json, message, _database, apiHost, dbHost, name, id, duckApiHost, dburl;
720
- return _regeneratorRuntime().wrap(function _callee$(_context) {
721
- while (1) switch (_context.prev = _context.next) {
722
- case 0:
723
- _Logger = Logger(config, '[init]'), info = _Logger.info, error = _Logger.error;
724
- envVarConfig = {
725
- config: config
726
- };
727
- _ref3 = (_config$db = config.db) != null ? _config$db : {}, host = _ref3.host, port = _ref3.port, dbConfig = _objectWithoutPropertiesLoose(_ref3, _excluded$2);
728
- configuredHost = host != null ? host : getDbHost(envVarConfig);
729
- configuredPort = port != null ? port : getDbPort(envVarConfig);
730
- if (!(configuredHost && _this.databaseName && _this.databaseId)) {
731
- _context.next = 8;
732
- break;
733
- }
734
- info('Already configured, aborting fetch');
735
- return _context.abrupt("return", _this);
736
- case 8:
737
- basePath = getBasePath(envVarConfig);
738
- cp = getControlPlane(envVarConfig);
739
- databaseName = getDatabaseName({
740
- config: config,
741
- logger: 'getInfo'
742
- });
743
- url = new URL(cp + "/databases/configure");
744
- if (databaseName) {
745
- url.searchParams.set('databaseName', databaseName);
746
- }
747
- info('configuring from', url.href);
748
- _context.next = 16;
749
- return fetch(url, {
750
- headers: {
751
- Authorization: "Bearer " + getInfoBearer({
752
- config: config
753
- })
754
- }
755
- });
756
- case 16:
757
- res = _context.sent;
758
- possibleError = res.clone();
759
- _context.prev = 18;
760
- _context.next = 21;
761
- return res.json();
762
- case 21:
763
- json = _context.sent;
764
- if (res.status === 404) {
765
- info('is the configured databaseName correct?');
766
- }
767
- if (json.status && json.status !== 'READY') {
768
- database = {
769
- message: 'Database is not ready yet'
770
- };
771
- } else {
772
- database = json;
773
- }
774
- _context.next = 33;
775
- break;
776
- case 26:
777
- _context.prev = 26;
778
- _context.t0 = _context["catch"](18);
779
- _context.next = 30;
780
- return possibleError.text();
781
- case 30:
782
- message = _context.sent;
783
- error(message);
784
- database = {
785
- message: message
786
- };
787
- case 33:
788
- info('[fetched database]', database);
789
- if (!('message' in database)) {
790
- _context.next = 42;
791
- break;
792
- }
793
- if (!('statusCode' in database)) {
794
- _context.next = 41;
795
- break;
796
- }
797
- error(database);
798
- throw new Error('HTTP error has occurred');
799
- case 41:
800
- throw new Error('Unable to auto-configure. Please remove NILEDB_NAME, NILEDB_API_URL, NILEDB_POSTGRES_URL, and/or NILEDB_HOST from your environment variables.');
801
- case 42:
802
- if (typeof database === 'object') {
803
- _database = database, apiHost = _database.apiHost, dbHost = _database.dbHost, name = _database.name, id = _database.id;
804
- duckApiHost = getBasePath(envVarConfig) || apiHost; // this needs changed in the control plane response
805
- _this.databaseId = id;
806
- _this.databaseName = name;
807
- dburl = new URL(dbHost);
808
- configuredHost = dburl.host;
809
- basePath = duckApiHost;
810
- }
811
- case 43:
812
- (_envVarConfig$config = envVarConfig.config) == null || (_envVarConfig$config = _envVarConfig$config.api) == null || delete _envVarConfig$config.basePath;
813
- basePath = getBasePath(envVarConfig);
814
- _this.api = new ApiConfig({
815
- basePath: basePath,
816
- cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
817
- token: getToken({
818
- config: config
819
- }),
820
- version: (_config$api$version = config == null || (_config$api2 = config.api) == null ? void 0 : _config$api2.version) != null ? _config$api$version : 2,
821
- localPath: getLocal(envVarConfig)
822
- });
823
- _this.db = _extends({
824
- user: _this.user,
825
- password: _this.password,
826
- host: configuredHost,
827
- port: configuredPort,
828
- database: _this.databaseName
829
- }, dbConfig);
830
- info('[config set]', _this);
831
- return _context.abrupt("return", _this);
832
- case 49:
833
- case "end":
834
- return _context.stop();
835
- }
836
- }, _callee, null, [[18, 26]]);
837
- }));
838
- return function (_x) {
839
- return _ref2.apply(this, arguments);
840
- };
841
- }();
842
- var _envVarConfig = {
843
- config: _config,
844
- logger: logger
845
- };
846
- this.user = getUsername(_envVarConfig);
847
- this.password = getPassword(_envVarConfig);
848
- {
849
- if (!this.user) {
850
- throw new Error('User is required. Set NILEDB_USER as an environment variable or set `user` in the config options.');
851
- }
852
- if (!this.password) {
853
- throw new Error('Password is required. Set NILEDB_PASSWORD as an environment variable or set `password` in the config options.');
854
- }
855
- }
856
- this.databaseId = getDatabaseId(_envVarConfig);
857
- this.databaseName = getDatabaseName(_envVarConfig);
858
- this._tenantId = getTenantId(_envVarConfig);
859
- this.debug = Boolean(_config == null ? void 0 : _config.debug);
860
- this._userId = _config == null ? void 0 : _config.userId;
861
- var _basePath = getBasePath(_envVarConfig);
862
- var _ref4 = (_config$db2 = _config == null ? void 0 : _config.db) != null ? _config$db2 : {},
863
- _host = _ref4.host,
864
- _port = _ref4.port,
865
- _dbConfig = _objectWithoutPropertiesLoose(_ref4, _excluded2);
866
- var _configuredHost = _host != null ? _host : getDbHost(_envVarConfig);
867
- var _configuredPort = _port != null ? _port : getDbPort(_envVarConfig);
868
- this.api = new ApiConfig({
869
- basePath: _basePath,
870
- cookieKey: (_config$api$cookieKey2 = _config == null || (_config$api3 = _config.api) == null ? void 0 : _config$api3.cookieKey) != null ? _config$api$cookieKey2 : 'token',
871
- token: getToken({
872
- config: _config
873
- }),
874
- version: (_config$api$version2 = _config == null || (_config$api4 = _config.api) == null ? void 0 : _config$api4.version) != null ? _config$api$version2 : 2,
875
- localPath: getLocal(_envVarConfig)
876
- });
877
- this.db = _extends({
878
- user: this.user,
879
- password: this.password,
880
- host: _configuredHost,
881
- port: _configuredPort
882
- }, _dbConfig);
883
- if (this.databaseName) {
884
- this.db.database = this.databaseName;
885
- }
886
- }
887
- return _createClass(Config, [{
888
- key: "tenantId",
889
- get: function get() {
890
- return this._tenantId;
891
- },
892
- set: function set(value) {
893
- this._tenantId = value;
894
- }
895
- }, {
896
- key: "userId",
897
- get: function get() {
898
- return this._userId;
899
- },
900
- set: function set(value) {
901
- this._userId = value;
902
- }
903
- }]);
904
- }();
905
-
906
- var Events;
907
- (function (Events) {
908
- Events["User"] = "userId";
909
- Events["Tenant"] = "tenantId";
910
- Events["Token"] = "token";
911
- Events["EvictPool"] = "EvictPool";
912
- })(Events || (Events = {}));
913
- var Eventer = /*#__PURE__*/function () {
914
- function Eventer() {
915
- this.events = void 0;
916
- this.events = {};
917
- }
918
- var _proto = Eventer.prototype;
919
- _proto.publish = function publish(eventName, value) {
920
- // Get all the callback functions of the current event
921
- var callbackList = this.events[eventName];
922
- // execute each callback function
923
- if (callbackList) {
924
- for (var _iterator = _createForOfIteratorHelperLoose(callbackList), _step; !(_step = _iterator()).done;) {
925
- var callback = _step.value;
926
- callback(value);
927
- }
928
- }
929
- }
930
- // Subscribe to events
931
- ;
932
- _proto.subscribe = function subscribe(eventName, callback) {
933
- // initialize this event
934
- if (!this.events[eventName]) {
935
- this.events[eventName] = [];
936
- }
937
- // store the callback function of the subscriber
938
- this.events[eventName].push(callback);
939
- };
940
- _proto.unsubscribe = function unsubscribe(eventName, callback) {
941
- var toRemove = this.events[eventName].findIndex(function (cb) {
942
- return cb === callback;
943
- });
944
- if (toRemove !== -1) {
945
- this.events[eventName].splice(toRemove, 1);
946
- }
947
- };
948
- return Eventer;
949
- }(); // tenantId manager
950
- var eventer = /*#__PURE__*/new Eventer();
951
- var updateTenantId = function updateTenantId(tenantId) {
952
- eventer.publish(Events.Tenant, tenantId);
953
- };
954
- var watchTenantId = function watchTenantId(cb) {
955
- return eventer.subscribe(Events.Tenant, cb);
956
- };
957
- var updateUserId = function updateUserId(userId) {
958
- eventer.publish(Events.User, userId);
959
- };
960
- var watchUserId = function watchUserId(cb) {
961
- return eventer.subscribe(Events.User, cb);
962
- };
963
- var watchToken = function watchToken(cb) {
964
- return eventer.subscribe(Events.Token, cb);
965
- };
966
- var watchEvictPool = function watchEvictPool(cb) {
967
- return eventer.subscribe(Events.EvictPool, cb);
968
- };
969
- var closeEvictPool = function closeEvictPool(cb) {
970
- return eventer.unsubscribe(Events.EvictPool, cb);
971
- };
972
- var evictPool = function evictPool(val) {
973
- eventer.publish(Events.EvictPool, val);
974
- };
975
-
976
- function createProxyForPool(pool, config) {
977
- var _Logger = Logger(config, '[pool]'),
978
- info = _Logger.info,
979
- error = _Logger.error;
980
- return new Proxy(pool, {
981
- get: function get(target, property) {
982
- if (property === 'query') {
983
- // give connection string a pass for these problems
984
- if (!config.db.connectionString) {
985
- if (!config.user || !config.password) {
986
- error('Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev');
987
- } else if (!config.db.database) {
988
- error('Database name is missing from the config. Call `nile.init()` or set NILEDB_ID in your .env');
989
- }
990
- }
991
- var caller = target[property];
992
- return function query() {
993
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
994
- args[_key] = arguments[_key];
995
- }
996
- info.apply(void 0, args);
997
- // @ts-expect-error - not mine
998
- var called = caller.apply(this, args);
999
- return called;
1000
- };
1001
- }
1002
- return target[property];
1003
- }
1004
- });
1005
- }
1006
-
1007
- function isUUID(value) {
1008
- if (!value) {
1009
- return false;
1010
- }
1011
- var regex = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1012
- return regex.test(value);
1013
- }
1014
-
1015
- var _excluded$1 = ["afterCreate"];
1016
- var NileDatabase = /*#__PURE__*/function () {
1017
- function NileDatabase(config, id) {
1018
- var _this = this;
1019
- this.pool = void 0;
1020
- this.tenantId = void 0;
1021
- this.userId = void 0;
1022
- this.id = void 0;
1023
- this.config = void 0;
1024
- this.timer = void 0;
1025
- var _Logger = Logger(config, '[NileInstance]'),
1026
- warn = _Logger.warn,
1027
- info = _Logger.info;
1028
- this.id = id;
1029
- var poolConfig = _extends({
1030
- min: 0,
1031
- max: 10,
1032
- idleTimeoutMillis: 30000
1033
- }, config.db);
1034
- var afterCreate = poolConfig.afterCreate,
1035
- remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded$1);
1036
- config.db = poolConfig;
1037
- this.config = config;
1038
- info(this.config.db);
1039
- this.pool = createProxyForPool(new pg.Pool(remaining), this.config);
1040
- if (typeof afterCreate === 'function') {
1041
- warn('Providing an pool configuration will stop automatic tenant context setting.');
1042
- }
1043
- // start the timer for cleanup
1044
- this.startTimeout();
1045
- this.pool.on('connect', /*#__PURE__*/function () {
1046
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(client) {
1047
- var afterCreate;
1048
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1049
- while (1) switch (_context.prev = _context.next) {
1050
- case 0:
1051
- info('pool connected');
1052
- afterCreate = makeAfterCreate(config);
1053
- afterCreate(client, function (err) {
1054
- var _Logger2 = Logger(config, '[after create callback]'),
1055
- error = _Logger2.error;
1056
- if (err) {
1057
- error('after create failed', err);
1058
- evictPool(_this.id);
1059
- }
1060
- });
1061
- _this.startTimeout();
1062
- case 4:
1063
- case "end":
1064
- return _context.stop();
1065
- }
1066
- }, _callee);
1067
- }));
1068
- return function (_x) {
1069
- return _ref.apply(this, arguments);
1070
- };
1071
- }());
1072
- this.pool.on('error', /*#__PURE__*/function () {
1073
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) {
1074
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1075
- while (1) switch (_context2.prev = _context2.next) {
1076
- case 0:
1077
- info('pool failed', e);
1078
- if (_this.timer) {
1079
- clearTimeout(_this.timer);
1080
- }
1081
- evictPool(_this.id);
1082
- case 3:
1083
- case "end":
1084
- return _context2.stop();
1085
- }
1086
- }, _callee2);
1087
- }));
1088
- return function (_x2) {
1089
- return _ref2.apply(this, arguments);
1090
- };
1091
- }());
1092
- }
1093
- var _proto = NileDatabase.prototype;
1094
- _proto.startTimeout = function startTimeout() {
1095
- var _this2 = this;
1096
- var _Logger3 = Logger(this.config, '[NileInstance]'),
1097
- info = _Logger3.info;
1098
- if (this.timer) {
1099
- clearTimeout(this.timer);
1100
- }
1101
- this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1102
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1103
- while (1) switch (_context3.prev = _context3.next) {
1104
- case 0:
1105
- info('Pool reached idleTimeoutMillis.', _this2.id, 'evicted after', _this2.config.db.idleTimeoutMillis, 'ms');
1106
- _context3.next = 3;
1107
- return _this2.pool.end(function () {
1108
- info('Pool end called');
1109
- // something odd going on here. Without the callback, pool.end() is flakey
1110
- });
1111
- case 3:
1112
- evictPool(_this2.id);
1113
- case 4:
1114
- case "end":
1115
- return _context3.stop();
1116
- }
1117
- }, _callee3);
1118
- })), this.config.db.idleTimeoutMillis);
1119
- };
1120
- return NileDatabase;
1121
- }();
1122
- function makeAfterCreate(config) {
1123
- var _Logger4 = Logger(config, '[afterCreate]'),
1124
- warn = _Logger4.warn,
1125
- info = _Logger4.info;
1126
- return function (conn, done) {
1127
- conn.on('error', function errorHandler(error) {
1128
- warn('Connection was terminated by server', error);
1129
- done(error, conn);
1130
- });
1131
- if (isUUID(config.tenantId)) {
1132
- var query = ["SET nile.tenant_id = '" + config.tenantId + "'"];
1133
- if (isUUID(config.userId)) {
1134
- if (!config.tenantId) {
1135
- warn('A user id cannot be set in context without a tenant id');
1136
- }
1137
- query.push("SET nile.user_id = '" + config.userId + "'");
1138
- }
1139
- // in this example we use pg driver's connection API
1140
- conn.query(query.join(';'), function (err) {
1141
- if (query.length === 1) {
1142
- info('[tenant id]', config.tenantId);
1143
- }
1144
- if (query.length === 2) {
1145
- info('[user id]', config.userId);
1146
- }
1147
- done(err, conn);
1148
- });
1149
- }
1150
- done(null, conn);
1151
- };
1152
- }
1153
-
1154
- var DBManager = /*#__PURE__*/function () {
1155
- function DBManager(_config) {
1156
- var _this = this;
1157
- this.connections = void 0;
1158
- this.cleared = void 0;
1159
- this.poolWatcher = function (config) {
1160
- return function (id) {
1161
- var _Logger = Logger(config, '[DBManager]'),
1162
- info = _Logger.info;
1163
- if (id && _this.connections.has(id)) {
1164
- info('Removing', id, 'from db connection pool.');
1165
- _this.connections["delete"](id);
1166
- }
1167
- };
1168
- };
1169
- this.getConnection = function (config) {
1170
- var _Logger2 = Logger(config, '[DBManager]'),
1171
- info = _Logger2.info;
1172
- var id = _this.makeId(config.tenantId, config.userId);
1173
- var existing = _this.connections.get(id);
1174
- info('# of instances:', _this.connections.size);
1175
- if (existing) {
1176
- info('returning existing', id);
1177
- existing.startTimeout();
1178
- return existing.pool;
1179
- }
1180
- var newOne = new NileDatabase(new Config(config), id);
1181
- _this.connections.set(id, newOne);
1182
- info('created new', id);
1183
- info('# of instances:', _this.connections.size);
1184
- // resume listening to the evict pool if a connection is requested.
1185
- if (_this.cleared) {
1186
- _this.cleared = false;
1187
- watchEvictPool(_this.poolWatcher(config));
1188
- }
1189
- return newOne.pool;
1190
- };
1191
- this.clear = function (config) {
1192
- var _Logger3 = Logger(config, '[DBManager]'),
1193
- info = _Logger3.info;
1194
- info('Clearing all connections', _this.connections.size);
1195
- closeEvictPool(_this.poolWatcher(config));
1196
- _this.cleared = true;
1197
- _this.connections.clear();
1198
- };
1199
- var _Logger4 = Logger(_config, '[DBManager]'),
1200
- _info = _Logger4.info;
1201
- this.cleared = false;
1202
- this.connections = new Map();
1203
- // add the base one, so you can at least query
1204
- var _id = this.makeId();
1205
- _info('constructor', _id);
1206
- this.connections.set(_id, new NileDatabase(new Config(_config), _id));
1207
- watchEvictPool(this.poolWatcher(_config));
1208
- }
1209
- var _proto = DBManager.prototype;
1210
- _proto.makeId = function makeId(tenantId, userId) {
1211
- if (isUUID(tenantId) && isUUID(userId)) {
1212
- return tenantId + ":" + userId;
1213
- }
1214
- if (isUUID(tenantId)) {
1215
- return "" + tenantId;
1216
- }
1217
- return 'base';
1218
- };
1219
- return DBManager;
1220
- }();
1221
-
1222
- var getServerId = function getServerId(config) {
1223
- var cfg = new Config(config);
1224
- return makeServerId(cfg);
1225
- };
1226
- var makeServerId = function makeServerId(config) {
1227
- return Buffer.from(JSON.stringify(config), 'utf8').toString('base64');
1228
- };
1229
-
1230
- var NILEDB_API_URL = process.env.NILEDB_API_URL;
1231
- function makeRestUrl(path, qp) {
1232
- if (!NILEDB_API_URL) {
1233
- throw new Error('An API url is required. Set it via NILEDB_API_URL.');
1234
- }
1235
- var params = new URLSearchParams(qp);
1236
- return "" + [NILEDB_API_URL, path.substring(1, path.length)].join('/') + (qp ? "?" + params.toString() : '');
1237
- }
1238
-
1239
- var apiRoutes = {
1240
- ME: /*#__PURE__*/makeRestUrl('/me'),
1241
- USERS: function USERS(tenantId) {
1242
- return makeRestUrl('/users', tenantId ? {
1243
- tenantId: tenantId
1244
- } : undefined);
1245
- },
1246
- USER: function USER(userId) {
1247
- return makeRestUrl("/users/" + userId);
1248
- },
1249
- TENANTS: /*#__PURE__*/makeRestUrl('/tenants'),
1250
- TENANT: function TENANT(tenantId) {
1251
- return makeRestUrl("/tenants/" + tenantId);
1252
- },
1253
- SIGNUP: /*#__PURE__*/makeRestUrl('/signup'),
1254
- TENANT_USERS: function TENANT_USERS(tenantId) {
1255
- return makeRestUrl("/tenants/" + tenantId + "/users");
1256
- },
1257
- TENANT_USER: function TENANT_USER(tenantId, userId) {
1258
- return makeRestUrl("/tenants/" + tenantId + "/users/" + userId);
1259
- },
1260
- USER_TENANTS: function USER_TENANTS(userId) {
1261
- return makeRestUrl("/users/" + userId + "/tenants");
1262
- }
1263
- };
1264
-
1265
- function urlMatches(requestUrl, route) {
1266
- var url = new URL(requestUrl);
1267
- return url.pathname.startsWith(route);
1268
- }
1269
-
1270
- var _excluded = ["request"];
1271
- var _console$1 = console,
1272
- log$1 = _console$1.log;
1273
- function request(_x, _x2, _x3) {
1274
- return _request.apply(this, arguments);
1275
- }
1276
- function _request() {
1277
- _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, _init, config) {
1278
- var _params$method;
1279
- var _Logger, info, error, request, init, requestUrl, updatedHeaders, params, _init$body, res, loggingRes;
1280
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1281
- while (1) switch (_context.prev = _context.next) {
1282
- case 0:
1283
- _Logger = Logger(_extends({}, config, {
1284
- debug: config == null ? void 0 : config.debug
1285
- }), '[REQUEST]', "[" + url + "]"), info = _Logger.info, error = _Logger.error;
1286
- request = _init.request, init = _objectWithoutPropertiesLoose(_init, _excluded);
1287
- requestUrl = new URL(request.url);
1288
- updatedHeaders = new Headers(request.headers);
1289
- updatedHeaders.set('host', requestUrl.host);
1290
- updatedHeaders.set('niledb-origin', requestUrl.origin);
1291
- updatedHeaders.set('niledb-creds', Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD).toString('base64'));
1292
- params = _extends({}, init, {
1293
- headers: updatedHeaders
1294
- });
1295
- if (params.method === 'POST' || params.method === 'PUT') {
1296
- params.body = (_init$body = init.body) != null ? _init$body : request.body;
1297
- // @ts-expect-error - its there
1298
- params.duplex = 'half';
1299
- }
1300
- log$1("[" + ((_params$method = params.method) != null ? _params$method : 'GET') + "]", url);
1301
- _context.next = 12;
1302
- return fetch(url, _extends({}, params))["catch"](function (e) {
1303
- error('An error has occurred in the fetch', e);
1304
- return new Response('An unexpected (most likely configuration) problem has occurred', {
1305
- status: 500
1306
- });
1307
- });
1308
- case 12:
1309
- res = _context.sent;
1310
- loggingRes = typeof (res == null ? void 0 : res.clone) === 'function' ? res == null ? void 0 : res.clone() : null;
1311
- _context.t0 = info;
1312
- _context.t1 = res == null ? void 0 : res.status;
1313
- _context.t2 = res == null ? void 0 : res.statusText;
1314
- _context.next = 19;
1315
- return loggingRes == null ? void 0 : loggingRes.text();
1316
- case 19:
1317
- _context.t3 = _context.sent;
1318
- (0, _context.t0)('[Response]', _context.t1, _context.t2, _context.t3);
1319
- return _context.abrupt("return", res);
1320
- case 22:
1321
- case "end":
1322
- return _context.stop();
1323
- }
1324
- }, _callee);
1325
- }));
1326
- return _request.apply(this, arguments);
1327
- }
1328
-
1329
- var key$6 = 'ME';
1330
- var url = apiRoutes[key$6];
1331
- /**
1332
- * @swagger
1333
- * /api/me:
1334
- * get:
1335
- * summary: Identify the principal
1336
- * description: Returns information about the principal associated with the session
1337
- * provided
1338
- * operationId: me
1339
- * responses:
1340
- * "200":
1341
- * description: Identified user
1342
- * content:
1343
- * application/json:
1344
- * schema:
1345
- * $ref: '#/components/schemas/User'
1346
- * "400":
1347
- * description: API/Database failures
1348
- * content:
1349
- * text/plain:
1350
- * schema:
1351
- * type: string
1352
- * "404":
1353
- * description: Not found
1354
- * content: {}
1355
- * "401":
1356
- * description: Unauthorized
1357
- * content: {}
1358
- */
1359
- function GET$3(_x, _x2) {
1360
- return _GET$3.apply(this, arguments);
1361
- }
1362
- function _GET$3() {
1363
- _GET$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
1364
- var res;
1365
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1366
- while (1) switch (_context.prev = _context.next) {
1367
- case 0:
1368
- log('[GET]', url);
1369
- _context.next = 3;
1370
- return request(url, init);
1371
- case 3:
1372
- res = _context.sent;
1373
- return _context.abrupt("return", res);
1374
- case 5:
1375
- case "end":
1376
- return _context.stop();
1377
- }
1378
- }, _callee);
1379
- }));
1380
- return _GET$3.apply(this, arguments);
1381
- }
1382
- function route$a(_x3, _x4) {
1383
- return _route$a.apply(this, arguments);
1384
- }
1385
- function _route$a() {
1386
- _route$a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request, config) {
1387
- var _Logger, info;
1388
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1389
- while (1) switch (_context2.prev = _context2.next) {
1390
- case 0:
1391
- _Logger = Logger(_extends({}, config, {
1392
- debug: config.debug
1393
- }), '[ROUTES]', "[" + key$6 + "]"), info = _Logger.info;
1394
- _context2.t0 = request.method;
1395
- _context2.next = _context2.t0 === 'GET' ? 4 : 7;
1396
- break;
1397
- case 4:
1398
- _context2.next = 6;
1399
- return GET$3({
1400
- request: request
1401
- }, info);
1402
- case 6:
1403
- return _context2.abrupt("return", _context2.sent);
1404
- case 7:
1405
- return _context2.abrupt("return", new Response('method not allowed', {
1406
- status: 405
1407
- }));
1408
- case 8:
1409
- case "end":
1410
- return _context2.stop();
1411
- }
1412
- }, _callee2);
1413
- }));
1414
- return _route$a.apply(this, arguments);
1415
- }
1416
- function matches$a(configRoutes, request) {
1417
- return urlMatches(request.url, configRoutes[key$6]);
1418
- }
1419
-
1420
- function auth(_x, _x2) {
1421
- return _auth.apply(this, arguments);
1422
- }
1423
- function _auth() {
1424
- _auth = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
1425
- var _Logger, info, sessionUrl, res;
1426
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1427
- while (1) switch (_context.prev = _context.next) {
1428
- case 0:
1429
- _Logger = Logger(_extends({}, config, {
1430
- debug: config.debug
1431
- }), '[nileauth]'), info = _Logger.info;
1432
- info('checking auth');
1433
- sessionUrl = config.api.basePath + "/auth/session";
1434
- info('using session', sessionUrl);
1435
- // handle the pass through with posts
1436
- req.headers["delete"]('content-length');
1437
- _context.next = 7;
1438
- return request(sessionUrl, {
1439
- request: req
1440
- });
1441
- case 7:
1442
- res = _context.sent;
1443
- if (res) {
1444
- _context.next = 11;
1445
- break;
1446
- }
1447
- info('no session found');
1448
- return _context.abrupt("return", undefined);
1449
- case 11:
1450
- info('session active');
1451
- _context.next = 14;
1452
- return new Response(res.body).json();
1453
- case 14:
1454
- return _context.abrupt("return", _context.sent);
1455
- case 15:
1456
- case "end":
1457
- return _context.stop();
1458
- }
1459
- }, _callee);
1460
- }));
1461
- return _auth.apply(this, arguments);
1462
- }
1463
-
1464
- var ResponseError = function ResponseError(body, init) {
1465
- this.response = void 0;
1466
- this.response = new Response(body, init);
1467
- };
1468
-
1469
- var X_NILE_TENANT = 'niledb-tenant-id';
1470
- var X_NILE_USER_ID = 'niledb-user-id';
1471
- function getTokenFromCookie(headers, cookieKey) {
1472
- var _headers$get;
1473
- var cookie = (_headers$get = headers.get('cookie')) == null ? void 0 : _headers$get.split('; ');
1474
- var _cookies = {};
1475
- if (cookie) {
1476
- for (var _iterator = _createForOfIteratorHelperLoose(cookie), _step; !(_step = _iterator()).done;) {
1477
- var parts = _step.value;
1478
- var cookieParts = parts.split('=');
1479
- var _cookie = cookieParts.slice(1).join('=');
1480
- var name = cookieParts[0];
1481
- _cookies[name] = _cookie;
1482
- }
1483
- }
1484
- if (cookie) {
1485
- for (var _iterator2 = _createForOfIteratorHelperLoose(cookie), _step2; !(_step2 = _iterator2()).done;) {
1486
- var _parts = _step2.value;
1487
- var _cookieParts = _parts.split('=');
1488
- var _cookie2 = _cookieParts.slice(1).join('=');
1489
- var _name = _cookieParts[0];
1490
- _cookies[_name] = _cookie2;
1491
- }
1492
- }
1493
- if (cookieKey) {
1494
- return _cookies[cookieKey];
1495
- }
1496
- return null;
1497
- }
1498
- function getTenantFromHttp(headers, config) {
1499
- var _ref;
1500
- var cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
1501
- return (_ref = cookieTenant != null ? cookieTenant : headers == null ? void 0 : headers.get(X_NILE_TENANT)) != null ? _ref : config == null ? void 0 : config.tenantId;
1502
- }
1503
- function getUserFromHttp(headers, config) {
1504
- var _headers$get2;
1505
- var token = getTokenFromCookie(headers, config.api.cookieKey);
1506
- if (token) {
1507
- var jwt = jose.decodeJwt(token);
1508
- return jwt.sub;
1509
- }
1510
- return (_headers$get2 = headers == null ? void 0 : headers.get(X_NILE_USER_ID)) != null ? _headers$get2 : config.userId;
1511
- }
1512
- function _fetch(_x, _x2, _x3) {
1513
- return _fetch2.apply(this, arguments);
1514
- }
1515
- function _fetch2() {
1516
- _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
1517
- var _config$api, _config$api2, _response$status;
1518
- var _Logger, info, error, url, cookieKey, headers, basicHeaders, creds, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
1519
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1520
- while (1) switch (_context.prev = _context.next) {
1521
- case 0:
1522
- _Logger = Logger(config, '[server]'), info = _Logger.info, error = _Logger.error;
1523
- url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
1524
- cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
1525
- headers = new Headers(opts == null ? void 0 : opts.headers);
1526
- basicHeaders = new Headers(opts == null ? void 0 : opts.headers);
1527
- basicHeaders.set('content-type', 'application/json; charset=utf-8');
1528
- creds = Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD, 'utf8').toString('base64');
1529
- basicHeaders.set('niledb-creds', creds);
1530
- authHeader = headers.get('Authorization');
1531
- if (!authHeader) {
1532
- token = getTokenFromCookie(headers, cookieKey);
1533
- if (token) {
1534
- basicHeaders.set('Authorization', "Bearer " + token);
1535
- } else if (getToken({
1536
- config: config
1537
- })) {
1538
- basicHeaders.set('Authorization', "Bearer " + getToken({
1539
- config: config
1540
- }));
1541
- }
1542
- }
1543
- tenantId = getTenantFromHttp(headers, config);
1544
- updateTenantId(tenantId);
1545
- userId = getUserFromHttp(headers, config);
1546
- updateUserId(userId);
1547
- if (!(url.includes('{tenantId}') && !tenantId)) {
1548
- _context.next = 16;
1549
- break;
1550
- }
1551
- return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
1552
- status: 400
1553
- }));
1554
- case 16:
1555
- useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
1556
- info('[fetch]', useableUrl);
1557
- _context.next = 20;
1558
- return fetch(useableUrl, _extends({}, opts, {
1559
- headers: basicHeaders
1560
- }))["catch"](function (e) {
1561
- error('[fetch]', '[response]', e);
1562
- });
1563
- case 20:
1564
- response = _context.sent;
1565
- if (!(response && response.status >= 200 && response.status < 300)) {
1566
- _context.next = 39;
1567
- break;
1568
- }
1569
- if (!(typeof response.clone === 'function')) {
1570
- _context.next = 38;
1571
- break;
1572
- }
1573
- _context.prev = 23;
1574
- _context.t0 = info;
1575
- _context.next = 27;
1576
- return response.clone().json();
1577
- case 27:
1578
- _context.t1 = _context.sent;
1579
- (0, _context.t0)('[fetch]', '[response]', _context.t1);
1580
- _context.next = 38;
1581
- break;
1582
- case 31:
1583
- _context.prev = 31;
1584
- _context.t2 = _context["catch"](23);
1585
- _context.t3 = info;
1586
- _context.next = 36;
1587
- return response.clone().text();
1588
- case 36:
1589
- _context.t4 = _context.sent;
1590
- (0, _context.t3)('[fetch]', '[response]', _context.t4);
1591
- case 38:
1592
- return _context.abrupt("return", response);
1593
- case 39:
1594
- if (!((response == null ? void 0 : response.status) === 401)) {
1595
- _context.next = 41;
1596
- break;
1597
- }
1598
- return _context.abrupt("return", new ResponseError('Unauthorized', {
1599
- status: 401
1600
- }));
1601
- case 41:
1602
- if (!((response == null ? void 0 : response.status) === 405)) {
1603
- _context.next = 43;
1604
- break;
1605
- }
1606
- return _context.abrupt("return", new ResponseError('Method not allowed', {
1607
- status: 405
1608
- }));
1609
- case 43:
1610
- errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
1611
- msg = '';
1612
- _context.prev = 45;
1613
- _context.next = 48;
1614
- return response == null ? void 0 : response.json();
1615
- case 48:
1616
- res = _context.sent;
1617
- _context.next = 59;
1618
- break;
1619
- case 51:
1620
- _context.prev = 51;
1621
- _context.t5 = _context["catch"](45);
1622
- if (!errorHandler) {
1623
- _context.next = 58;
1624
- break;
1625
- }
1626
- _context.next = 56;
1627
- return errorHandler.text();
1628
- case 56:
1629
- msg = _context.sent;
1630
- if (msg) {
1631
- error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
1632
- }
1633
- case 58:
1634
- if (!msg) {
1635
- error('[fetch]', '[response]', _context.t5);
1636
- }
1637
- case 59:
1638
- if (!msg) {
1639
- _context.next = 61;
1640
- break;
1641
- }
1642
- return _context.abrupt("return", new ResponseError(msg, {
1643
- status: errorHandler == null ? void 0 : errorHandler.status
1644
- }));
1645
- case 61:
1646
- if (!(res && 'message' in res)) {
1647
- _context.next = 65;
1648
- break;
1649
- }
1650
- _res = res, message = _res.message;
1651
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", message);
1652
- return _context.abrupt("return", new ResponseError(message, {
1653
- status: 400
1654
- }));
1655
- case 65:
1656
- if (!(res && 'errors' in res)) {
1657
- _context.next = 69;
1658
- break;
1659
- }
1660
- _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
1661
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", _message);
1662
- return _context.abrupt("return", new ResponseError(_message, {
1663
- status: 400
1664
- }));
1665
- case 69:
1666
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
1667
- return _context.abrupt("return", new ResponseError(null, {
1668
- status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
1669
- }));
1670
- case 71:
1671
- case "end":
1672
- return _context.stop();
1673
- }
1674
- }, _callee, null, [[23, 31], [45, 51]]);
1675
- }));
1676
- return _fetch2.apply(this, arguments);
1677
- }
1678
-
1679
- /**
1680
- * @swagger
1681
- * /api/users:
1682
- * post:
1683
- * tags:
1684
- * - users
1685
- * summary: Creates a user
1686
- * description: Creates a user in the database
1687
- * operationId: createUser
1688
- * parameters:
1689
- * - name: tenantId
1690
- * description: A tenant id to add the user to when they are created
1691
- * in: query
1692
- * schema:
1693
- * type: string
1694
- * - name: newTenantName
1695
- * description: A tenant name to create, then the user to when they are created
1696
- * in: query
1697
- * schema:
1698
- * type: string
1699
- * requestBody:
1700
- * description: |-
1701
- * The email and password combination the user will use to authenticate.
1702
- * The `name` is optional; if provided it will be recorded in the `users` table.
1703
- * The `newTenant` is optional; if provided, it is used as the name of a new tenant record associated with the newly created user.
1704
- * content:
1705
- * application/json:
1706
- * schema:
1707
- * $ref: '#/components/schemas/CreateBasicUserRequest'
1708
- * examples:
1709
- * Create User Request:
1710
- * summary: Creates a user with basic credentials
1711
- * description: Create User Request
1712
- * value:
1713
- * email: a.user@somedomain.com
1714
- * password: somepassword
1715
- * name: A. User
1716
- * Create User Request with Tenant:
1717
- * summary: Creates a user and a new tenant for that user
1718
- * description: Create User Request with Tenant
1719
- * value:
1720
- * email: a.user@somedomain.com
1721
- * password: somepassword
1722
- * name: A. User
1723
- * newTenant: My Sandbox
1724
- * responses:
1725
- * "201":
1726
- * description: User created
1727
- * content:
1728
- * application/json:
1729
- * schema:
1730
- * $ref: "#/components/schemas/User"
1731
- * "400":
1732
- * description: API/Database failures
1733
- * content:
1734
- * text/plain:
1735
- * schema:
1736
- * type: string
1737
- * "401":
1738
- * description: Unauthorized
1739
- * content: {}
1740
- */
1741
- function POST$2(_x, _x2, _x3) {
1742
- return _POST$2.apply(this, arguments);
1743
- }
1744
- function _POST$2() {
1745
- _POST$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
1746
- var yurl, tenantId, tenant, url;
1747
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1748
- while (1) switch (_context.prev = _context.next) {
1749
- case 0:
1750
- if (session) {
1751
- _context.next = 2;
1752
- break;
1753
- }
1754
- return _context.abrupt("return", new Response(null, {
1755
- status: 401
1756
- }));
1757
- case 2:
1758
- init.body = init.request.body;
1759
- init.method = 'POST';
1760
- yurl = new URL(init.request.url);
1761
- tenantId = yurl.searchParams.get('tenantId');
1762
- tenant = tenantId != null ? tenantId : getTenantFromHttp(init.request.headers);
1763
- url = apiRoutes.USERS(tenant ? tenant : undefined);
1764
- log && log('[POST]', url);
1765
- _context.next = 11;
1766
- return request(url, init);
1767
- case 11:
1768
- return _context.abrupt("return", _context.sent);
1769
- case 12:
1770
- case "end":
1771
- return _context.stop();
1772
- }
1773
- }, _callee);
1774
- }));
1775
- return _POST$2.apply(this, arguments);
1776
- }
1777
-
1778
- /**
1779
- * @swagger
1780
- * /api/users:
1781
- * get:
1782
- * tags:
1783
- * - users
1784
- * summary: lists users in the tenant
1785
- * description: Returns information about the users within the tenant
1786
- * provided. You can also pass the a `niledb-tenant-id` in the header or in a cookie.
1787
- * operationId: listUsers
1788
- * parameters:
1789
- * - name: tenantId
1790
- * in: query
1791
- * schema:
1792
- * type: string
1793
- * responses:
1794
- * "200":
1795
- * description: A list of users
1796
- * content:
1797
- * application/json:
1798
- * schema:
1799
- * type: array
1800
- * items:
1801
- * $ref: '#/components/schemas/TenantUser'
1802
- * "404":
1803
- * description: Not found
1804
- * content: {}
1805
- * "401":
1806
- * description: Unauthorized
1807
- * content: {}
1808
- */
1809
- function GET$2(_x, _x2) {
1810
- return _GET$2.apply(this, arguments);
1811
- }
1812
- function _GET$2() {
1813
- _GET$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
1814
- var yurl, tenantId, tenant, url;
1815
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1816
- while (1) switch (_context.prev = _context.next) {
1817
- case 0:
1818
- yurl = new URL(init.request.url);
1819
- tenantId = yurl.searchParams.get('tenantId');
1820
- tenant = tenantId != null ? tenantId : getTenantFromHttp(init.request.headers);
1821
- if (tenant) {
1822
- _context.next = 6;
1823
- break;
1824
- }
1825
- log('[GET]', '[ERROR]', 'No tenant id provided.');
1826
- return _context.abrupt("return", new Response(null, {
1827
- status: 404
1828
- }));
1829
- case 6:
1830
- url = apiRoutes.TENANT_USERS(tenant);
1831
- log('[GET]', url);
1832
- init.method = 'GET';
1833
- _context.next = 11;
1834
- return request(url, init);
1835
- case 11:
1836
- return _context.abrupt("return", _context.sent);
1837
- case 12:
1838
- case "end":
1839
- return _context.stop();
1840
- }
1841
- }, _callee);
1842
- }));
1843
- return _GET$2.apply(this, arguments);
1844
- }
1845
-
1846
- /**
1847
- * @swagger
1848
- * /api/users/{userid}:
1849
- * put:
1850
- * tags:
1851
- * - users
1852
- * summary: update a user
1853
- * description: updates a user within the tenant
1854
- * operationId: updateUser
1855
- * parameters:
1856
- * - name: userid
1857
- * in: path
1858
- * required: true
1859
- * schema:
1860
- * type: string
1861
- * requestBody:
1862
- * description: |-
1863
- * Update a user
1864
- * content:
1865
- * application/json:
1866
- * schema:
1867
- * $ref: '#/components/schemas/UpdateUserRequest'
1868
- * responses:
1869
- * "200":
1870
- * description: An updated user
1871
- * content:
1872
- * application/json:
1873
- * schema:
1874
- * $ref: '#/components/schemas/User'
1875
- * "404":
1876
- * description: Not found
1877
- * content: {}
1878
- * "401":
1879
- * description: Unauthorized
1880
- * content: {}
1881
- */
1882
- function PUT$1(_x, _x2, _x3) {
1883
- return _PUT$1.apply(this, arguments);
1884
- }
1885
- function _PUT$1() {
1886
- _PUT$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
1887
- var _URL$pathname$split$r, userId, url;
1888
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1889
- while (1) switch (_context.prev = _context.next) {
1890
- case 0:
1891
- if (session) {
1892
- _context.next = 2;
1893
- break;
1894
- }
1895
- return _context.abrupt("return", new Response(null, {
1896
- status: 401
1897
- }));
1898
- case 2:
1899
- init.body = init.request.body;
1900
- init.method = 'PUT';
1901
- // update the user
1902
- _URL$pathname$split$r = new URL(init.request.url).pathname.split('/').reverse(), userId = _URL$pathname$split$r[0];
1903
- url = apiRoutes.USER(userId);
1904
- log('[PUT]', url);
1905
- _context.next = 9;
1906
- return request(url, init);
1907
- case 9:
1908
- return _context.abrupt("return", _context.sent);
1909
- case 10:
1910
- case "end":
1911
- return _context.stop();
1912
- }
1913
- }, _callee);
1914
- }));
1915
- return _PUT$1.apply(this, arguments);
1916
- }
1917
-
1918
- var key$5 = 'USERS';
1919
- function route$9(_x, _x2) {
1920
- return _route$9.apply(this, arguments);
1921
- }
1922
- function _route$9() {
1923
- _route$9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
1924
- var _Logger, info, session;
1925
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1926
- while (1) switch (_context.prev = _context.next) {
1927
- case 0:
1928
- _Logger = Logger(_extends({}, config, {
1929
- debug: config.debug
1930
- }), '[ROUTES]', "[" + key$5 + "]"), info = _Logger.info;
1931
- _context.next = 3;
1932
- return auth(request, config);
1933
- case 3:
1934
- session = _context.sent;
1935
- _context.t0 = request.method;
1936
- _context.next = _context.t0 === 'GET' ? 7 : _context.t0 === 'POST' ? 10 : _context.t0 === 'PUT' ? 13 : 16;
1937
- break;
1938
- case 7:
1939
- _context.next = 9;
1940
- return GET$2({
1941
- request: request
1942
- }, info);
1943
- case 9:
1944
- return _context.abrupt("return", _context.sent);
1945
- case 10:
1946
- _context.next = 12;
1947
- return POST$2(session, {
1948
- request: request
1949
- }, info);
1950
- case 12:
1951
- return _context.abrupt("return", _context.sent);
1952
- case 13:
1953
- _context.next = 15;
1954
- return PUT$1(session, {
1955
- request: request
1956
- }, info);
1957
- case 15:
1958
- return _context.abrupt("return", _context.sent);
1959
- case 16:
1960
- return _context.abrupt("return", new Response('method not allowed', {
1961
- status: 405
1962
- }));
1963
- case 17:
1964
- case "end":
1965
- return _context.stop();
1966
- }
1967
- }, _callee);
1968
- }));
1969
- return _route$9.apply(this, arguments);
1970
- }
1971
- function matches$9(configRoutes, request) {
1972
- return urlMatches(request.url, configRoutes[key$5]);
1973
- }
1974
-
1975
- /**
1976
- * @swagger
1977
- * /api/tenants/{tenantId}/users:
1978
- * get:
1979
- * tags:
1980
- * - users
1981
- * summary: List tenant users
1982
- * description: Lists users that are associated with the specified tenant.
1983
- * operationId: listTenantUsers
1984
- * parameters:
1985
- * - name: tenantId
1986
- * in: path
1987
- * required: true
1988
- * schema:
1989
- * type: string
1990
- * responses:
1991
- * "200":
1992
- * description: Users found
1993
- * content:
1994
- * application/json:
1995
- * schema:
1996
- * type: array
1997
- * items:
1998
- * $ref: '#/components/schemas/User'
1999
- * "401":
2000
- * description: Unauthorized
2001
- * content:
2002
- * application/json:
2003
- * schema:
2004
- * $ref: '#/components/schemas/APIError'
2005
- */
2006
- function GET$1(_x, _x2, _x3) {
2007
- return _GET$1.apply(this, arguments);
2008
- }
2009
- function _GET$1() {
2010
- _GET$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2011
- var yurl, _yurl$pathname$split$, tenantId, url;
2012
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2013
- while (1) switch (_context.prev = _context.next) {
2014
- case 0:
2015
- yurl = new URL(init.request.url);
2016
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1];
2017
- if (tenantId) {
2018
- _context.next = 4;
2019
- break;
2020
- }
2021
- return _context.abrupt("return", new Response(null, {
2022
- status: 404
2023
- }));
2024
- case 4:
2025
- url = "" + apiRoutes.TENANT_USERS(tenantId);
2026
- log('[GET]', '[TENANT_USERS]', url);
2027
- _context.next = 8;
2028
- return request(url, init);
2029
- case 8:
2030
- return _context.abrupt("return", _context.sent);
2031
- case 9:
2032
- case "end":
2033
- return _context.stop();
2034
- }
2035
- }, _callee);
2036
- }));
2037
- return _GET$1.apply(this, arguments);
2038
- }
2039
-
2040
- /**
2041
- * @swagger
2042
- * /api/tenants/{tenantId}/users:
2043
- * post:
2044
- * tags:
2045
- * - users
2046
- * summary: Create a user in a tenant
2047
- * description: Creates a new user and associates that user with the specified
2048
- * tenant.
2049
- * operationId: createTenantUser
2050
- * parameters:
2051
- * - name: tenantId
2052
- * in: path
2053
- * required: true
2054
- * schema:
2055
- * type: string
2056
- * requestBody:
2057
- * description: |
2058
- * The email and password combination the user will use to authenticate.
2059
- * The `name` is optional; if provided it will be recorded in the `users` table.
2060
- * content:
2061
- * application/json:
2062
- * schema:
2063
- * $ref: '#/components/schemas/CreateBasicUserRequest'
2064
- * examples:
2065
- * Create User Request:
2066
- * summary: Creates a user with basic credentials
2067
- * description: Create User Request
2068
- * value:
2069
- * email: a.user@somedomain.com
2070
- * password: somepassword
2071
- * name: A. User
2072
- * responses:
2073
- * "201":
2074
- * description: User created
2075
- * content:
2076
- * application/json:
2077
- * schema:
2078
- * $ref: '#/components/schemas/User'
2079
- */
2080
- function POST$1(_x, _x2, _x3) {
2081
- return _POST$1.apply(this, arguments);
2082
- }
2083
- function _POST$1() {
2084
- _POST$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2085
- var yurl, _yurl$pathname$split$, tenantId, url;
2086
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2087
- while (1) switch (_context.prev = _context.next) {
2088
- case 0:
2089
- yurl = new URL(init.request.url);
2090
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1]; // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2091
- // @ts-ignore
2092
- init.body = JSON.stringify({
2093
- email: session.email
2094
- });
2095
- init.method = 'PUT';
2096
- url = apiRoutes.TENANT_USERS(tenantId);
2097
- log('[PUT]', url);
2098
- _context.next = 8;
2099
- return request(url, init);
2100
- case 8:
2101
- return _context.abrupt("return", _context.sent);
2102
- case 9:
2103
- case "end":
2104
- return _context.stop();
2105
- }
2106
- }, _callee);
2107
- }));
2108
- return _POST$1.apply(this, arguments);
2109
- }
2110
-
2111
- /**
2112
- * @swagger
2113
- * /api/tenants/{tenantId}/users/{email}:
2114
- * delete:
2115
- * tags:
2116
- * - tenants
2117
- * summary: removes a user from a tenant
2118
- * description: removes an associated user from a specified
2119
- * tenant.
2120
- * operationId: unlinkUser
2121
- * parameters:
2122
- * - name: tenantId
2123
- * in: path
2124
- * required: true
2125
- * schema:
2126
- * type: string
2127
- * - name: email
2128
- * in: path
2129
- * required: true
2130
- * schema:
2131
- * type: string
2132
-
2133
- * responses:
2134
- * "204":
2135
- * description: User removed
2136
- */
2137
- function DELETE$1(_x, _x2, _x3) {
2138
- return _DELETE$1.apply(this, arguments);
2139
- }
2140
- function _DELETE$1() {
2141
- _DELETE$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2142
- var yurl, _yurl$pathname$split$, userId, tenantId, url;
2143
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2144
- while (1) switch (_context.prev = _context.next) {
2145
- case 0:
2146
- yurl = new URL(init.request.url); // eslint-disable-next-line @typescript-eslint/no-unused-vars
2147
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), userId = _yurl$pathname$split$[0], tenantId = _yurl$pathname$split$[2];
2148
- if (tenantId) {
2149
- _context.next = 4;
2150
- break;
2151
- }
2152
- return _context.abrupt("return", new Response(null, {
2153
- status: 404
2154
- }));
2155
- case 4:
2156
- init.method = 'DELETE';
2157
- init.body = JSON.stringify({
2158
- email: userId
2159
- });
2160
- url = "" + apiRoutes.TENANT_USER(tenantId, userId);
2161
- log('[DELETE]', url);
2162
- _context.next = 10;
2163
- return request(url, init);
2164
- case 10:
2165
- return _context.abrupt("return", _context.sent);
2166
- case 11:
2167
- case "end":
2168
- return _context.stop();
2169
- }
2170
- }, _callee);
2171
- }));
2172
- return _DELETE$1.apply(this, arguments);
2173
- }
2174
-
2175
- /**
2176
- * @swagger
2177
- * /api/tenants/{tenantId}/users:
2178
- * put:
2179
- * tags:
2180
- * - tenants
2181
- * summary: associates an existing user with the tenant
2182
- * operationId: linkUser
2183
- * parameters:
2184
- * - name: tenantId
2185
- * in: path
2186
- * required: true
2187
- * schema:
2188
- * type: string
2189
- * requestBody:
2190
- * description: |
2191
- * The email of the user you want to add to a tenant.
2192
- * content:
2193
- * application/json:
2194
- * schema:
2195
- * $ref: '#/components/schemas/AssociateUserRequest'
2196
- * responses:
2197
- * "201":
2198
- * description: add user to tenant
2199
- */
2200
- function PUT(_x, _x2, _x3) {
2201
- return _PUT.apply(this, arguments);
2202
- }
2203
- function _PUT() {
2204
- _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2205
- var yurl, _yurl$pathname$split$, tenantId, url;
2206
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2207
- while (1) switch (_context.prev = _context.next) {
2208
- case 0:
2209
- yurl = new URL(init.request.url);
2210
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[1];
2211
- if (tenantId) {
2212
- _context.next = 4;
2213
- break;
2214
- }
2215
- return _context.abrupt("return", new Response(null, {
2216
- status: 404
2217
- }));
2218
- case 4:
2219
- init.method = 'PUT';
2220
- url = "" + apiRoutes.TENANT_USERS(tenantId);
2221
- log('[PUT]', url);
2222
- _context.next = 9;
2223
- return request(url, init);
2224
- case 9:
2225
- return _context.abrupt("return", _context.sent);
2226
- case 10:
2227
- case "end":
2228
- return _context.stop();
2229
- }
2230
- }, _callee);
2231
- }));
2232
- return _PUT.apply(this, arguments);
2233
- }
2234
-
2235
- var key$4 = 'TENANT_USERS';
2236
- function route$8(_x, _x2) {
2237
- return _route$8.apply(this, arguments);
2238
- }
2239
- function _route$8() {
2240
- _route$8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
2241
- var _Logger, info, session;
2242
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2243
- while (1) switch (_context.prev = _context.next) {
2244
- case 0:
2245
- _Logger = Logger(_extends({}, config, {
2246
- debug: config.debug
2247
- }), '[ROUTES]', "[" + key$4 + "]"), info = _Logger.info;
2248
- _context.next = 3;
2249
- return auth(request, config);
2250
- case 3:
2251
- session = _context.sent;
2252
- if (session) {
2253
- _context.next = 7;
2254
- break;
2255
- }
2256
- info('401');
2257
- return _context.abrupt("return", new Response(null, {
2258
- status: 401
2259
- }));
2260
- case 7:
2261
- _context.t0 = request.method;
2262
- _context.next = _context.t0 === 'GET' ? 10 : _context.t0 === 'POST' ? 13 : _context.t0 === 'PUT' ? 16 : _context.t0 === 'DELETE' ? 19 : 22;
2263
- break;
2264
- case 10:
2265
- _context.next = 12;
2266
- return GET$1(session, {
2267
- request: request
2268
- }, info);
2269
- case 12:
2270
- return _context.abrupt("return", _context.sent);
2271
- case 13:
2272
- _context.next = 15;
2273
- return POST$1(session, {
2274
- request: request
2275
- }, info);
2276
- case 15:
2277
- return _context.abrupt("return", _context.sent);
2278
- case 16:
2279
- _context.next = 18;
2280
- return PUT(session, {
2281
- request: request
2282
- }, info);
2283
- case 18:
2284
- return _context.abrupt("return", _context.sent);
2285
- case 19:
2286
- _context.next = 21;
2287
- return DELETE$1(session, {
2288
- request: request
2289
- }, info);
2290
- case 21:
2291
- return _context.abrupt("return", _context.sent);
2292
- case 22:
2293
- return _context.abrupt("return", new Response('method not allowed', {
2294
- status: 405
2295
- }));
2296
- case 23:
2297
- case "end":
2298
- return _context.stop();
2299
- }
2300
- }, _callee);
2301
- }));
2302
- return _route$8.apply(this, arguments);
2303
- }
2304
- function matches$8(configRoutes, request) {
2305
- var url = new URL(request.url);
2306
- var _url$pathname$split$r = url.pathname.split('/').reverse(),
2307
- userId = _url$pathname$split$r[0],
2308
- possibleTenantId = _url$pathname$split$r[1],
2309
- tenantId = _url$pathname$split$r[2];
2310
- var route = configRoutes[key$4].replace('{tenantId}', tenantId).replace('{userId}', userId);
2311
- if (userId === 'users') {
2312
- route = configRoutes[key$4].replace('{tenantId}', possibleTenantId);
2313
- }
2314
- return urlMatches(request.url, route);
2315
- }
2316
-
2317
- /**
2318
- * @swagger
2319
- * /api/tenants:
2320
- * get:
2321
- * tags:
2322
- * - tenants
2323
- * summary: list tenants by user
2324
- * description: Creates a user in the database
2325
- * operationId: listTenants
2326
- * responses:
2327
- * "200":
2328
- * description: a list of tenants
2329
- * content:
2330
- * application/json:
2331
- * schema:
2332
- * type: array
2333
- * items:
2334
- * $ref: "#/components/schemas/Tenant"
2335
- * "400":
2336
- * description: API/Database failures
2337
- * content:
2338
- * text/plain:
2339
- * schema:
2340
- * type: string
2341
- * "401":
2342
- * description: Unauthorized
2343
- * content: {}
2344
- */
2345
- function GET(_x, _x2, _x3) {
2346
- return _GET.apply(this, arguments);
2347
- }
2348
- function _GET() {
2349
- _GET = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2350
- var url, res;
2351
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2352
- while (1) switch (_context.prev = _context.next) {
2353
- case 0:
2354
- url = "" + apiRoutes.USER_TENANTS(session.id);
2355
- if (typeof session === 'object' && 'user' in session && session.user) {
2356
- url = "" + apiRoutes.USER_TENANTS(session.user.id);
2357
- }
2358
- log('[GET]', url);
2359
- _context.next = 5;
2360
- return request(url, init);
2361
- case 5:
2362
- res = _context.sent;
2363
- return _context.abrupt("return", res);
2364
- case 7:
2365
- case "end":
2366
- return _context.stop();
2367
- }
2368
- }, _callee);
2369
- }));
2370
- return _GET.apply(this, arguments);
2371
- }
2372
-
2373
- /**
2374
- * @swagger
2375
- * /api/tenants/{tenantId}:
2376
- * delete:
2377
- * tags:
2378
- * - tenants
2379
- * summary: Deletes a tenant.
2380
- * operationId: deleteTenant
2381
- * parameters:
2382
- * - name: tenantId
2383
- * in: path
2384
- * required: true
2385
- * schema:
2386
- * type: string
2387
- * responses:
2388
- * "204":
2389
- * description: Tenant deleted
2390
- * "401":
2391
- * description: Unauthorized
2392
- * content:
2393
- * application/json:
2394
- * schema:
2395
- * $ref: '#/components/schemas/APIError'
2396
- * "404":
2397
- * description: Tenant not found
2398
- * content:
2399
- * application/json:
2400
- * schema:
2401
- * $ref: '#/components/schemas/APIError'
2402
- */
2403
- function DELETE(_x, _x2, _x3) {
2404
- return _DELETE.apply(this, arguments);
2405
- }
2406
- function _DELETE() {
2407
- _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2408
- var yurl, _yurl$pathname$split$, tenantId, url;
2409
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2410
- while (1) switch (_context.prev = _context.next) {
2411
- case 0:
2412
- yurl = new URL(init.request.url);
2413
- _yurl$pathname$split$ = yurl.pathname.split('/').reverse(), tenantId = _yurl$pathname$split$[0];
2414
- if (tenantId) {
2415
- _context.next = 4;
2416
- break;
2417
- }
2418
- return _context.abrupt("return", new Response(null, {
2419
- status: 404
2420
- }));
2421
- case 4:
2422
- init.method = 'DELETE';
2423
- url = "" + apiRoutes.TENANT(tenantId);
2424
- log('[DELETE]', url);
2425
- _context.next = 9;
2426
- return request(url, init);
2427
- case 9:
2428
- return _context.abrupt("return", _context.sent);
2429
- case 10:
2430
- case "end":
2431
- return _context.stop();
2432
- }
2433
- }, _callee);
2434
- }));
2435
- return _DELETE.apply(this, arguments);
2436
- }
2437
-
2438
- /**
2439
- * @swagger
2440
- * /api/tenants:
2441
- * post:
2442
- * tags:
2443
- * - tenants
2444
- * summary: Create a tenant
2445
- * description: Creates a new tenant in a database.
2446
- * operationId: createTenant
2447
- * requestBody:
2448
- * description: A wrapper for the tenant name.
2449
- * content:
2450
- * application/json:
2451
- * schema:
2452
- * $ref: '#/components/schemas/CreateTenantRequest'
2453
- * examples:
2454
- * Create Tenant Request:
2455
- * summary: Creates a named tenant
2456
- * description: Create Tenant Request
2457
- * value:
2458
- * name: My Sandbox
2459
- * responses:
2460
- * "201":
2461
- * description: Tenant created
2462
- * content:
2463
- * application/json:
2464
- * schema:
2465
- * $ref: '#/components/schemas/Tenant'
2466
- * "401":
2467
- * description: Unauthorized
2468
- * content:
2469
- * application/json:
2470
- * schema:
2471
- * $ref: '#/components/schemas/APIError'
2472
- * "404":
2473
- * description: Database not found
2474
- * content:
2475
- * application/json:
2476
- * schema:
2477
- * $ref: '#/components/schemas/APIError'
2478
- */
2479
- function POST(_x, _x2, _x3) {
2480
- return _POST.apply(this, arguments);
2481
- }
2482
- function _POST() {
2483
- _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(session, init, log) {
2484
- var url;
2485
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2486
- while (1) switch (_context.prev = _context.next) {
2487
- case 0:
2488
- init.body = init.request.body;
2489
- init.method = 'POST';
2490
- url = "" + apiRoutes.TENANTS;
2491
- log('[POST]', url);
2492
- _context.next = 6;
2493
- return request(url, init);
2494
- case 6:
2495
- return _context.abrupt("return", _context.sent);
2496
- case 7:
2497
- case "end":
2498
- return _context.stop();
2499
- }
2500
- }, _callee);
2501
- }));
2502
- return _POST.apply(this, arguments);
2503
- }
2504
-
2505
- var key$3 = 'TENANTS';
2506
- function route$7(_x, _x2) {
2507
- return _route$7.apply(this, arguments);
2508
- }
2509
- function _route$7() {
2510
- _route$7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request, config) {
2511
- var _Logger, info, session;
2512
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2513
- while (1) switch (_context.prev = _context.next) {
2514
- case 0:
2515
- _Logger = Logger(_extends({}, config, {
2516
- debug: config.debug
2517
- }), '[ROUTES]', "[" + key$3 + "]"), info = _Logger.info;
2518
- _context.next = 3;
2519
- return auth(request, config);
2520
- case 3:
2521
- session = _context.sent;
2522
- if (session) {
2523
- _context.next = 7;
2524
- break;
2525
- }
2526
- info('401');
2527
- return _context.abrupt("return", new Response(null, {
2528
- status: 401
2529
- }));
2530
- case 7:
2531
- _context.t0 = request.method;
2532
- _context.next = _context.t0 === 'GET' ? 10 : _context.t0 === 'POST' ? 13 : _context.t0 === 'DELETE' ? 16 : 19;
2533
- break;
2534
- case 10:
2535
- _context.next = 12;
2536
- return GET(session, {
2537
- request: request
2538
- }, info);
2539
- case 12:
2540
- return _context.abrupt("return", _context.sent);
2541
- case 13:
2542
- _context.next = 15;
2543
- return POST(session, {
2544
- request: request
2545
- }, info);
2546
- case 15:
2547
- return _context.abrupt("return", _context.sent);
2548
- case 16:
2549
- _context.next = 18;
2550
- return DELETE(session, {
2551
- request: request
2552
- }, info);
2553
- case 18:
2554
- return _context.abrupt("return", _context.sent);
2555
- case 19:
2556
- return _context.abrupt("return", new Response('method not allowed', {
2557
- status: 405
2558
- }));
2559
- case 20:
2560
- case "end":
2561
- return _context.stop();
2562
- }
2563
- }, _callee);
2564
- }));
2565
- return _route$7.apply(this, arguments);
2566
- }
2567
- function matches$7(configRoutes, request) {
2568
- return urlMatches(request.url, configRoutes[key$3]);
2569
- }
2570
-
2571
- var proxyRoutes = {
2572
- SIGNIN: /*#__PURE__*/makeRestUrl('/auth/signin'),
2573
- PROVIDERS: /*#__PURE__*/makeRestUrl('/auth/providers'),
2574
- SESSION: /*#__PURE__*/makeRestUrl('/auth/session'),
2575
- CSRF: /*#__PURE__*/makeRestUrl('/auth/csrf'),
2576
- CALLBACK: /*#__PURE__*/makeRestUrl('/auth/callback'),
2577
- SIGNOUT: /*#__PURE__*/makeRestUrl('/auth/signout'),
2578
- ERROR: /*#__PURE__*/makeRestUrl('/auth/error')
2579
- };
2580
-
2581
- var key$2 = 'SIGNIN';
2582
- function route$6(_x) {
2583
- return _route$6.apply(this, arguments);
2584
- }
2585
- function _route$6() {
2586
- _route$6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2587
- var url, init, _URL$pathname$split$r, provider, passThroughUrl, params, res;
2588
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2589
- while (1) switch (_context.prev = _context.next) {
2590
- case 0:
2591
- url = proxyRoutes[key$2];
2592
- init = {
2593
- method: req.method,
2594
- headers: req.headers
2595
- };
2596
- if (req.method === 'POST') {
2597
- if (typeof req.clone === 'function') {
2598
- init.body = req.clone().body;
2599
- }
2600
- _URL$pathname$split$r = new URL(req.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
2601
- url = proxyRoutes[key$2] + "/" + provider;
2602
- }
2603
- passThroughUrl = new URL(req.url);
2604
- params = new URLSearchParams(passThroughUrl.search);
2605
- url = "" + url + (params.toString() !== '' ? "?" + params.toString() : '');
2606
- _context.next = 8;
2607
- return request(url, _extends({}, init, {
2608
- request: req
2609
- }));
2610
- case 8:
2611
- res = _context.sent;
2612
- return _context.abrupt("return", res);
2613
- case 10:
2614
- case "end":
2615
- return _context.stop();
2616
- }
2617
- }, _callee);
2618
- }));
2619
- return _route$6.apply(this, arguments);
2620
- }
2621
- function matches$6(configRoutes, request) {
2622
- return urlMatches(request.url, configRoutes[key$2]);
2623
- }
2624
-
2625
- function route$5(_x, _x2) {
2626
- return _route$5.apply(this, arguments);
2627
- }
2628
- function _route$5() {
2629
- _route$5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
2630
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2631
- while (1) switch (_context.prev = _context.next) {
2632
- case 0:
2633
- return _context.abrupt("return", request(proxyRoutes.SESSION, {
2634
- method: req.method,
2635
- request: req
2636
- }, config));
2637
- case 1:
2638
- case "end":
2639
- return _context.stop();
2640
- }
2641
- }, _callee);
2642
- }));
2643
- return _route$5.apply(this, arguments);
2644
- }
2645
- function matches$5(configRoutes, request) {
2646
- return urlMatches(request.url, configRoutes.SESSION);
2647
- }
2648
-
2649
- function route$4(_x) {
2650
- return _route$4.apply(this, arguments);
2651
- }
2652
- function _route$4() {
2653
- _route$4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2654
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2655
- while (1) switch (_context.prev = _context.next) {
2656
- case 0:
2657
- return _context.abrupt("return", request(proxyRoutes.PROVIDERS, {
2658
- method: req.method,
2659
- request: req
2660
- }));
2661
- case 1:
2662
- case "end":
2663
- return _context.stop();
2664
- }
2665
- }, _callee);
2666
- }));
2667
- return _route$4.apply(this, arguments);
2668
- }
2669
- function matches$4(configRoutes, request) {
2670
- return urlMatches(request.url, configRoutes.PROVIDERS);
2671
- }
2672
-
2673
- function route$3(_x) {
2674
- return _route$3.apply(this, arguments);
2675
- }
2676
- function _route$3() {
2677
- _route$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2678
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2679
- while (1) switch (_context.prev = _context.next) {
2680
- case 0:
2681
- return _context.abrupt("return", request(proxyRoutes.CSRF, {
2682
- method: req.method,
2683
- request: req
2684
- }));
2685
- case 1:
2686
- case "end":
2687
- return _context.stop();
2688
- }
2689
- }, _callee);
2690
- }));
2691
- return _route$3.apply(this, arguments);
2692
- }
2693
- function matches$3(configRoutes, request) {
2694
- return urlMatches(request.url, configRoutes.CSRF);
2695
- }
2696
-
2697
- var _console = console,
2698
- log = _console.log,
2699
- error = _console.error;
2700
- function route$2(_x) {
2701
- return _route$2.apply(this, arguments);
2702
- }
2703
- function _route$2() {
2704
- _route$2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
2705
- var _URL$pathname$split$r, provider, passThroughUrl, params, url, res, location;
2706
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2707
- while (1) switch (_context.prev = _context.next) {
2708
- case 0:
2709
- _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
2710
- passThroughUrl = new URL(request$1.url);
2711
- params = new URLSearchParams(passThroughUrl.search);
2712
- url = proxyRoutes.CALLBACK + "/" + provider + (params.toString() !== '' ? "?" + params.toString() : '');
2713
- _context.next = 6;
2714
- return request(url, {
2715
- request: request$1,
2716
- method: request$1.method
2717
- })["catch"](function (e) {
2718
- error('an error has occurred in callback');
2719
- log(e);
2720
- });
2721
- case 6:
2722
- res = _context.sent;
2723
- location = res == null ? void 0 : res.headers.get('location');
2724
- if (!location) {
2725
- _context.next = 10;
2726
- break;
2727
- }
2728
- return _context.abrupt("return", new Response(res == null ? void 0 : res.body, {
2729
- status: 302,
2730
- headers: res == null ? void 0 : res.headers
2731
- }));
2732
- case 10:
2733
- return _context.abrupt("return", new Response(res == null ? void 0 : res.body, {
2734
- status: res == null ? void 0 : res.status,
2735
- headers: res == null ? void 0 : res.headers
2736
- }));
2737
- case 11:
2738
- case "end":
2739
- return _context.stop();
2740
- }
2741
- }, _callee);
2742
- }));
2743
- return _route$2.apply(this, arguments);
2744
- }
2745
- function matches$2(configRoutes, request) {
2746
- return urlMatches(request.url, configRoutes.CALLBACK);
2747
- }
2748
-
2749
- var key$1 = 'SIGNOUT';
2750
- function route$1(_x) {
2751
- return _route$1.apply(this, arguments);
2752
- }
2753
- function _route$1() {
2754
- _route$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request$1) {
2755
- var url, init, _URL$pathname$split$r, provider, res;
2756
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2757
- while (1) switch (_context.prev = _context.next) {
2758
- case 0:
2759
- url = proxyRoutes[key$1];
2760
- init = {
2761
- method: request$1.method
2762
- };
2763
- if (request$1.method === 'POST') {
2764
- init.body = request$1.body;
2765
- _URL$pathname$split$r = new URL(request$1.url).pathname.split('/').reverse(), provider = _URL$pathname$split$r[0];
2766
- url = proxyRoutes[key$1] + "/" + provider;
2767
- }
2768
- _context.next = 5;
2769
- return request(url, _extends({}, init, {
2770
- request: request$1
2771
- }));
2772
- case 5:
2773
- res = _context.sent;
2774
- return _context.abrupt("return", res);
2775
- case 7:
2776
- case "end":
2777
- return _context.stop();
2778
- }
2779
- }, _callee);
2780
- }));
2781
- return _route$1.apply(this, arguments);
2782
- }
2783
- function matches$1(configRoutes, request) {
2784
- return urlMatches(request.url, configRoutes[key$1]);
2785
- }
2786
-
2787
- var key = 'ERROR';
2788
- function route(_x) {
2789
- return _route.apply(this, arguments);
2790
- }
2791
- function _route() {
2792
- _route = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2793
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2794
- while (1) switch (_context.prev = _context.next) {
2795
- case 0:
2796
- return _context.abrupt("return", request(proxyRoutes[key], {
2797
- method: req.method,
2798
- request: req
2799
- }));
2800
- case 1:
2801
- case "end":
2802
- return _context.stop();
2803
- }
2804
- }, _callee);
2805
- }));
2806
- return _route.apply(this, arguments);
2807
- }
2808
- function matches(configRoutes, request) {
2809
- return urlMatches(request.url, configRoutes[key]);
2810
- }
2811
-
2812
- function GETTER(configRoutes, config) {
2813
- return /*#__PURE__*/function () {
2814
- var _GET = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2815
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2816
- while (1) switch (_context.prev = _context.next) {
2817
- case 0:
2818
- if (!matches$a(configRoutes, req)) {
2819
- _context.next = 2;
2820
- break;
2821
- }
2822
- return _context.abrupt("return", route$a(req, config));
2823
- case 2:
2824
- if (!matches$9(configRoutes, req)) {
2825
- _context.next = 4;
2826
- break;
2827
- }
2828
- return _context.abrupt("return", route$9(req, config));
2829
- case 4:
2830
- if (!matches$8(configRoutes, req)) {
2831
- _context.next = 6;
2832
- break;
2833
- }
2834
- return _context.abrupt("return", route$8(req, config));
2835
- case 6:
2836
- if (!matches$7(configRoutes, req)) {
2837
- _context.next = 8;
2838
- break;
2839
- }
2840
- return _context.abrupt("return", route$7(req, config));
2841
- case 8:
2842
- if (!matches$5(configRoutes, req)) {
2843
- _context.next = 10;
2844
- break;
2845
- }
2846
- return _context.abrupt("return", route$5(req, config));
2847
- case 10:
2848
- if (!matches$6(configRoutes, req)) {
2849
- _context.next = 12;
2850
- break;
2851
- }
2852
- return _context.abrupt("return", route$6(req));
2853
- case 12:
2854
- if (!matches$4(configRoutes, req)) {
2855
- _context.next = 14;
2856
- break;
2857
- }
2858
- return _context.abrupt("return", route$4(req));
2859
- case 14:
2860
- if (!matches$3(configRoutes, req)) {
2861
- _context.next = 16;
2862
- break;
2863
- }
2864
- return _context.abrupt("return", route$3(req));
2865
- case 16:
2866
- if (!matches$2(configRoutes, req)) {
2867
- _context.next = 18;
2868
- break;
2869
- }
2870
- return _context.abrupt("return", route$2(req));
2871
- case 18:
2872
- if (!matches$1(configRoutes, req)) {
2873
- _context.next = 20;
2874
- break;
2875
- }
2876
- return _context.abrupt("return", route$1(req));
2877
- case 20:
2878
- if (!matches(configRoutes, req)) {
2879
- _context.next = 22;
2880
- break;
2881
- }
2882
- return _context.abrupt("return", route(req));
2883
- case 22:
2884
- return _context.abrupt("return", new Response(null, {
2885
- status: 404
2886
- }));
2887
- case 23:
2888
- case "end":
2889
- return _context.stop();
2890
- }
2891
- }, _callee);
2892
- }));
2893
- function GET(_x) {
2894
- return _GET.apply(this, arguments);
2895
- }
2896
- return GET;
2897
- }();
2898
- }
2899
-
2900
- function POSTER(configRoutes, config) {
2901
- return /*#__PURE__*/function () {
2902
- var _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2903
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2904
- while (1) switch (_context.prev = _context.next) {
2905
- case 0:
2906
- if (!matches$8(configRoutes, req)) {
2907
- _context.next = 2;
2908
- break;
2909
- }
2910
- return _context.abrupt("return", route$8(req, config));
2911
- case 2:
2912
- if (!matches$9(configRoutes, req)) {
2913
- _context.next = 4;
2914
- break;
2915
- }
2916
- return _context.abrupt("return", route$9(req, config));
2917
- case 4:
2918
- if (!matches$7(configRoutes, req)) {
2919
- _context.next = 6;
2920
- break;
2921
- }
2922
- return _context.abrupt("return", route$7(req, config));
2923
- case 6:
2924
- if (!matches$5(configRoutes, req)) {
2925
- _context.next = 8;
2926
- break;
2927
- }
2928
- return _context.abrupt("return", route$5(req, config));
2929
- case 8:
2930
- if (!matches$6(configRoutes, req)) {
2931
- _context.next = 10;
2932
- break;
2933
- }
2934
- return _context.abrupt("return", route$6(req));
2935
- case 10:
2936
- if (!matches$4(configRoutes, req)) {
2937
- _context.next = 12;
2938
- break;
2939
- }
2940
- return _context.abrupt("return", route$4(req));
2941
- case 12:
2942
- if (!matches$3(configRoutes, req)) {
2943
- _context.next = 14;
2944
- break;
2945
- }
2946
- return _context.abrupt("return", route$3(req));
2947
- case 14:
2948
- if (!matches$2(configRoutes, req)) {
2949
- _context.next = 16;
2950
- break;
2951
- }
2952
- return _context.abrupt("return", route$2(req));
2953
- case 16:
2954
- if (!matches$1(configRoutes, req)) {
2955
- _context.next = 18;
2956
- break;
2957
- }
2958
- return _context.abrupt("return", route$1(req));
2959
- case 18:
2960
- return _context.abrupt("return", new Response(null, {
2961
- status: 404
2962
- }));
2963
- case 19:
2964
- case "end":
2965
- return _context.stop();
2966
- }
2967
- }, _callee);
2968
- }));
2969
- function POST(_x) {
2970
- return _POST.apply(this, arguments);
2971
- }
2972
- return POST;
2973
- }();
2974
- }
2975
-
2976
- function DELETER(configRoutes, config) {
2977
- return /*#__PURE__*/function () {
2978
- var _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2979
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2980
- while (1) switch (_context.prev = _context.next) {
2981
- case 0:
2982
- if (!matches$8(configRoutes, req)) {
2983
- _context.next = 2;
2984
- break;
2985
- }
2986
- return _context.abrupt("return", route$8(req, config));
2987
- case 2:
2988
- if (!matches$7(configRoutes, req)) {
2989
- _context.next = 4;
2990
- break;
2991
- }
2992
- return _context.abrupt("return", route$7(req, config));
2993
- case 4:
2994
- return _context.abrupt("return", new Response(null, {
2995
- status: 404
2996
- }));
2997
- case 5:
2998
- case "end":
2999
- return _context.stop();
3000
- }
3001
- }, _callee);
3002
- }));
3003
- function DELETE(_x) {
3004
- return _DELETE.apply(this, arguments);
3005
- }
3006
- return DELETE;
3007
- }();
3008
- }
3009
-
3010
- function PUTER(configRoutes, config) {
3011
- return /*#__PURE__*/function () {
3012
- var _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3013
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3014
- while (1) switch (_context.prev = _context.next) {
3015
- case 0:
3016
- if (!matches$8(configRoutes, req)) {
3017
- _context.next = 2;
3018
- break;
3019
- }
3020
- return _context.abrupt("return", route$8(req, config));
3021
- case 2:
3022
- if (!matches$9(configRoutes, req)) {
3023
- _context.next = 4;
3024
- break;
3025
- }
3026
- return _context.abrupt("return", route$9(req, config));
3027
- case 4:
3028
- if (!matches$7(configRoutes, req)) {
3029
- _context.next = 6;
3030
- break;
3031
- }
3032
- return _context.abrupt("return", route$7(req, config));
3033
- case 6:
3034
- return _context.abrupt("return", new Response(null, {
3035
- status: 404
3036
- }));
3037
- case 7:
3038
- case "end":
3039
- return _context.stop();
3040
- }
3041
- }, _callee);
3042
- }));
3043
- function PUT(_x) {
3044
- return _PUT.apply(this, arguments);
3045
- }
3046
- return PUT;
3047
- }();
3048
- }
3049
-
3050
- function Handlers(configRoutes, config) {
3051
- var GET = GETTER(configRoutes, config);
3052
- var POST = POSTER(configRoutes, config);
3053
- var DELETE = DELETER(configRoutes, config);
3054
- var PUT = PUTER(configRoutes, config);
3055
- return {
3056
- GET: GET,
3057
- POST: POST,
3058
- DELETE: DELETE,
3059
- PUT: PUT
3060
- };
3061
- }
3062
-
3063
- var appRoutes = function appRoutes(prefix) {
3064
- if (prefix === void 0) {
3065
- prefix = '/api';
3066
- }
3067
- return {
3068
- SIGNIN: prefix + "/auth/signin",
3069
- PROVIDERS: prefix + "/auth/providers",
3070
- SESSION: prefix + "/auth/session",
3071
- CSRF: prefix + "/auth/csrf",
3072
- CALLBACK: prefix + "/auth/callback",
3073
- SIGNOUT: prefix + "/auth/signout",
3074
- ERROR: prefix + "/auth/error",
3075
- ME: prefix + "/me",
3076
- USERS: prefix + "/users",
3077
- TENANTS: prefix + "/tenants",
3078
- TENANT_USER: prefix + "/tenants/{tenantId}/users/{userId}",
3079
- TENANT_USERS: prefix + "/tenants/{tenantId}/users",
3080
- SIGNUP: prefix + "/signup"
3081
- };
3082
- };
3083
-
3084
- /**
3085
- * a helper function to log in server side.
3086
- */
3087
- function serverAuth(config, handlers) {
3088
- var _Logger = Logger(config, '[serverAuth]'),
3089
- info = _Logger.info;
3090
- return /*#__PURE__*/function () {
3091
- var _login = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
3092
- var _yield$csrfRes$json, _exec;
3093
- var email, password, sessionUrl, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, _ref2, csrfToken, credentials, csrfCookie, signInUrl, postReq, loginRes, authCookie, _ref3, token;
3094
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3095
- while (1) switch (_context.prev = _context.next) {
3096
- case 0:
3097
- email = _ref.email, password = _ref.password;
3098
- info('Obtaining session');
3099
- sessionUrl = new URL(config.api.localPath + "/api/auth/providers");
3100
- sessionReq = new Request(sessionUrl, {
3101
- method: 'GET',
3102
- headers: new Headers({
3103
- host: sessionUrl.host
3104
- })
3105
- });
3106
- _context.next = 6;
3107
- return handlers.POST(sessionReq);
3108
- case 6:
3109
- sessionRes = _context.sent;
3110
- _context.next = 9;
3111
- return sessionRes == null ? void 0 : sessionRes.json();
3112
- case 9:
3113
- providers = _context.sent;
3114
- info('Obtaining csrf');
3115
- csrf = new URL(config.api.localPath + "/api/auth/csrf");
3116
- csrfReq = new Request(csrf, {
3117
- method: 'GET',
3118
- headers: new Headers({
3119
- host: sessionUrl.host
3120
- })
3121
- });
3122
- _context.next = 15;
3123
- return handlers.POST(csrfReq);
3124
- case 15:
3125
- csrfRes = _context.sent;
3126
- _context.next = 18;
3127
- return csrfRes == null ? void 0 : csrfRes.json();
3128
- case 18:
3129
- _context.t0 = _yield$csrfRes$json = _context.sent;
3130
- if (!(_context.t0 != null)) {
3131
- _context.next = 23;
3132
- break;
3133
- }
3134
- _context.t1 = _yield$csrfRes$json;
3135
- _context.next = 24;
3136
- break;
3137
- case 23:
3138
- _context.t1 = {};
3139
- case 24:
3140
- _ref2 = _context.t1;
3141
- csrfToken = _ref2.csrfToken;
3142
- credentials = providers.credentials;
3143
- csrfCookie = csrfRes == null ? void 0 : csrfRes.headers.get('set-cookie');
3144
- signInUrl = new URL(credentials.callbackUrl);
3145
- if (csrfCookie) {
3146
- _context.next = 31;
3147
- break;
3148
- }
3149
- throw new Error('Unable to authenticate REST');
3150
- case 31:
3151
- info('Attempting sign in to', signInUrl.href);
3152
- postReq = new Request(signInUrl, {
3153
- method: 'POST',
3154
- headers: new Headers({
3155
- 'content-type': 'application/json',
3156
- cookie: csrfCookie
3157
- }),
3158
- body: JSON.stringify({
3159
- email: email,
3160
- password: password,
3161
- csrfToken: csrfToken,
3162
- callbackUrl: credentials.callbackUrl
3163
- })
3164
- });
3165
- _context.next = 35;
3166
- return handlers.POST(postReq);
3167
- case 35:
3168
- loginRes = _context.sent;
3169
- authCookie = loginRes == null ? void 0 : loginRes.headers.get('set-cookie');
3170
- if (authCookie) {
3171
- _context.next = 39;
3172
- break;
3173
- }
3174
- throw new Error('authentication failed');
3175
- case 39:
3176
- info('Server login successful');
3177
- _ref3 = (_exec = /(nile\.session-token=.+?);/.exec(authCookie)) != null ? _exec : [], token = _ref3[1];
3178
- return _context.abrupt("return", new Headers({
3179
- cookie: [token, csrfCookie].join('; ')
3180
- }));
3181
- case 42:
3182
- case "end":
3183
- return _context.stop();
3184
- }
3185
- }, _callee);
3186
- }));
3187
- function login(_x) {
3188
- return _login.apply(this, arguments);
3189
- }
3190
- return login;
3191
- }();
3192
- }
3193
-
3194
- var Requester = /*#__PURE__*/function (_Config) {
3195
- function Requester(config) {
3196
- return _Config.call(this, config) || this;
3197
- }
3198
- _inheritsLoose(Requester, _Config);
3199
- var _proto = Requester.prototype;
3200
- _proto.rawRequest = /*#__PURE__*/function () {
3201
- var _rawRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(method, url, init, body) {
3202
- var _init, res;
3203
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3204
- while (1) switch (_context.prev = _context.next) {
3205
- case 0:
3206
- _init = _extends({}, init, {
3207
- body: body,
3208
- method: method
3209
- });
3210
- _context.next = 3;
3211
- return _fetch(this, url, _init);
3212
- case 3:
3213
- res = _context.sent;
3214
- if (!(res instanceof ResponseError)) {
3215
- _context.next = 6;
3216
- break;
3217
- }
3218
- return _context.abrupt("return", res.response);
3219
- case 6:
3220
- return _context.abrupt("return", res);
3221
- case 7:
3222
- case "end":
3223
- return _context.stop();
3224
- }
3225
- }, _callee, this);
3226
- }));
3227
- function rawRequest(_x, _x2, _x3, _x4) {
3228
- return _rawRequest.apply(this, arguments);
3229
- }
3230
- return rawRequest;
3231
- }()
3232
- /**
3233
- * three options here
3234
- * 1) pass in headers for a server side request
3235
- * 2) pass in the payload that matches the api
3236
- * 3) pass in the request object sent by a browser
3237
- * @param method
3238
- * @param url
3239
- * @param req
3240
- * @param init
3241
- * @returns
3242
- */
3243
- ;
3244
- _proto.request =
3245
- /*#__PURE__*/
3246
- function () {
3247
- var _request = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(method, url, req, init) {
3248
- var headers, tenantId, cookie, _headers, _tenantId, _cookie, body, _init;
3249
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3250
- while (1) switch (_context2.prev = _context2.next) {
3251
- case 0:
3252
- // set the headers
3253
- headers = new Headers(init ? init == null ? void 0 : init.headers : {});
3254
- if (req instanceof Headers) {
3255
- tenantId = req.get(X_NILE_TENANT);
3256
- cookie = req.get('cookie');
3257
- if (tenantId) {
3258
- headers.set(X_NILE_TENANT, tenantId);
3259
- }
3260
- if (cookie) {
3261
- headers.set('cookie', cookie);
3262
- }
3263
- } else if (req instanceof Request) {
3264
- // pass back the X_NILE_TENANT
3265
- _headers = new Headers(req == null ? void 0 : req.headers);
3266
- _tenantId = _headers.get(X_NILE_TENANT);
3267
- _cookie = _headers.get('cookie');
3268
- if (_tenantId) {
3269
- headers.set(X_NILE_TENANT, _tenantId);
3270
- }
3271
- if (_cookie) {
3272
- headers.set('cookie', _cookie);
3273
- }
3274
- }
3275
- // default the body - may be the actual payload for the API
3276
- body = JSON.stringify(req); // comes from next/some server
3277
- if (!(method === 'GET')) {
3278
- _context2.next = 7;
3279
- break;
3280
- }
3281
- body = undefined;
3282
- _context2.next = 14;
3283
- break;
3284
- case 7:
3285
- if (!(req instanceof Request)) {
3286
- _context2.next = 13;
3287
- break;
3288
- }
3289
- _context2.next = 10;
3290
- return new Response(req.body).text();
3291
- case 10:
3292
- body = _context2.sent;
3293
- _context2.next = 14;
3294
- break;
3295
- case 13:
3296
- if (
3297
- // is just headers for a GET request
3298
- req instanceof Headers || JSON.stringify(req) === '{}' || req && typeof req === 'object' && Object.values(req).length === 0) {
3299
- body = undefined;
3300
- }
3301
- case 14:
3302
- _init = _extends({}, init, {
3303
- headers: headers
3304
- });
3305
- _context2.next = 17;
3306
- return this.rawRequest(method, url, _init, body);
3307
- case 17:
3308
- return _context2.abrupt("return", _context2.sent);
3309
- case 18:
3310
- case "end":
3311
- return _context2.stop();
3312
- }
3313
- }, _callee2, this);
3314
- }));
3315
- function request(_x5, _x6, _x7, _x8) {
3316
- return _request.apply(this, arguments);
3317
- }
3318
- return request;
3319
- }();
3320
- _proto.post = /*#__PURE__*/function () {
3321
- var _post = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, url, init) {
3322
- var response;
3323
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3324
- while (1) switch (_context3.prev = _context3.next) {
3325
- case 0:
3326
- _context3.next = 2;
3327
- return this.request('POST', url, req, init);
3328
- case 2:
3329
- response = _context3.sent;
3330
- if (!(response && response.status >= 200 && response.status < 300)) {
3331
- _context3.next = 5;
3332
- break;
3333
- }
3334
- return _context3.abrupt("return", response.json());
3335
- case 5:
3336
- return _context3.abrupt("return", response);
3337
- case 6:
3338
- case "end":
3339
- return _context3.stop();
3340
- }
3341
- }, _callee3, this);
3342
- }));
3343
- function post(_x9, _x10, _x11) {
3344
- return _post.apply(this, arguments);
3345
- }
3346
- return post;
3347
- }();
3348
- _proto.get = /*#__PURE__*/function () {
3349
- var _get = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, url, init) {
3350
- var response;
3351
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3352
- while (1) switch (_context4.prev = _context4.next) {
3353
- case 0:
3354
- _context4.next = 2;
3355
- return this.request('GET', url, req, init);
3356
- case 2:
3357
- response = _context4.sent;
3358
- if (!(response && response.status >= 200 && response.status < 300)) {
3359
- _context4.next = 5;
3360
- break;
3361
- }
3362
- return _context4.abrupt("return", response.json());
3363
- case 5:
3364
- return _context4.abrupt("return", response);
3365
- case 6:
3366
- case "end":
3367
- return _context4.stop();
3368
- }
3369
- }, _callee4, this);
3370
- }));
3371
- function get(_x12, _x13, _x14) {
3372
- return _get.apply(this, arguments);
3373
- }
3374
- return get;
3375
- }();
3376
- _proto.put = /*#__PURE__*/function () {
3377
- var _put = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req, url, init) {
3378
- var response;
3379
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
3380
- while (1) switch (_context5.prev = _context5.next) {
3381
- case 0:
3382
- _context5.next = 2;
3383
- return this.request('PUT', url, req, init);
3384
- case 2:
3385
- response = _context5.sent;
3386
- if (!(response && response.status >= 200 && response.status < 300)) {
3387
- _context5.next = 5;
3388
- break;
3389
- }
3390
- return _context5.abrupt("return", response.json());
3391
- case 5:
3392
- return _context5.abrupt("return", response);
3393
- case 6:
3394
- case "end":
3395
- return _context5.stop();
3396
- }
3397
- }, _callee5, this);
3398
- }));
3399
- function put(_x15, _x16, _x17) {
3400
- return _put.apply(this, arguments);
3401
- }
3402
- return put;
3403
- }();
3404
- _proto["delete"] = /*#__PURE__*/function () {
3405
- var _delete2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, url, init) {
3406
- var response;
3407
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
3408
- while (1) switch (_context6.prev = _context6.next) {
3409
- case 0:
3410
- _context6.next = 2;
3411
- return this.request('DELETE', url, req, init);
3412
- case 2:
3413
- response = _context6.sent;
3414
- if (!(response && response.status >= 200 && response.status < 300)) {
3415
- _context6.next = 5;
3416
- break;
3417
- }
3418
- return _context6.abrupt("return", response.json());
3419
- case 5:
3420
- return _context6.abrupt("return", response);
3421
- case 6:
3422
- case "end":
3423
- return _context6.stop();
3424
- }
3425
- }, _callee6, this);
3426
- }));
3427
- function _delete(_x18, _x19, _x20) {
3428
- return _delete2.apply(this, arguments);
3429
- }
3430
- return _delete;
3431
- }();
3432
- return Requester;
3433
- }(Config);
3434
-
3435
- var Tenants = /*#__PURE__*/function (_Config) {
3436
- function Tenants(config, headers) {
3437
- var _this;
3438
- _this = _Config.call(this, config) || this;
3439
- _this.headers = void 0;
3440
- _this.createTenant = /*#__PURE__*/function () {
3441
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
3442
- var _req, _requester, _init;
3443
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3444
- while (1) switch (_context.prev = _context.next) {
3445
- case 0:
3446
- if (typeof req === 'string') {
3447
- _req = new Request("" + _this.api.basePath + _this.tenantsUrl, {
3448
- body: JSON.stringify({
3449
- name: req
3450
- }),
3451
- method: 'POST'
3452
- });
3453
- } else {
3454
- _req = req;
3455
- }
3456
- _requester = new Requester(_this);
3457
- _init = _this.handleHeaders(init);
3458
- return _context.abrupt("return", _requester.post(_req, _this.tenantsUrl, _init));
3459
- case 4:
3460
- case "end":
3461
- return _context.stop();
3462
- }
3463
- }, _callee);
3464
- }));
3465
- return function (_x, _x2) {
3466
- return _ref.apply(this, arguments);
3467
- };
3468
- }();
3469
- _this.getTenant = /*#__PURE__*/function () {
3470
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, init) {
3471
- var _requester, _init;
3472
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3473
- while (1) switch (_context2.prev = _context2.next) {
3474
- case 0:
3475
- if (typeof req === 'string') {
3476
- _this.tenantId = req;
3477
- }
3478
- _requester = new Requester(_this);
3479
- _init = _this.handleHeaders(init);
3480
- return _context2.abrupt("return", _requester.get(req, _this.tenantUrl, _init));
3481
- case 4:
3482
- case "end":
3483
- return _context2.stop();
3484
- }
3485
- }, _callee2);
3486
- }));
3487
- return function (_x3, _x4) {
3488
- return _ref2.apply(this, arguments);
3489
- };
3490
- }();
3491
- _this.listTenants = /*#__PURE__*/function () {
3492
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
3493
- var _requester, _init;
3494
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3495
- while (1) switch (_context3.prev = _context3.next) {
3496
- case 0:
3497
- _requester = new Requester(_this);
3498
- _init = _this.handleHeaders(init);
3499
- return _context3.abrupt("return", _requester.get(req, _this.tenantListUrl, _init));
3500
- case 3:
3501
- case "end":
3502
- return _context3.stop();
3503
- }
3504
- }, _callee3);
3505
- }));
3506
- return function (_x5, _x6) {
3507
- return _ref3.apply(this, arguments);
3508
- };
3509
- }();
3510
- _this.headers = headers;
3511
- return _this;
3512
- }
3513
- _inheritsLoose(Tenants, _Config);
3514
- var _proto = Tenants.prototype;
3515
- _proto.handleHeaders = function handleHeaders(init) {
3516
- if (this.headers) {
3517
- if (init) {
3518
- var _init2;
3519
- init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
3520
- return init;
3521
- } else {
3522
- init = {
3523
- headers: this.headers
3524
- };
3525
- return init;
3526
- }
3527
- }
3528
- return undefined;
3529
- };
3530
- return _createClass(Tenants, [{
3531
- key: "tenantsUrl",
3532
- get: function get() {
3533
- return '/tenants';
3534
- }
3535
- }, {
3536
- key: "tenantUrl",
3537
- get: function get() {
3538
- var _this$tenantId;
3539
- return "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
3540
- }
3541
- }, {
3542
- key: "tenantListUrl",
3543
- get: function get() {
3544
- var _this$userId;
3545
- return "/users/" + ((_this$userId = this.userId) != null ? _this$userId : '{userId}') + "/tenants";
3546
- }
3547
- }]);
3548
- }(Config);
3549
-
3550
- var Users = /*#__PURE__*/function (_Config) {
3551
- function Users(config, headers) {
3552
- var _this;
3553
- _this = _Config.call(this, config) || this;
3554
- _this.headers = void 0;
3555
- _this.createUser = /*#__PURE__*/function () {
3556
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
3557
- var _requester, _init;
3558
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3559
- while (1) switch (_context.prev = _context.next) {
3560
- case 0:
3561
- _requester = new Requester(_this);
3562
- _init = _this.handleHeaders(init);
3563
- _context.next = 4;
3564
- return _requester.post(req, _this.usersUrl, _init);
3565
- case 4:
3566
- return _context.abrupt("return", _context.sent);
3567
- case 5:
3568
- case "end":
3569
- return _context.stop();
3570
- }
3571
- }, _callee);
3572
- }));
3573
- return function (_x, _x2) {
3574
- return _ref.apply(this, arguments);
3575
- };
3576
- }();
3577
- _this.updateUser = /*#__PURE__*/function () {
3578
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(userId, req, init) {
3579
- var _requester, _init;
3580
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3581
- while (1) switch (_context2.prev = _context2.next) {
3582
- case 0:
3583
- _requester = new Requester(_this);
3584
- _init = _this.handleHeaders(init);
3585
- _context2.next = 4;
3586
- return _requester.put(req, _this.usersUrl + "/" + userId, _init);
3587
- case 4:
3588
- return _context2.abrupt("return", _context2.sent);
3589
- case 5:
3590
- case "end":
3591
- return _context2.stop();
3592
- }
3593
- }, _callee2);
3594
- }));
3595
- return function (_x3, _x4, _x5) {
3596
- return _ref2.apply(this, arguments);
3597
- };
3598
- }();
3599
- _this.listUsers = /*#__PURE__*/function () {
3600
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
3601
- var _requester, _init;
3602
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3603
- while (1) switch (_context3.prev = _context3.next) {
3604
- case 0:
3605
- _requester = new Requester(_this);
3606
- _init = _this.handleHeaders(init);
3607
- _context3.next = 4;
3608
- return _requester.get(req, _this.tenantUsersUrl, _init);
3609
- case 4:
3610
- return _context3.abrupt("return", _context3.sent);
3611
- case 5:
3612
- case "end":
3613
- return _context3.stop();
3614
- }
3615
- }, _callee3);
3616
- }));
3617
- return function (_x6, _x7) {
3618
- return _ref3.apply(this, arguments);
3619
- };
3620
- }();
3621
- _this.linkUser = /*#__PURE__*/function () {
3622
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, init) {
3623
- var _requester, _init;
3624
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3625
- while (1) switch (_context4.prev = _context4.next) {
3626
- case 0:
3627
- _requester = new Requester(_this);
3628
- _init = _this.handleHeaders(init);
3629
- _context4.next = 4;
3630
- return _requester.put(req, _this.tenantUsersUrl, _init);
3631
- case 4:
3632
- return _context4.abrupt("return", _context4.sent);
3633
- case 5:
3634
- case "end":
3635
- return _context4.stop();
3636
- }
3637
- }, _callee4);
3638
- }));
3639
- return function (_x8, _x9) {
3640
- return _ref4.apply(this, arguments);
3641
- };
3642
- }();
3643
- _this.tenantUsersDeleteUrl = function (userId) {
3644
- var _this$tenantId;
3645
- return "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/users/" + (userId != null ? userId : '{userId}');
3646
- };
3647
- _this.getUserId = /*#__PURE__*/function () {
3648
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req) {
3649
- var body;
3650
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
3651
- while (1) switch (_context5.prev = _context5.next) {
3652
- case 0:
3653
- if (!(req instanceof Request)) {
3654
- _context5.next = 6;
3655
- break;
3656
- }
3657
- _context5.next = 3;
3658
- return new Response(req == null ? void 0 : req.body).json();
3659
- case 3:
3660
- body = _context5.sent;
3661
- if (!body) {
3662
- _context5.next = 6;
3663
- break;
3664
- }
3665
- return _context5.abrupt("return", body.id);
3666
- case 6:
3667
- if (!('id' in req)) {
3668
- _context5.next = 8;
3669
- break;
3670
- }
3671
- return _context5.abrupt("return", req.id);
3672
- case 8:
3673
- return _context5.abrupt("return", null);
3674
- case 9:
3675
- case "end":
3676
- return _context5.stop();
3677
- }
3678
- }, _callee5);
3679
- }));
3680
- return function (_x10) {
3681
- return _ref5.apply(this, arguments);
3682
- };
3683
- }();
3684
- _this.unlinkUser = /*#__PURE__*/function () {
3685
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, init) {
3686
- var _requester, userId, _init;
3687
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
3688
- while (1) switch (_context6.prev = _context6.next) {
3689
- case 0:
3690
- _requester = new Requester(_this);
3691
- _context6.next = 3;
3692
- return _this.getUserId(req);
3693
- case 3:
3694
- userId = _context6.sent;
3695
- _init = _this.handleHeaders(init);
3696
- _context6.next = 7;
3697
- return _requester["delete"](req, _this.tenantUsersDeleteUrl(userId), _init);
3698
- case 7:
3699
- return _context6.abrupt("return", _context6.sent);
3700
- case 8:
3701
- case "end":
3702
- return _context6.stop();
3703
- }
3704
- }, _callee6);
3705
- }));
3706
- return function (_x11, _x12) {
3707
- return _ref6.apply(this, arguments);
3708
- };
3709
- }();
3710
- _this.me = /*#__PURE__*/function () {
3711
- var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(req, init) {
3712
- var _requester, _init;
3713
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
3714
- while (1) switch (_context7.prev = _context7.next) {
3715
- case 0:
3716
- _requester = new Requester(_this);
3717
- _init = _this.handleHeaders(init);
3718
- _context7.next = 4;
3719
- return _requester.get(req, _this.meUrl, _init);
3720
- case 4:
3721
- return _context7.abrupt("return", _context7.sent);
3722
- case 5:
3723
- case "end":
3724
- return _context7.stop();
3725
- }
3726
- }, _callee7);
3727
- }));
3728
- return function (_x13, _x14) {
3729
- return _ref7.apply(this, arguments);
3730
- };
3731
- }();
3732
- _this.headers = headers;
3733
- return _this;
3734
- }
3735
- _inheritsLoose(Users, _Config);
3736
- var _proto = Users.prototype;
3737
- _proto.handleHeaders = function handleHeaders(init) {
3738
- if (this.headers) {
3739
- if (init) {
3740
- var _init2;
3741
- init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
3742
- return init;
3743
- } else {
3744
- init = {
3745
- headers: this.headers
3746
- };
3747
- return init;
3748
- }
3749
- }
3750
- return undefined;
3751
- };
3752
- return _createClass(Users, [{
3753
- key: "usersUrl",
3754
- get: function get() {
3755
- return '/users';
3756
- }
3757
- }, {
3758
- key: "tenantUsersUrl",
3759
- get: function get() {
3760
- var _this$tenantId2;
3761
- return "/tenants/" + ((_this$tenantId2 = this.tenantId) != null ? _this$tenantId2 : '{tenantId}') + "/users";
3762
- }
3763
- }, {
3764
- key: "meUrl",
3765
- get: function get() {
3766
- return '/me';
3767
- }
3768
- }]);
3769
- }(Config);
3770
-
3771
- var Api = /*#__PURE__*/function () {
3772
- function Api(config) {
3773
- this.config = void 0;
3774
- this.users = void 0;
3775
- this.tenants = void 0;
3776
- this.routes = void 0;
3777
- this.handlers = void 0;
3778
- this.config = config;
3779
- this.users = new Users(config);
3780
- this.tenants = new Tenants(config);
3781
- this.routes = _extends({}, appRoutes(config == null ? void 0 : config.routePrefix), config == null ? void 0 : config.routes);
3782
- this.handlers = Handlers(this.routes, config);
3783
- }
3784
- var _proto = Api.prototype;
3785
- _proto.login = /*#__PURE__*/function () {
3786
- var _login = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(payload) {
3787
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3788
- while (1) switch (_context.prev = _context.next) {
3789
- case 0:
3790
- _context.next = 2;
3791
- return serverAuth(this.config, this.handlers)(payload);
3792
- case 2:
3793
- this.headers = _context.sent;
3794
- case 3:
3795
- case "end":
3796
- return _context.stop();
3797
- }
3798
- }, _callee, this);
3799
- }));
3800
- function login(_x) {
3801
- return _login.apply(this, arguments);
3802
- }
3803
- return login;
3804
- }();
3805
- return _createClass(Api, [{
3806
- key: "headers",
3807
- set: function set(headers) {
3808
- this.users = new Users(this.config, headers);
3809
- this.tenants = new Tenants(this.config, headers);
3810
- }
3811
- }]);
3812
- }();
3813
-
3814
- var Server = /*#__PURE__*/function () {
3815
- function Server(config) {
3816
- var _this = this;
3817
- this.config = void 0;
3818
- this.api = void 0;
3819
- this.manager = void 0;
3820
- this.servers = void 0;
3821
- this.config = new Config(config, '[initial config]');
3822
- this.servers = new Map();
3823
- this.api = new Api(this.config);
3824
- this.manager = new DBManager(this.config);
3825
- watchTenantId(function (tenantId) {
3826
- _this.tenantId = tenantId;
3827
- });
3828
- watchUserId(function (userId) {
3829
- _this.userId = userId;
3830
- });
3831
- watchToken(function (token) {
3832
- _this.token = token;
3833
- });
3834
- }
3835
- var _proto = Server.prototype;
3836
- _proto.setConfig = function setConfig(cfg) {
3837
- this.config = new Config(cfg);
3838
- };
3839
- _proto.init = /*#__PURE__*/function () {
3840
- var _init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cfg) {
3841
- var updatedConfig;
3842
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3843
- while (1) switch (_context.prev = _context.next) {
3844
- case 0:
3845
- _context.next = 2;
3846
- return this.config.configure(_extends({}, this.config, cfg));
3847
- case 2:
3848
- updatedConfig = _context.sent;
3849
- this.setConfig(updatedConfig);
3850
- this.manager.clear(this.config);
3851
- this.manager = new DBManager(this.config);
3852
- this.api = new Api(this.config);
3853
- return _context.abrupt("return", this);
3854
- case 8:
3855
- case "end":
3856
- return _context.stop();
3857
- }
3858
- }, _callee, this);
3859
- }));
3860
- function init(_x) {
3861
- return _init.apply(this, arguments);
3862
- }
3863
- return init;
3864
- }();
3865
- /**
3866
- * A utility function if you want to manage different NileDB instances yourself
3867
- * returns the global Server object, an existing server that's already been configured,
3868
- * or a new one if the config isn't in the cache
3869
- */
3870
- _proto.getInstance = function getInstance(config) {
3871
- var _config = _extends({}, this.config, config);
3872
- var serverId = getServerId(_config);
3873
- var currentServerId = makeServerId(this.config);
3874
- if (serverId === currentServerId) {
3875
- return this;
3876
- }
3877
- var existing = this.servers.get(serverId);
3878
- if (existing) {
3879
- // be sure the config is up to date
3880
- var updatedConfig = new Config(_config);
3881
- existing.setConfig(updatedConfig);
3882
- // propagate special config items
3883
- existing.tenantId = updatedConfig.tenantId;
3884
- existing.userId = updatedConfig.userId;
3885
- existing.token = updatedConfig.api.token;
3886
- existing.databaseId = updatedConfig.databaseId;
3887
- return existing;
3888
- }
3889
- var newServer = new Server(_config);
3890
- this.servers.set(serverId, newServer);
3891
- return newServer;
3892
- };
3893
- return _createClass(Server, [{
3894
- key: "databaseId",
3895
- set: function set(val) {
3896
- if (val) {
3897
- this.config.databaseId = val;
3898
- this.api.users.databaseId = val;
3899
- this.api.tenants.databaseId = val;
3900
- }
3901
- }
3902
- }, {
3903
- key: "userId",
3904
- get: function get() {
3905
- return this.config.userId;
3906
- },
3907
- set: function set(userId) {
3908
- this.databaseId = this.config.databaseId;
3909
- this.config.userId = userId;
3910
- if (this.api) {
3911
- this.api.users.userId = this.config.userId;
3912
- this.api.tenants.userId = this.config.userId;
3913
- }
3914
- }
3915
- }, {
3916
- key: "tenantId",
3917
- get: function get() {
3918
- return this.config.tenantId;
3919
- },
3920
- set: function set(tenantId) {
3921
- this.databaseId = this.config.databaseId;
3922
- this.config.tenantId = tenantId;
3923
- if (this.api) {
3924
- this.api.users.tenantId = tenantId;
3925
- this.api.tenants.tenantId = tenantId;
3926
- }
3927
- }
3928
- }, {
3929
- key: "token",
3930
- get: function get() {
3931
- var _this$config;
3932
- return (_this$config = this.config) == null || (_this$config = _this$config.api) == null ? void 0 : _this$config.token;
3933
- },
3934
- set: function set(token) {
3935
- if (token) {
3936
- this.config.api.token = token;
3937
- if (this.api) {
3938
- this.api.users.api.token = token;
3939
- this.api.tenants.api.token = token;
3940
- }
3941
- }
3942
- }
3943
- }, {
3944
- key: "db",
3945
- get: function get() {
3946
- return this.manager.getConnection(this.config);
3947
- }
3948
- }]);
3949
- }();
3950
- function create(_x2) {
3951
- return _create.apply(this, arguments);
3952
- }
3953
- function _create() {
3954
- _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(config) {
3955
- var server;
3956
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3957
- while (1) switch (_context2.prev = _context2.next) {
3958
- case 0:
3959
- server = new Server(config);
3960
- _context2.next = 3;
3961
- return server.init();
3962
- case 3:
3963
- return _context2.abrupt("return", _context2.sent);
3964
- case 4:
3965
- case "end":
3966
- return _context2.stop();
3967
- }
3968
- }, _callee2);
3969
- }));
3970
- return _create.apply(this, arguments);
3971
- }
3972
-
3973
- exports.Nile = create;
3974
- exports.Server = Server;
3975
- exports.default = create;
3976
- //# sourceMappingURL=server.cjs.development.js.map