@niledatabase/server 3.0.0-alpha.43 → 3.0.0-alpha.45

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